@zibby/skills 0.1.68 → 0.1.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,27 +1,27 @@
1
- import{registerSkill as N}from"@zibby/agent-workflow";import{createRequire as Cs}from"module";import{join as Ps}from"path";var Us=Cs(import.meta.url);function qs(){if(process.env.MCP_BROWSER_PATH)return process.env.MCP_BROWSER_PATH;try{return Us.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js")}catch{return null}}var Ds="1280x720",Js="1280x720";function Ms({headless:s}={}){if(s===!0)return!0;if(s===!1)return!1;let t=process.env.ZIBBY_HEADLESS;return t==="1"||String(t).toLowerCase()==="true"}function Bs(s,t){let e=(s||[]).filter(r=>r!=="--headless");return t?[...e,"--headless"]:e}var Tt={id:"browser",serverName:"playwright",cursorKey:"playwright-official",allowedTools:["mcp__playwright__*"],sessionEnvKey:"ZIBBY_SESSION_INFO",description:"Playwright Browser MCP Server",envKeys:[],tools:[],promptFragment:`Execute this test using the browser tools available to you. You MUST make actual browser tool calls \u2014 do not fabricate results.
1
+ import{registerSkill as N}from"@zibby/agent-workflow";import{createRequire as Ws}from"module";import{join as Zs}from"path";var Vs=Ws(import.meta.url);function Qs(){if(process.env.MCP_BROWSER_PATH)return process.env.MCP_BROWSER_PATH;try{return Vs.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js")}catch{return null}}var Xs="1280x720",en="1280x720";function tn({headless:s}={}){if(s===!0)return!0;if(s===!1)return!1;let t=process.env.ZIBBY_HEADLESS;return t==="1"||String(t).toLowerCase()==="true"}function rn(s,t){let e=(s||[]).filter(r=>r!=="--headless");return t?[...e,"--headless"]:e}var Pt={id:"browser",serverName:"playwright",cursorKey:"playwright-official",allowedTools:["mcp__playwright__*"],sessionEnvKey:"ZIBBY_SESSION_INFO",description:"Playwright Browser MCP Server",envKeys:[],tools:[],promptFragment:`Execute this test using the browser tools available to you. You MUST make actual browser tool calls \u2014 do not fabricate results.
2
2
  If you DO NOT have access to browser tools \u2192 return {"success": false, "steps": [], "browserClosed": false, "notes": "No browser tools available"}.
3
- DO NOT return success: true unless you ACTUALLY called browser tools.`,resolve({sessionPath:s,workspace:t,nodeName:e,headless:r}={}){let i=qs(),n=s&&e?Ps(s,e):null,o=n||s||t||"test-results",c=Ms({headless:r}),a={};if(n&&(a.ZIBBY_NODE_SESSION_PATH=n),s&&(a.ZIBBY_SESSION_PATH=s),!i)throw new Error(`@zibby/mcp-browser is not installed.
3
+ DO NOT return success: true unless you ACTUALLY called browser tools.`,resolve({sessionPath:s,workspace:t,nodeName:e,headless:r}={}){let n=Qs(),i=s&&e?Zs(s,e):null,o=i||s||t||"test-results",a=tn({headless:r}),c={};if(i&&(c.ZIBBY_NODE_SESSION_PATH=i),s&&(c.ZIBBY_SESSION_PATH=s),!n)throw new Error(`@zibby/mcp-browser is not installed.
4
4
  Cloud: verify the Fargate image has it (packages/Dockerfile installs it globally alongside @zibby/cli).
5
5
  Local: \`npm install @zibby/mcp-browser\` in your workflow, or use the global @zibby/cli install (which pulls it transitively).
6
- Override: set MCP_BROWSER_PATH to the path of mcp-browser-zibby.js.`);return{command:"node",args:Bs([i,"--isolated",`--save-video=${Ds}`,`--viewport-size=${Js}`,`--output-dir=${o}`],c),env:a}}};import{createRequire as Gs}from"module";import{resolveIntegrationToken as Fs,clearTokenCache as Hs}from"@zibby/core/backend-client.js";var I=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",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Ks=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"},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 zs=Gs(import.meta.url);function Ys(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return zs.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var Ws=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Zs(s,t){if(!t||!t.length)return s;let e=s;for(let r of t)r.type==="strong"?e=`**${e}**`:r.type==="em"?e=`_${e}_`:r.type==="code"?e=`\`${e}\``:r.type==="strike"?e=`~~${e}~~`:r.type==="link"&&r.attrs?.href&&(e=`[${e}](${r.attrs.href})`);return e}function Oe(s,t=0){if(!Array.isArray(s))return"";let e=[];for(let r of s){if(r.type==="text"){e.push(Zs(r.text||"",r.marks));continue}if(r.type==="hardBreak"){e.push(`
6
+ Override: set MCP_BROWSER_PATH to the path of mcp-browser-zibby.js.`);return{command:"node",args:rn([n,"--isolated",`--save-video=${Xs}`,`--viewport-size=${en}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as nn}from"module";import{resolveIntegrationToken as on,clearTokenCache as an}from"@zibby/core/backend-client.js";var v=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",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),sn=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"},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 cn=nn(import.meta.url);function ln(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return cn.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var dn=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function un(s,t){if(!t||!t.length)return s;let e=s;for(let r of t)r.type==="strong"?e=`**${e}**`:r.type==="em"?e=`_${e}_`:r.type==="code"?e=`\`${e}\``:r.type==="strike"?e=`~~${e}~~`:r.type==="link"&&r.attrs?.href&&(e=`[${e}](${r.attrs.href})`);return e}function Le(s,t=0){if(!Array.isArray(s))return"";let e=[];for(let r of s){if(r.type==="text"){e.push(un(r.text||"",r.marks));continue}if(r.type==="hardBreak"){e.push(`
7
7
  `);continue}if(r.type==="rule"){e.push(`
8
8
  ---
9
- `);continue}let i=r.content?Oe(r.content,t+1):"";if(r.type==="listItem")e.push(i);else if(r.type==="bulletList"){let n=(r.content||[]).map(o=>`- ${Oe(o.content||[],t+1).trim()}`);e.push(`
10
- ${n.join(`
9
+ `);continue}let n=r.content?Le(r.content,t+1):"";if(r.type==="listItem")e.push(n);else if(r.type==="bulletList"){let i=(r.content||[]).map(o=>`- ${Le(o.content||[],t+1).trim()}`);e.push(`
10
+ ${i.join(`
11
11
  `)}
12
- `)}else if(r.type==="orderedList"){let n=(r.content||[]).map((o,c)=>`${c+1}. ${Oe(o.content||[],t+1).trim()}`);e.push(`
13
- ${n.join(`
12
+ `)}else if(r.type==="orderedList"){let i=(r.content||[]).map((o,a)=>`${a+1}. ${Le(o.content||[],t+1).trim()}`);e.push(`
13
+ ${i.join(`
14
14
  `)}
15
- `)}else if(r.type==="heading"){let n=r.attrs?.level||2;e.push(`
15
+ `)}else if(r.type==="heading"){let i=r.attrs?.level||2;e.push(`
16
16
 
17
- ${"#".repeat(n)} ${i.trim()}
17
+ ${"#".repeat(i)} ${n.trim()}
18
18
 
19
- `)}else Ws.has(r.type)?e.push(`
19
+ `)}else dn.has(r.type)?e.push(`
20
20
 
21
- ${i}
22
- `):e.push(i)}return e.join("").replace(/\n{3,}/g,`
21
+ ${n}
22
+ `):e.push(n)}return e.join("").replace(/\n{3,}/g,`
23
23
 
24
- `)}function oe(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ze(s){return oe(s).replace(/[a-z0-9]+/g,"")}function Re(s,t){let e=oe(s),r=oe(t);if(!e||!r)return 0;if(e===r)return 1;if(e.length===1||r.length===1)return e===r?1:0;let i=l=>{let u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},n=i(e),o=i(r),c=0,a=0,d=0;for(let l of n.values())a+=l;for(let l of o.values())d+=l;for(let[l,u]of n.entries()){let p=o.get(l)||0;c+=Math.min(u,p)}return 2*c/Math.max(1,a+d)}function Z(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Vs(s,t=[]){let e=Array.isArray(t)?t:[];if(e.length===0)return{requested:s||null,resolved:null,strategy:"none"};let r=e.filter(c=>!c.subtask),i=r.length>0?r:e,n=Z(s);if(n){let c=i.find(l=>Z(l.name)===n);if(c)return{requested:s,resolved:c,strategy:"exact"};let a={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(a)){if(!l.some(p=>Z(p)===n))continue;let u=i.find(p=>l.some(m=>Z(m)===Z(p.name)));if(u)return{requested:s,resolved:u,strategy:"alias"}}let d=i.map(l=>({t:l,score:Re(s,l.name)})).sort((l,u)=>u.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:s,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let c of o){let a=i.find(d=>Z(d.name)===c);if(a)return{requested:s||null,resolved:a,strategy:"default-preferred"}}return{requested:s||null,resolved:i[0],strategy:"default-first"}}async function At(s){let t=`projectKeys=${encodeURIComponent(s)}&expand=projects.issuetypes`,e=await E(`/rest/api/3/issue/createmeta?${t}`),r=Array.isArray(e?.projects)?e.projects:[],n=r.find(c=>String(c?.key||"").toUpperCase()===String(s||"").toUpperCase())||r[0]||null;return(Array.isArray(n?.issuetypes)?n.issuetypes:[]).map(c=>({id:c.id,name:c.name,subtask:!!c.subtask,description:c.description||null}))}async function Et(s,t){if(!s)throw new Error("projectKey is required");let e="sprint is not EMPTY";t==="active"?e="sprint in openSprints()":t==="closed"?e="sprint in closedSprints()":t==="future"&&(e="sprint in futureSprints()");let r=`project = ${s} AND ${e} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(r)}&maxResults=100&fields=customfield_10020`,n=await E(`/rest/api/3/search/jql?${i}`),o=new Map;for(let c of n.issues||[])for(let a of c.fields?.customfield_10020||[])a&&!o.has(a.id)&&o.set(a.id,{id:a.id,name:a.name,state:a.state,boardId:a.boardId||null,startDate:a.startDate||null,endDate:a.endDate||null,goal:a.goal||null});return[...o.values()].sort((c,a)=>{let d={active:0,future:1,closed:2},l=(d[c.state]??3)-(d[a.state]??3);return l!==0?l:String(a.startDate||"").localeCompare(String(c.startDate||""))})}function Qs(s,{sprintId:t,sprintName:e,target:r}={}){let i=Array.isArray(s)?s:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(t!=null&&String(t).trim()!=="")return{sprint:i.find(c=>String(c.id)===String(t))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),c=i.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(c)return{sprint:c,selectedBy:"name-exact"};let a=i.map(d=>({s:d,score:Re(o,d.name||"")})).sort((d,l)=>l.score-d.score);return a[0]&&a[0].score>=.5?{sprint:a[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let n=String(r||"current").trim().toLowerCase();return n==="active"||n==="current"||n==="latest"?{sprint:i[0],selectedBy:n}:{sprint:i[0],selectedBy:"default"}}function Xs(s,t){let e=s?.fields?.customfield_10020;return Array.isArray(e)?e.some(r=>String(r?.id)===String(t)):!1}async function ei({issueKey:s,projectKey:t,sprintId:e,attempts:r=3,delayMs:i=450}){let n=[];for(let o=0;o<r;o++){try{let c=`project = ${t} AND key = ${s} AND sprint = ${e}`,a=`jql=${encodeURIComponent(c)}&maxResults=1&fields=key,status`,d=await E(`/rest/api/3/search/jql?${a}`);if(Number(d?.total||0)>0)return n.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:n};let u=await E(`/rest/api/3/issue/${s}?fields=customfield_10020,status`),p=Xs(u,e);if(n.push({attempt:o+1,jql:!1,issueField:p}),p)return{ok:!0,method:"issue_field",traces:n}}catch(c){n.push({attempt:o+1,error:String(c?.message||c)})}o<r-1&&await new Promise(c=>setTimeout(c,i))}return{ok:!1,method:"none",traces:n}}async function Ve({issueKey:s,projectKey:t,sprintId:e,sprintName:r,target:i}){if(!s)return{ok:!1,error:"issueKey is required"};let n=t;if(!n&&(n=(await E(`/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 Et(n,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${n}`};let{sprint:c,selectedBy:a}=Qs(o,{sprintId:e,sprintName:r,target:i});if(!c)return{ok:!1,error:`No matching sprint found in ${n}`,requested:{sprintId:e??null,sprintName:r??null,target:i??"current"},availableSprints:o.map(u=>({id:u.id,name:u.name,state:u.state}))};await E(`/rest/api/3/issue/${s}`,{method:"PUT",body:{fields:{customfield_10020:Number(c.id)}}});let d=await ei({issueKey:s,projectKey:n,sprintId:c.id}),l=d.ok;return{ok:l,issueKey:s,projectKey:n,sprintId:c.id,sprintName:c.name,selectedBy:a,verifiedBy:d.method,verified:l,verificationTrace:d.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${s} in sprint ${c.id}`}}async function E(s,t={}){let e=async()=>{let{token:r,cloudId:i}=await Fs("jira");if(typeof r!="string"||!r)throw new Error(`Invalid jira token type: ${typeof r}`);if(!i)throw new Error("Invalid jira cloudId: missing");let n=`https://api.atlassian.com/ex/jira/${i}${s}`,o=await fetch(n,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${a.slice(0,300)}`)}let c=await o.text().catch(()=>"");if(!c||!c.trim())return{};try{return JSON.parse(c)}catch{return{raw:c}}};try{return await e()}catch(r){let i=String(r?.message||r||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw r;return Hs("jira"),e()}}var jt={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:I.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
24
+ `)}function ae(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function st(s){return ae(s).replace(/[a-z0-9]+/g,"")}function xe(s,t){let e=ae(s),r=ae(t);if(!e||!r)return 0;if(e===r)return 1;if(e.length===1||r.length===1)return e===r?1:0;let n=l=>{let u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},i=n(e),o=n(r),a=0,c=0,d=0;for(let l of i.values())c+=l;for(let l of o.values())d+=l;for(let[l,u]of i.entries()){let p=o.get(l)||0;a+=Math.min(u,p)}return 2*a/Math.max(1,c+d)}function Z(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function pn(s,t=[]){let e=Array.isArray(t)?t:[];if(e.length===0)return{requested:s||null,resolved:null,strategy:"none"};let r=e.filter(a=>!a.subtask),n=r.length>0?r:e,i=Z(s);if(i){let a=n.find(l=>Z(l.name)===i);if(a)return{requested:s,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(p=>Z(p)===i))continue;let u=n.find(p=>l.some(m=>Z(m)===Z(p.name)));if(u)return{requested:s,resolved:u,strategy:"alias"}}let d=n.map(l=>({t:l,score:xe(s,l.name)})).sort((l,u)=>u.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:s,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=n.find(d=>Z(d.name)===a);if(c)return{requested:s||null,resolved:c,strategy:"default-preferred"}}return{requested:s||null,resolved:n[0],strategy:"default-first"}}async function Ut(s){let t=`projectKeys=${encodeURIComponent(s)}&expand=projects.issuetypes`,e=await E(`/rest/api/3/issue/createmeta?${t}`),r=Array.isArray(e?.projects)?e.projects:[],i=r.find(a=>String(a?.key||"").toUpperCase()===String(s||"").toUpperCase())||r[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 qt(s,t){if(!s)throw new Error("projectKey is required");let e="sprint is not EMPTY";t==="active"?e="sprint in openSprints()":t==="closed"?e="sprint in closedSprints()":t==="future"&&(e="sprint in futureSprints()");let r=`project = ${s} AND ${e} ORDER BY updated DESC`,n=`jql=${encodeURIComponent(r)}&maxResults=100&fields=customfield_10020`,i=await E(`/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 d={active:0,future:1,closed:2},l=(d[a.state]??3)-(d[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function mn(s,{sprintId:t,sprintName:e,target:r}={}){let n=Array.isArray(s)?s:[];if(!n.length)return{sprint:null,selectedBy:"none"};if(t!=null&&String(t).trim()!=="")return{sprint:n.find(a=>String(a.id)===String(t))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),a=n.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=n.map(d=>({s:d,score:xe(o,d.name||"")})).sort((d,l)=>l.score-d.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let i=String(r||"current").trim().toLowerCase();return i==="active"||i==="current"||i==="latest"?{sprint:n[0],selectedBy:i}:{sprint:n[0],selectedBy:"default"}}function fn(s,t){let e=s?.fields?.customfield_10020;return Array.isArray(e)?e.some(r=>String(r?.id)===String(t)):!1}async function hn({issueKey:s,projectKey:t,sprintId:e,attempts:r=3,delayMs:n=450}){let i=[];for(let o=0;o<r;o++){try{let a=`project = ${t} AND key = ${s} AND sprint = ${e}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,d=await E(`/rest/api/3/search/jql?${c}`);if(Number(d?.total||0)>0)return i.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:i};let u=await E(`/rest/api/3/issue/${s}?fields=customfield_10020,status`),p=fn(u,e);if(i.push({attempt:o+1,jql:!1,issueField:p}),p)return{ok:!0,method:"issue_field",traces:i}}catch(a){i.push({attempt:o+1,error:String(a?.message||a)})}o<r-1&&await new Promise(a=>setTimeout(a,n))}return{ok:!1,method:"none",traces:i}}async function nt({issueKey:s,projectKey:t,sprintId:e,sprintName:r,target:n}){if(!s)return{ok:!1,error:"issueKey is required"};let i=t;if(!i&&(i=(await E(`/rest/api/3/issue/${s}?fields=project`))?.fields?.project?.key||null,!i))return{ok:!1,error:`Could not resolve project for ${s}`};let o=await qt(i,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${i}`};let{sprint:a,selectedBy:c}=mn(o,{sprintId:e,sprintName:r,target:n});if(!a)return{ok:!1,error:`No matching sprint found in ${i}`,requested:{sprintId:e??null,sprintName:r??null,target:n??"current"},availableSprints:o.map(u=>({id:u.id,name:u.name,state:u.state}))};await E(`/rest/api/3/issue/${s}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await hn({issueKey:s,projectKey:i,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:s,projectKey:i,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:d.method,verified:l,verificationTrace:d.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${s} in sprint ${a.id}`}}async function E(s,t={}){let e=async()=>{let{token:r,cloudId:n}=await on("jira");if(typeof r!="string"||!r)throw new Error(`Invalid jira token type: ${typeof r}`);if(!n)throw new Error("Invalid jira cloudId: missing");let i=`https://api.atlassian.com/ex/jira/${n}${s}`,o=await fetch(i,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.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(r){let n=String(r?.message||r||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("403")||n.includes("substring")))throw r;return an("jira"),e()}}var Dt={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:v.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
25
25
  You have direct access to the user's Jira. Use these tools proactively:
26
26
 
27
27
  ### Issue tools
@@ -71,7 +71,7 @@ When user asks to move/transition ticket status:
71
71
  3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
72
72
  4. Call jira_get_issue(issueKey) to verify final status before claiming success.
73
73
  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.
74
- 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let s=Ys();if(!s)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return process.env.ATLASSIAN_INSTANCE_URL&&(t.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{command:"node",args:[s],env:t,description:this.description}},async handleToolCall(s,t){try{switch(s){case"jira_list_projects":{let e=await E("/rest/api/3/project"),r=(Array.isArray(e)?e:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:r.length,projects:r})}case"jira_list_statuses":{let{projectKey:e}=t||{};if(e){let n=await E(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(n)?n:[],c=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(c.has(l.id)||c.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let a=[...c.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:e,count:a.length,statuses:a})}let r=await E("/rest/api/3/status"),i=(Array.isArray(r)?r:[]).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:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:e}=t||{};if(!e)return JSON.stringify({error:"projectKey is required"});let r=await At(e);return JSON.stringify({projectKey:e,count:r.length,issueTypes:r})}case"jira_search":{let e=t.jql||"",r=t.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let n=`jql=${encodeURIComponent(e)}&maxResults=${r}&fields=summary,status,assignee,priority,updated,issuetype,project`,c=((await E(`/rest/api/3/search/jql?${n}`)).issues||[]).map(a=>({key:a.key,project:a.fields?.project?.key,summary:a.fields?.summary,status:a.fields?.status?.name,assignee:a.fields?.assignee?.displayName||"Unassigned",priority:a.fields?.priority?.name,type:a.fields?.issuetype?.name}));return JSON.stringify({count:c.length,issues:c})}case"jira_get_issue":{let e=t.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let r=await E(`/rest/api/3/issue/${e}`);return JSON.stringify({key:r.key,project:r.fields?.project?.key,summary:r.fields?.summary,description:r.fields?.description,status:r.fields?.status?.name,assignee:r.fields?.assignee?.displayName||"Unassigned",priority:r.fields?.priority?.name,type:r.fields?.issuetype?.name,labels:r.fields?.labels,created:r.fields?.created,updated:r.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:r,issueType:i,description:n,priority:o,labels:c,assigneeId:a,moveToSprint:d,moveToActiveSprint:l,sprintId:u,sprintName:p,target:m}=t;if(!e||!r)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await At(e),f=Vs(i,h)}catch{}let _={project:{key:e},summary:r,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};n&&(_.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}),o&&(_.priority={name:o}),c?.length&&(_.labels=c),a&&(_.assignee={id:a});let g=await E("/rest/api/3/issue",{method:"POST",body:{fields:_}}),b={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&Z(f.requested)!==Z(f.resolved.name)&&(b.issueTypeWarning=`Requested "${f.requested}" is not available in ${e}; used "${f.resolved.name}" instead.`)),h.length>0&&(b.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(b.sprintMove=await Ve({issueKey:g.key,projectKey:e,sprintId:u,sprintName:p,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:e,state:r}=t,i=await Et(e,r);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o}=t||{},c=await Ve({issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o||"current"});return JSON.stringify(c)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o}=t||{},c=await Ve({issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o});return JSON.stringify(c)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:r,projectKey:i,status:n,maxResults:o}=t;if(!e&&!r)return JSON.stringify({error:"sprintName or sprintId is required"});let c=o||50,a=r?`sprint = ${r}`:`sprint = "${e}"`,d=i?`project = ${i} AND `:"",l=n?` AND status = "${n}"`:"",u=`${d}${a}${l} ORDER BY status ASC, priority DESC`,p=`jql=${encodeURIComponent(u)}&maxResults=${c}&fields=summary,status,assignee,priority,issuetype,project`,m=await E(`/rest/api/3/search/jql?${p}`),f=(m.issues||[]).map(_=>({key:_.key,project:_.fields?.project?.key,summary:_.fields?.summary,status:_.fields?.status?.name,assignee:_.fields?.assignee?.displayName||"Unassigned",priority:_.fields?.priority?.name,type:_.fields?.issuetype?.name})),h={};for(let _ of f)h[_.status]=(h[_.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:e,maxResults:r}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let n=await E(`/rest/api/3/issue/${e}/comment?maxResults=${r||50}&orderBy=-created`),o=(n.comments||[]).map(c=>{let a="";return c.body?.content&&(a=Oe(c.body.content)),{id:c.id,author:c.author?.displayName||"Unknown",body:a,created:c.created,updated:c.updated}});return JSON.stringify({count:o.length,total:n.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:r}=t;return!e||!r?JSON.stringify({error:"issueKey and body are required"}):(await E(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:r}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:r}=t;return!e||!r?JSON.stringify({error:"issueKey and fields are required"}):(await E(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:r}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:r,toStatus:i,statusName:n,status:o}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let c=String(i||n||o||"").trim();if(!r&&!c){let u=((await E(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(p=>({id:p.id,name:p.name,to:p.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:u})}let a=r;if(!a){let u=(await E(`/rest/api/3/issue/${e}/transitions`)).transitions||[],p=oe(c),m=u.find(f=>oe(f?.name||"")===p||oe(f?.to?.name||"")===p);if(!m){let f=Ze(c);f.length>=2&&(m=u.find(h=>{let _=Ze(h?.name||""),g=Ze(h?.to?.name||""),b=_.length>=2&&(_.includes(f)||f.includes(_)),y=g.length>=2&&(g.includes(f)||f.includes(g));return b||y}))}if(!m){let f=u.map(b=>{let y=Re(c,b?.name||""),k=Re(c,b?.to?.name||"");return{t:b,score:Math.max(y,k)}}).sort((b,y)=>y.score-b.score),h=f[0],_=f[1];h&&h.score>=.45&&(!_||h.score-_.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${c}"`,issueKey:e,availableTransitions:u.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});a=m.id}await E(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:a}}});let d=await E(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:a,statusAfter:d?.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"]}}]};import{existsSync as ti}from"fs";import{fileURLToPath as ri}from"url";import{dirname as si,resolve as ii}from"path";import{resolveIntegrationToken as Lt}from"@zibby/core/backend-client.js";function ni(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=si(ri(import.meta.url)),t=ii(s,"..","bin","mcp-skill.mjs");return ti(t)?t:null}async function v(s,t={}){let{token:e}=await Lt("github"),r=s.startsWith("https://")?s:`https://api.github.com${s}`,i={Authorization:`Bearer ${e}`,Accept:t.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...t.body?{"Content-Type":"application/json"}:{}},n=await fetch(r,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`GitHub API ${n.status}: ${o.slice(0,300)}`)}return t.raw?n.text():n.json()}var ae={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:I.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
74
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let s=ln();if(!s)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return process.env.ATLASSIAN_INSTANCE_URL&&(t.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{command:"node",args:[s],env:t,description:this.description}},async handleToolCall(s,t){try{switch(s){case"jira_list_projects":{let e=await E("/rest/api/3/project"),r=(Array.isArray(e)?e:[]).map(n=>({id:n.id,key:n.key,name:n.name,style:n.style}));return JSON.stringify({count:r.length,projects:r})}case"jira_list_statuses":{let{projectKey:e}=t||{};if(e){let i=await E(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(i)?i:[],a=new Map;for(let d of o)for(let l of d.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((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:e,count:c.length,statuses:c})}let r=await E("/rest/api/3/status"),n=(Array.isArray(r)?r:[]).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}=t||{};if(!e)return JSON.stringify({error:"projectKey is required"});let r=await Ut(e);return JSON.stringify({projectKey:e,count:r.length,issueTypes:r})}case"jira_search":{let e=t.jql||"",r=t.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let i=`jql=${encodeURIComponent(e)}&maxResults=${r}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await E(`/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=t.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let r=await E(`/rest/api/3/issue/${e}`);return JSON.stringify({key:r.key,project:r.fields?.project?.key,summary:r.fields?.summary,description:r.fields?.description,status:r.fields?.status?.name,assignee:r.fields?.assignee?.displayName||"Unassigned",priority:r.fields?.priority?.name,type:r.fields?.issuetype?.name,labels:r.fields?.labels,created:r.fields?.created,updated:r.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:r,issueType:n,description:i,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:u,sprintName:p,target:m}=t;if(!e||!r)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:n||null,resolved:null,strategy:"none"},h=[];try{h=await Ut(e),f=pn(n,h)}catch{}let _={project:{key:e},summary:r,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:n||"Task"}};i&&(_.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:i}]}]}),o&&(_.priority={name:o}),a?.length&&(_.labels=a),c&&(_.assignee={id:c});let g=await E("/rest/api/3/issue",{method:"POST",body:{fields:_}}),b={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&Z(f.requested)!==Z(f.resolved.name)&&(b.issueTypeWarning=`Requested "${f.requested}" is not available in ${e}; used "${f.resolved.name}" instead.`)),h.length>0&&(b.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(b.sprintMove=await nt({issueKey:g.key,projectKey:e,sprintId:u,sprintName:p,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:e,state:r}=t,n=await qt(e,r);return JSON.stringify({count:n.length,sprints:n})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:r,sprintId:n,sprintName:i,target:o}=t||{},a=await nt({issueKey:e,projectKey:r,sprintId:n,sprintName:i,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:r,sprintId:n,sprintName:i,target:o}=t||{},a=await nt({issueKey:e,projectKey:r,sprintId:n,sprintName:i,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:r,projectKey:n,status:i,maxResults:o}=t;if(!e&&!r)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=r?`sprint = ${r}`:`sprint = "${e}"`,d=n?`project = ${n} AND `:"",l=i?` AND status = "${i}"`:"",u=`${d}${c}${l} ORDER BY status ASC, priority DESC`,p=`jql=${encodeURIComponent(u)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await E(`/rest/api/3/search/jql?${p}`),f=(m.issues||[]).map(_=>({key:_.key,project:_.fields?.project?.key,summary:_.fields?.summary,status:_.fields?.status?.name,assignee:_.fields?.assignee?.displayName||"Unassigned",priority:_.fields?.priority?.name,type:_.fields?.issuetype?.name})),h={};for(let _ of f)h[_.status]=(h[_.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:e,maxResults:r}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let i=await E(`/rest/api/3/issue/${e}/comment?maxResults=${r||50}&orderBy=-created`),o=(i.comments||[]).map(a=>{let c="";return a.body?.content&&(c=Le(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:r}=t;return!e||!r?JSON.stringify({error:"issueKey and body are required"}):(await E(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:r}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:r}=t;return!e||!r?JSON.stringify({error:"issueKey and fields are required"}):(await E(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:r}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:r,toStatus:n,statusName:i,status:o}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(n||i||o||"").trim();if(!r&&!a){let u=((await E(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(p=>({id:p.id,name:p.name,to:p.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:u})}let c=r;if(!c){let u=(await E(`/rest/api/3/issue/${e}/transitions`)).transitions||[],p=ae(a),m=u.find(f=>ae(f?.name||"")===p||ae(f?.to?.name||"")===p);if(!m){let f=st(a);f.length>=2&&(m=u.find(h=>{let _=st(h?.name||""),g=st(h?.to?.name||""),b=_.length>=2&&(_.includes(f)||f.includes(_)),y=g.length>=2&&(g.includes(f)||f.includes(g));return b||y}))}if(!m){let f=u.map(b=>{let y=xe(a,b?.name||""),w=xe(a,b?.to?.name||"");return{t:b,score:Math.max(y,w)}}).sort((b,y)=>y.score-b.score),h=f[0],_=f[1];h&&h.score>=.45&&(!_||h.score-_.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:e,availableTransitions:u.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await E(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await E(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:d?.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"]}}]};import{existsSync as yn}from"fs";import{fileURLToPath as gn}from"url";import{dirname as _n,resolve as bn}from"path";import{resolveIntegrationToken as Jt}from"@zibby/core/backend-client.js";function kn(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=_n(gn(import.meta.url)),t=bn(s,"..","bin","mcp-skill.mjs");return yn(t)?t:null}async function I(s,t={}){let{token:e}=await Jt("github"),r=s.startsWith("https://")?s:`https://api.github.com${s}`,n={Authorization:`Bearer ${e}`,Accept:t.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...t.body?{"Content-Type":"application/json"}:{}},i=await fetch(r,{method:t.method||"GET",headers:n,body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`GitHub API ${i.status}: ${o.slice(0,300)}`)}return t.raw?i.text():i.json()}var ce={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:v.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
75
75
  You have access to the user's GitHub repositories. Available tools:
76
76
 
77
77
  ### Discovery
@@ -114,9 +114,9 @@ When user says "check out repo-name" or "clone repo-name":
114
114
  3. STOP. Do not offer to inspect files or ask what to do next.
115
115
 
116
116
  When user just wants to "look at" or "read" files (not clone):
117
- - Use github_get_file to read individual files via API`,resolve(){let s=ni();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/github.js","githubSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"github_search_issues":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let r=await v(`/search/issues?q=${encodeURIComponent(e)}&per_page=${t.limit||20}`),i=(r.items||[]).map(n=>({number:n.number,title:n.title,state:n.state,repo:n.repository_url?.split("/").slice(-2).join("/"),url:n.html_url,user:n.user?.login,isPR:!!n.pull_request,labels:(n.labels||[]).map(o=>o.name),createdAt:n.created_at}));return JSON.stringify({total:r.total_count,items:i})}case"github_search_code":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let r=t.repo?`+repo:${t.repo}`:"",i=t.language?`+language:${t.language}`:"",n=await v(`/search/code?q=${encodeURIComponent(e)}${r}${i}&per_page=${t.limit||15}`),o=(n.items||[]).map(c=>({name:c.name,path:c.path,repo:c.repository?.full_name,url:c.html_url,score:c.score}));return JSON.stringify({total:n.total_count,items:o})}case"github_get_pr":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}`);return JSON.stringify({number:n.number,title:n.title,state:n.state,merged:n.merged,body:n.body?.slice(0,5e3),user:n.user?.login,branch:n.head?.ref,headSha:n.head?.sha,base:n.base?.ref,changedFiles:n.changed_files,additions:n.additions,deletions:n.deletions,createdAt:n.created_at,mergedAt:n.merged_at,url:n.html_url,labels:(n.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=n.length>15e3;return JSON.stringify({number:i,diff:o?n.slice(0,15e3):n,truncated:o,totalLength:n.length})}case"github_list_pr_files":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:n.length,files:n.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:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}/comments?per_page=50`),o=await v(`/repos/${e}/${r}/issues/${i}/comments?per_page=50`),c=[...n.map(a=>({type:"review",user:a.user?.login,body:a.body?.slice(0,1e3),path:a.path,line:a.line,createdAt:a.created_at})),...o.map(a=>({type:"issue",user:a.user?.login,body:a.body?.slice(0,1e3),createdAt:a.created_at}))].sort((a,d)=>new Date(a.createdAt)-new Date(d.createdAt));return JSON.stringify({total:c.length,comments:c})}case"github_get_review_thread":{let{owner:e,repo:r,number:i,commentId:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await v(`/repos/${e}/${r}/pulls/comments/${n}`),c=o.in_reply_to_id||o.id,a=[];try{a=await v(`/repos/${e}/${r}/pulls/${i}/comments?per_page=100`)}catch{a=[o]}(!Array.isArray(a)||a.length===0)&&(a=[o]);let d=a.filter(p=>p.id===c||p.in_reply_to_id===c).sort((p,m)=>new Date(p.created_at)-new Date(m.created_at)),l=d.length?d:[o],u=l.find(p=>p.id===c)||l[0];return JSON.stringify({rootCommentId:c,path:u.path,line:u.line??u.original_line??null,side:u.side||"RIGHT",diffHunk:typeof u.diff_hunk=="string"?u.diff_hunk.slice(0,3e3):null,commitId:u.commit_id||u.original_commit_id||null,notes:l.map(p=>({id:p.id,user:p.user?.login,body:(p.body||"").slice(0,4e3),createdAt:p.created_at,isRoot:p.id===c,url:p.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:r,number:i,commentId:n,body:o}=t||{};if(!e||!r||!i||!n||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let c=await v(`/repos/${e}/${r}/pulls/${i}/comments/${n}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:c.id,url:c.html_url,inReplyTo:c.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:e,repo:r,number:i,body:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await v(`/repos/${e}/${r}/issues/${i}/comments`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:e,repo:r,number:i,body:n,event:o,comments:c}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(a))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let d=Array.isArray(c)?c.filter(p=>p&&p.path&&p.body&&(p.line!=null||p.position!=null)).map(p=>{let m={path:p.path,body:String(p.body)};return p.line!=null?(m.line=Number(p.line),m.side=p.side==="LEFT"?"LEFT":"RIGHT"):m.position=Number(p.position),m}):[];if(a!=="APPROVE"&&!n&&d.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l={event:a};n&&(l.body=String(n)),d.length>0&&(l.comments=d);let u=await v(`/repos/${e}/${r}/pulls/${i}/reviews`,{method:"POST",body:l});return JSON.stringify({ok:!0,id:u.id,state:u.state,event:a,commentsPosted:d.length,url:u.html_url})}case"github_list_commits":{let{owner:e,repo:r,branch:i,path:n,limit:o}=t;if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let c=`/repos/${e}/${r}/commits?per_page=${o||20}`;i&&(c+=`&sha=${encodeURIComponent(i)}`),n&&(c+=`&path=${encodeURIComponent(n)}`);let a=await v(c);return JSON.stringify({total:a.length,commits:a.map(d=>({sha:d.sha?.slice(0,8),fullSha:d.sha,message:d.commit?.message?.slice(0,300),author:d.commit?.author?.name,date:d.commit?.author?.date,url:d.html_url}))})}case"github_get_commit":{let{owner:e,repo:r,sha:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let n=await v(`/repos/${e}/${r}/commits/${i}`);return JSON.stringify({sha:n.sha?.slice(0,8),message:n.commit?.message,author:n.commit?.author?.name,date:n.commit?.author?.date,stats:n.stats,files:(n.files||[]).map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_get_file":{let{owner:e,repo:r,path:i,ref:n}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${r}/contents/${encodeURIComponent(i)}`;n&&(o+=`?ref=${encodeURIComponent(n)}`);let c=await v(o);if(c.type!=="file")return Array.isArray(c)?JSON.stringify({type:"directory",path:i,entries:c.map(l=>({name:l.name,type:l.type,size:l.size,path:l.path}))}):JSON.stringify({error:`Not a file: ${c.type}`});let a=Buffer.from(c.content||"","base64").toString("utf-8"),d=a.length>2e4;return JSON.stringify({path:c.path,size:c.size,sha:c.sha?.slice(0,8),content:d?a.slice(0,2e4):a,truncated:d})}case"github_get_user":try{let e=await v("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let r=e.repositories[0],i=r.owner.login,n=r.owner.type,o=n==="Organization"?`/orgs/${i}`:`/users/${i}`,c=await v(o);return JSON.stringify({login:c.login,name:c.name||c.login,avatar:c.avatar_url,bio:c.bio||c.description,type:n,isOrg:n==="Organization",publicRepos:c.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 r=(await v("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of r)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 n=Array.from(i.values());return JSON.stringify({count:n.length,orgs:n,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 f=function(g){let b=g.replace(/^~(?=$|\/|\\)/,m);return c(b)},{owner:e,repo:r,destination:i}=t;if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let{execSync:n}=await import("child_process"),{join:o,resolve:c}=await import("path"),{existsSync:a,mkdirSync:d}=await import("fs"),{homedir:l,platform:u}=await import("os"),{token:p}=await Lt("github"),m=l(),h=i?f(i):o(m,"zibby-repos"),_=o(h,r);if(d(h,{recursive:!0}),a(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});try{let g=`https://x-access-token:${p}@github.com/${e}/${r}.git`;n(`git clone ${g} "${_}"`,{stdio:"pipe"});let b=u()==="win32",y;return b?y=n(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):y=n(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${e}/${r} to ${_}`,contents:y.split(`
117
+ - Use github_get_file to read individual files via API`,resolve(){let s=kn();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/github.js","githubSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"github_search_issues":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let r=await I(`/search/issues?q=${encodeURIComponent(e)}&per_page=${t.limit||20}`),n=(r.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:r.total_count,items:n})}case"github_search_code":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let r=t.repo?`+repo:${t.repo}`:"",n=t.language?`+language:${t.language}`:"",i=await I(`/search/code?q=${encodeURIComponent(e)}${r}${n}&per_page=${t.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:r,number:n}=t;if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${e}/${r}/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:r,number:n}=t;if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${e}/${r}/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:r,number:n}=t;if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${e}/${r}/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:r,number:n}=t;if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${e}/${r}/pulls/${n}/comments?per_page=50`),o=await I(`/repos/${e}/${r}/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,d)=>new Date(c.createdAt)-new Date(d.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:r,number:n,commentId:i}=t||{};if(!e||!r||!n||!i)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await I(`/repos/${e}/${r}/pulls/comments/${i}`),a=o.in_reply_to_id||o.id,c=[];try{c=await I(`/repos/${e}/${r}/pulls/${n}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let d=c.filter(p=>p.id===a||p.in_reply_to_id===a).sort((p,m)=>new Date(p.created_at)-new Date(m.created_at)),l=d.length?d:[o],u=l.find(p=>p.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:u.path,line:u.line??u.original_line??null,side:u.side||"RIGHT",diffHunk:typeof u.diff_hunk=="string"?u.diff_hunk.slice(0,3e3):null,commitId:u.commit_id||u.original_commit_id||null,notes:l.map(p=>({id:p.id,user:p.user?.login,body:(p.body||"").slice(0,4e3),createdAt:p.created_at,isRoot:p.id===a,url:p.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:r,number:n,commentId:i,body:o}=t||{};if(!e||!r||!n||!i||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await I(`/repos/${e}/${r}/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:r,number:n,body:i}=t||{};if(!e||!r||!n||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await I(`/repos/${e}/${r}/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:r,number:n,body:i,event:o,comments:a}=t||{};if(!e||!r||!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 d=Array.isArray(a)?a.filter(p=>p&&p.path&&p.body&&(p.line!=null||p.position!=null)).map(p=>{let m={path:p.path,body:String(p.body)};return p.line!=null?(m.line=Number(p.line),m.side=p.side==="LEFT"?"LEFT":"RIGHT"):m.position=Number(p.position),m}):[];if(c!=="APPROVE"&&!i&&d.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l={event:c};i&&(l.body=String(i)),d.length>0&&(l.comments=d);let u=await I(`/repos/${e}/${r}/pulls/${n}/reviews`,{method:"POST",body:l});return JSON.stringify({ok:!0,id:u.id,state:u.state,event:c,commentsPosted:d.length,url:u.html_url})}case"github_list_commits":{let{owner:e,repo:r,branch:n,path:i,limit:o}=t;if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let a=`/repos/${e}/${r}/commits?per_page=${o||20}`;n&&(a+=`&sha=${encodeURIComponent(n)}`),i&&(a+=`&path=${encodeURIComponent(i)}`);let c=await I(a);return JSON.stringify({total:c.length,commits:c.map(d=>({sha:d.sha?.slice(0,8),fullSha:d.sha,message:d.commit?.message?.slice(0,300),author:d.commit?.author?.name,date:d.commit?.author?.date,url:d.html_url}))})}case"github_get_commit":{let{owner:e,repo:r,sha:n}=t;if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and sha are required"});let i=await I(`/repos/${e}/${r}/commits/${n}`);return JSON.stringify({sha:i.sha?.slice(0,8),message:i.commit?.message,author:i.commit?.author?.name,date:i.commit?.author?.date,stats:i.stats,files:(i.files||[]).map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_get_file":{let{owner:e,repo:r,path:n,ref:i}=t;if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${r}/contents/${encodeURIComponent(n)}`;i&&(o+=`?ref=${encodeURIComponent(i)}`);let a=await I(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"),d=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:d?c.slice(0,2e4):c,truncated:d})}case"github_get_user":try{let e=await I("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let r=e.repositories[0],n=r.owner.login,i=r.owner.type,o=i==="Organization"?`/orgs/${n}`:`/users/${n}`,a=await I(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 r=(await I("/installation/repositories?per_page=100")).repositories||[],n=new Map;for(let o of r)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 f=function(g){let b=g.replace(/^~(?=$|\/|\\)/,m);return a(b)},{owner:e,repo:r,destination:n}=t;if(!e||!r)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:d}=await import("fs"),{homedir:l,platform:u}=await import("os"),{token:p}=await Jt("github"),m=l(),h=n?f(n):o(m,"zibby-repos"),_=o(h,r);if(d(h,{recursive:!0}),c(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});try{let g=`https://x-access-token:${p}@github.com/${e}/${r}.git`;i(`git clone ${g} "${_}"`,{stdio:"pipe"});let b=u()==="win32",y;return b?y=i(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):y=i(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${e}/${r} to ${_}`,contents:y.split(`
118
118
  `).slice(0,30).join(`
119
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(g){return JSON.stringify({error:`Clone failed: ${g.message}`})}}case"github_search_repos":{let{query:e,limit:r}=t;if(!e)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),n=JSON.parse(i);if(n.error)return JSON.stringify(n);let o=e.toLowerCase(),c=n.repos.filter(a=>a.name.toLowerCase().includes(o)||a.fullName.toLowerCase().includes(o)||a.description&&a.description.toLowerCase().includes(o));return JSON.stringify({query:e,count:c.length,repos:c.slice(0,r||20)})}case"github_list_repos":{let{owner:e,type:r,sort:i,direction:n,limit:o,query:c}=t,a=100,d=o||200,l=[],u=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")}),p=y=>{if(!c)return!0;let k=String(c).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<d;){let J=`/installation/repositories?per_page=${a}&page=${y}`,We=(await v(J)).repositories||[];if(We.length===0)break;l=l.concat(We),k=We.length===a,y++}let A=l.map(u).filter(p),W=A.slice(0,d),Ye=A.length>W.length,T=W.filter(J=>J.private).length,O=W.filter(J=>!J.private).length;return JSON.stringify({count:W.length,repos:W,truncated:Ye,privateCount:T,publicCount:O,message:`Found ${T} private and ${O} public repos`})}let m=await v(`/orgs/${e}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&l.length<d;){let y;m?y=`/orgs/${e}/repos?per_page=${a}&page=${f}&type=${r||"all"}&sort=${i||"updated"}&direction=${n||"desc"}`:y=`/users/${e}/repos?per_page=${a}&page=${f}&type=${r||"all"}&sort=${i||"updated"}&direction=${n||"desc"}`;let k=await v(y),A=Array.isArray(k)?k:[];if(A.length===0)break;l=l.concat(A),h=A.length===a,f++}let _=l.map(u).filter(p),g=_.slice(0,d),b=_.length>g.length;return JSON.stringify({count:g.length,repos:g,truncated:b})}case"github_create_pr":{let{owner:e,repo:r,head:i,title:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=t.base;if(!o)try{o=(await v(`/repos/${e}/${r}`)).default_branch||"main"}catch{o="main"}let c={title:String(n),head:String(i),base:String(o),body:t.body?String(t.body):"",draft:!!t.draft};try{let a=await v(`/repos/${e}/${r}/pulls`,{method:"POST",body:c});return JSON.stringify({success:!0,pr_url:a.html_url,number:a.number,branch:i,base:o,repo:`${e}/${r}`,provider:"github",draft:!!a.draft,state:a.state})}catch(a){let d=String(a.message||a);if(/GitHub API 422/.test(d))return JSON.stringify({success:!1,branch:i,base:o,repo:`${e}/${r}`,provider:"github",skippedReason:d});throw a}}case"github_merge_pr":{let{owner:e,repo:r,number:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=t.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(n))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${n})`});let o={merge_method:n};t.commitTitle&&(o.commit_title=String(t.commitTitle)),t.commitMessage&&(o.commit_message=String(t.commitMessage));try{let c=await v(`/repos/${e}/${r}/pulls/${i}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:c.sha,number:i,provider:"github"})}catch(c){let a=String(c.message||c);if(/GitHub API (405|409|404)/.test(a))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:a});throw c}}case"github_create_issue":{let{owner:e,repo:r,title:i,body:n}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await v(`/repos/${e}/${r}/issues`,{method:"POST",body:{title:i,body:n||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:e,repo:r,state:i,labels:n,since:o,assignee:c,sort:a,direction:d,limit:l}=t||{};if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let u=new URLSearchParams;u.set("state",i||"open"),u.set("per_page",String(l||30)),u.set("sort",a||"updated"),u.set("direction",d||"desc"),n&&u.set("labels",Array.isArray(n)?n.join(","):n),o&&u.set("since",o),c&&u.set("assignee",c);let p=await v(`/repos/${e}/${r}/issues?${u.toString()}`),m=(Array.isArray(p)?p:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:e,repo:r,number:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/issues/${i}`);return n.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:n.number,title:n.title,body:n.body||"",state:n.state,stateReason:n.state_reason||null,labels:(n.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:n.assignee?.login||null,assignees:(n.assignees||[]).map(o=>o.login),user:n.user?.login,milestone:n.milestone?.title||null,comments:n.comments,url:n.html_url,createdAt:n.created_at,updatedAt:n.updated_at,closedAt:n.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:r,number:i,limit:n}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await v(`/repos/${e}/${r}/issues/${i}/comments?per_page=${n||100}`),c=(Array.isArray(o)?o:[]).map(a=>({id:a.id,user:a.user?.login,body:a.body||"",createdAt:a.created_at,updatedAt:a.updated_at,url:a.html_url}));return JSON.stringify({count:c.length,comments:c})}case"github_add_issue_comment":{let{owner:e,repo:r,number:i,body:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await v(`/repos/${e}/${r}/issues/${i}/comments`,{method:"POST",body:{body:n}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:e,repo:r,number:i,stateReason:n}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};n&&(o.state_reason=n);let c=await v(`/repos/${e}/${r}/issues/${i}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:c.number,state:c.state,stateReason:c.state_reason||null,url:c.html_url})}case"github_reopen_issue":{let{owner:e,repo:r,number:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:n.number,state:n.state,url:n.html_url})}case"github_label_issue":{let{owner:e,repo:r,number:i,labels:n,mode:o}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let c=Array.isArray(n)?n:n?[n]:[];if(!c.length)return JSON.stringify({error:"labels (string or array) is required"});let a=o||"add";if(a==="set"){let l=await v(`/repos/${e}/${r}/issues/${i}`,{method:"PATCH",body:{labels:c}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(u=>typeof u=="string"?u:u.name)})}if(a==="remove"){for(let u of c)await v(`/repos/${e}/${r}/issues/${i}/labels/${encodeURIComponent(u)}`,{method:"DELETE"});let l=await v(`/repos/${e}/${r}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(u=>typeof u=="string"?u:u.name)})}let d=await v(`/repos/${e}/${r}/issues/${i}/labels`,{method:"POST",body:{labels:c}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(d)?d:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}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 recent commits on a branch, 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:"Max commits (default: 20)"}},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)"}},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"]}}]};import{existsSync as oi}from"fs";import{fileURLToPath as ai}from"url";import{dirname as ci,resolve as li}from"path";function di(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=ci(ai(import.meta.url)),t=li(s,"..","bin","mcp-skill.mjs");return oi(t)?t:null}function ui(){let s=process.env.GITLAB_API_URL;if(s)return s.replace(/\/+$/,"");let t=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(t)?t:`${t}/api/v4`}function pi(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let s=process.env.GITLAB_TOKEN;if(!s)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":s}}async function j(s,t={}){let e=/^https?:\/\//.test(s)?s:`${ui()}${s}`,r={Accept:"application/json","User-Agent":"Zibby-App",...pi(),...t.body?{"Content-Type":"application/json"}:{}},i=await fetch(e,{method:t.method||"GET",headers:r,body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`GitLab API ${i.status}: ${n.slice(0,300)}`)}return t.raw?i.text():i.json()}function $t(){let s=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(s?s.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function mi(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function $(s){let t=String(s);return/^\d+$/.test(t)?t:encodeURIComponent(t)}var ce={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:I.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab (connected)
119
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(g){return JSON.stringify({error:`Clone failed: ${g.message}`})}}case"github_search_repos":{let{query:e,limit:r}=t;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,r||20)})}case"github_list_repos":{let{owner:e,type:r,sort:n,direction:i,limit:o,query:a}=t,c=100,d=o||200,l=[],u=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")}),p=y=>{if(!a)return!0;let w=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(w)||y.fullName&&y.fullName.toLowerCase().includes(w)||y.description&&y.description.toLowerCase().includes(w)};if(!e){let y=1,w=!0;for(;w&&l.length<d;){let J=`/installation/repositories?per_page=${c}&page=${y}`,rt=(await I(J)).repositories||[];if(rt.length===0)break;l=l.concat(rt),w=rt.length===c,y++}let A=l.map(u).filter(p),W=A.slice(0,d),tt=A.length>W.length,T=W.filter(J=>J.private).length,O=W.filter(J=>!J.private).length;return JSON.stringify({count:W.length,repos:W,truncated:tt,privateCount:T,publicCount:O,message:`Found ${T} private and ${O} public repos`})}let m=await I(`/orgs/${e}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&l.length<d;){let y;m?y=`/orgs/${e}/repos?per_page=${c}&page=${f}&type=${r||"all"}&sort=${n||"updated"}&direction=${i||"desc"}`:y=`/users/${e}/repos?per_page=${c}&page=${f}&type=${r||"all"}&sort=${n||"updated"}&direction=${i||"desc"}`;let w=await I(y),A=Array.isArray(w)?w:[];if(A.length===0)break;l=l.concat(A),h=A.length===c,f++}let _=l.map(u).filter(p),g=_.slice(0,d),b=_.length>g.length;return JSON.stringify({count:g.length,repos:g,truncated:b})}case"github_create_pr":{let{owner:e,repo:r,head:n,title:i}=t||{};if(!e||!r||!n||!i)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=t.base;if(!o)try{o=(await I(`/repos/${e}/${r}`)).default_branch||"main"}catch{o="main"}let a={title:String(i),head:String(n),base:String(o),body:t.body?String(t.body):"",draft:!!t.draft};try{let c=await I(`/repos/${e}/${r}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:n,base:o,repo:`${e}/${r}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let d=String(c.message||c);if(/GitHub API 422/.test(d))return JSON.stringify({success:!1,branch:n,base:o,repo:`${e}/${r}`,provider:"github",skippedReason:d});throw c}}case"github_merge_pr":{let{owner:e,repo:r,number:n}=t||{};if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=t.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};t.commitTitle&&(o.commit_title=String(t.commitTitle)),t.commitMessage&&(o.commit_message=String(t.commitMessage));try{let a=await I(`/repos/${e}/${r}/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:r,title:n,body:i}=t;if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and title are required"});let o=await I(`/repos/${e}/${r}/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:r,state:n,labels:i,since:o,assignee:a,sort:c,direction:d,limit:l}=t||{};if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let u=new URLSearchParams;u.set("state",n||"open"),u.set("per_page",String(l||30)),u.set("sort",c||"updated"),u.set("direction",d||"desc"),i&&u.set("labels",Array.isArray(i)?i.join(","):i),o&&u.set("since",o),a&&u.set("assignee",a);let p=await I(`/repos/${e}/${r}/issues?${u.toString()}`),m=(Array.isArray(p)?p:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:e,repo:r,number:n}=t||{};if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${e}/${r}/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:r,number:n,limit:i}=t||{};if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let o=await I(`/repos/${e}/${r}/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:r,number:n,body:i}=t||{};if(!e||!r||!n||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await I(`/repos/${e}/${r}/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:r,number:n,stateReason:i}=t||{};if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};i&&(o.state_reason=i);let a=await I(`/repos/${e}/${r}/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:r,number:n}=t||{};if(!e||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${e}/${r}/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:r,number:n,labels:i,mode:o}=t||{};if(!e||!r||!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 I(`/repos/${e}/${r}/issues/${n}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(u=>typeof u=="string"?u:u.name)})}if(c==="remove"){for(let u of a)await I(`/repos/${e}/${r}/issues/${n}/labels/${encodeURIComponent(u)}`,{method:"DELETE"});let l=await I(`/repos/${e}/${r}/issues/${n}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(u=>typeof u=="string"?u:u.name)})}let d=await I(`/repos/${e}/${r}/issues/${n}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:n,labels:(Array.isArray(d)?d:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}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 recent commits on a branch, 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:"Max commits (default: 20)"}},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)"}},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"]}}]};import{existsSync as wn}from"fs";import{fileURLToPath as Sn}from"url";import{dirname as In,resolve as vn}from"path";function Nn(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=In(Sn(import.meta.url)),t=vn(s,"..","bin","mcp-skill.mjs");return wn(t)?t:null}function On(){let s=process.env.GITLAB_API_URL;if(s)return s.replace(/\/+$/,"");let t=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(t)?t:`${t}/api/v4`}function Rn(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let s=process.env.GITLAB_TOKEN;if(!s)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":s}}async function L(s,t={}){let e=/^https?:\/\//.test(s)?s:`${On()}${s}`,r={Accept:"application/json","User-Agent":"Zibby-App",...Rn(),...t.body?{"Content-Type":"application/json"}:{}},n=await fetch(e,{method:t.method||"GET",headers:r,body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`GitLab API ${n.status}: ${i.slice(0,300)}`)}return t.raw?n.text():n.json()}function Mt(){let s=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(s?s.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Tn(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function j(s){let t=String(s);return/^\d+$/.test(t)?t:encodeURIComponent(t)}var le={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:v.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab (connected)
120
120
  You have access to the user's GitLab projects via the REST API (cloud gitlab.com OR self-hosted). A "merge request" (MR) is GitLab's pull request. An MR is addressed by a PROJECT (numeric id OR full path like "group/repo") and an \`iid\` (the per-project MR number shown in the URL). For projects, prefer the full path form ("group/subgroup/repo") \u2014 it's what users have. Available tools:
121
121
 
122
122
  ### Discovery
@@ -142,9 +142,9 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
142
142
 
143
143
  ### Notes
144
144
  - A code-review flow is: gitlab_get_mr (context + diff_refs) \u2192 gitlab_get_mr_changes (the diff) \u2192 gitlab_post_mr_discussion per inline finding \u2192 gitlab_post_mr_note for the summary.
145
- - If an inline position is rejected by GitLab (bad line anchor), fall back to gitlab_post_mr_note with the file/line in the text.`,resolve(){let s=di();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/gitlab.js","gitlabSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"gitlab_clone":{let{projectPath:e,projectId:r,destination:i,branch:n}=t||{},o=e&&String(e).trim();if(!o&&r!=null&&(/^\d+$/.test(String(r))?o=(await j(`/projects/${$(r)}`))?.path_with_namespace:o=String(r).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let c=mi();if(!c)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:a}=await import("child_process"),{join:d,resolve:l}=await import("path"),{existsSync:u,mkdirSync:p}=await import("fs"),m=i?l(i):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(p(m,{recursive:!0}),u(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let _=$t().replace(/^https?:\/\//,""),b=`${$t().startsWith("http://")?"http":"https"}://oauth2:${c}@${_}/${o}.git`,y=n?`--branch "${String(n).replace(/"/g,"")}" `:"";try{a(`git clone --depth 1 ${y}${b} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let k=a(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:k.split(`
145
+ - If an inline position is rejected by GitLab (bad line anchor), fall back to gitlab_post_mr_note with the file/line in the text.`,resolve(){let s=Nn();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/gitlab.js","gitlabSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"gitlab_clone":{let{projectPath:e,projectId:r,destination:n,branch:i}=t||{},o=e&&String(e).trim();if(!o&&r!=null&&(/^\d+$/.test(String(r))?o=(await L(`/projects/${j(r)}`))?.path_with_namespace:o=String(r).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=Tn();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:d,resolve:l}=await import("path"),{existsSync:u,mkdirSync:p}=await import("fs"),m=n?l(n):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(p(m,{recursive:!0}),u(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let _=Mt().replace(/^https?:\/\//,""),b=`${Mt().startsWith("http://")?"http":"https"}://oauth2:${a}@${_}/${o}.git`,y=i?`--branch "${String(i).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${y}${b} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let w=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:w.split(`
146
146
  `).slice(0,30).join(`
147
- `)})}catch(k){let A=String(k.message||k).split(c).join("***");return JSON.stringify({error:`Clone failed: ${A}`})}}case"gitlab_create_mr":{let e=t?.project??t?.projectId,r=t?.source_branch??t?.sourceBranch,{title:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let n=$(e),o=t?.target_branch??t?.targetBranch;if(!o)try{o=(await j(`/projects/${n}`)).default_branch||"main"}catch{o="main"}let c={source_branch:String(r),target_branch:String(o),title:String(i),description:t?.description?String(t.description):""};try{let a=await j(`/projects/${n}/merge_requests`,{method:"POST",body:c});return JSON.stringify({success:!0,pr_url:a.web_url,number:a.iid,branch:c.source_branch,targetBranch:c.target_branch,project:String(e),provider:"gitlab",state:a.state})}catch(a){let d=String(a.message||a);if(/GitLab API (409|400)/.test(d))return JSON.stringify({success:!1,branch:c.source_branch,targetBranch:c.target_branch,project:String(e),provider:"gitlab",skippedReason:d});throw a}}case"gitlab_accept_mr":{let e=t?.project??t?.projectId,{iid:r}=t||{};if(!e||!r)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let i=$(e),n={};t.squash!=null&&(n.squash=!!t.squash),t.mergeCommitMessage&&(n.merge_commit_message=String(t.mergeCommitMessage)),t.mergeWhenPipelineSucceeds!=null&&(n.merge_when_pipeline_succeeds=!!t.mergeWhenPipelineSucceeds);try{let o=await j(`/projects/${i}/merge_requests/${r}/merge`,{method:"PUT",body:n});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??r,project:String(e),provider:"gitlab",state:o.state})}catch(o){let c=String(o.message||o);if(/GitLab API (405|406|404)/.test(c))return JSON.stringify({success:!1,iid:r,project:String(e),provider:"gitlab",skippedReason:c});throw o}}case"gitlab_get_mr":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await j(`/projects/${$(e)}/merge_requests/${r}`);return JSON.stringify({iid:i.iid,projectId:i.project_id,title:i.title,description:(i.description||"").slice(0,5e3),state:i.state,author:i.author?.username,sourceBranch:i.source_branch,targetBranch:i.target_branch,draft:i.draft??i.work_in_progress??!1,mergeStatus:i.merge_status,changesCount:i.changes_count,labels:Array.isArray(i.labels)?i.labels:[],webUrl:i.web_url,createdAt:i.created_at,updatedAt:i.updated_at,mergedAt:i.merged_at,diffRefs:i.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await j(`/projects/${$(e)}/merge_requests/${r}/changes`),n=Array.isArray(i.changes)?i.changes:[];return JSON.stringify({iid:i.iid,total:n.length,diffRefs:i.diff_refs||null,files:n.map(o=>({oldPath:o.old_path,newPath:o.new_path,newFile:!!o.new_file,deletedFile:!!o.deleted_file,renamedFile:!!o.renamed_file,diff:typeof o.diff=="string"?o.diff.slice(0,3e3):""}))})}case"gitlab_list_mrs":{let{projectId:e,state:r,targetBranch:i,sourceBranch:n,authorUsername:o,labels:c,search:a,sort:d,orderBy:l,limit:u}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",r||"opened"),p.set("per_page",String(u||20)),p.set("order_by",l||"updated_at"),p.set("sort",d||"desc"),i&&p.set("target_branch",i),n&&p.set("source_branch",n),o&&p.set("author_username",o),c&&p.set("labels",Array.isArray(c)?c.join(","):c),a&&p.set("search",a);let m=await j(`/projects/${$(e)}/merge_requests?${p.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:e,iid:r,limit:i}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let n=await j(`/projects/${$(e)}/merge_requests/${r}/notes?per_page=${i||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(n)?n.length:0,notes:(Array.isArray(n)?n:[]).map(o=>({id:o.id,author:o.author?.username,body:(o.body||"").slice(0,1e3),system:!!o.system,createdAt:o.created_at}))})}case"gitlab_post_mr_note":{let{projectId:e,iid:r,body:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let n=await j(`/projects/${$(e)}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:n.id,createdAt:n.created_at})}case"gitlab_post_mr_discussion":{let{projectId:e,iid:r,path:i,oldPath:n,newLine:o,oldLine:c,body:a}=t||{};if(!e||!r||!i||!a)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(o==null&&c==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let d=$(e),l=t.diffRefs||null;if(l||(l=(await j(`/projects/${d}/merge_requests/${r}`)).diff_refs||null),!l||!l.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let u={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:i,old_path:n||i};o!=null&&(u.new_line=Number(o)),c!=null&&(u.old_line=Number(c));try{let p=await j(`/projects/${d}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(a),position:u}});return JSON.stringify({ok:!0,discussionId:p.id})}catch(p){return JSON.stringify({ok:!1,error:`inline anchor rejected (${p.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:e,iid:r,body:i,comments:n}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let o=$(e),c=Array.isArray(n)?n.filter(p=>p&&p.path&&p.body&&(p.newLine!=null||p.oldLine!=null)):[];if(!i&&c.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let a=t.diffRefs||null;c.length>0&&!a&&(a=(await j(`/projects/${o}/merge_requests/${r}`)).diff_refs||null);let d=!1;i&&(await j(`/projects/${o}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(i)}}),d=!0);let l=0,u=[];if(c.length>0&&a)for(let p of c){let m={base_sha:a.base_sha,start_sha:a.start_sha,head_sha:a.head_sha,position_type:"text",new_path:p.path,old_path:p.oldPath||p.path};p.newLine!=null&&(m.new_line=Number(p.newLine)),p.oldLine!=null&&(m.old_line=Number(p.oldLine));try{await j(`/projects/${o}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(p.body),position:m}}),l+=1}catch(f){u.push(`${p.path}:${p.newLine??p.oldLine} \u2014 ${f.message}`)}}else c.length>0&&!a&&u.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:d,inlinePosted:l,inlineErrors:u.length?u:void 0})}case"gitlab_get_discussion":{let{projectId:e,iid:r,discussionId:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let n=await j(`/projects/${$(e)}/merge_requests/${r}/discussions/${encodeURIComponent(i)}`),o=Array.isArray(n.notes)?n.notes:[],c=o.find(d=>d.position)||null,a=c?c.position:null;return JSON.stringify({discussionId:n.id,individualNote:!!n.individual_note,path:a&&(a.new_path||a.old_path)||null,newLine:a?a.new_line??null:null,oldLine:a?a.old_line??null:null,diffRefs:a?{base_sha:a.base_sha,start_sha:a.start_sha,head_sha:a.head_sha}:null,notes:o.map(d=>({id:d.id,author:d.author?.username,body:(d.body||"").slice(0,4e3),system:!!d.system,createdAt:d.created_at}))})}case"gitlab_reply_discussion":{let{projectId:e,iid:r,discussionId:i,body:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await j(`/projects/${$(e)}/merge_requests/${r}/discussions/${encodeURIComponent(i)}/notes`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:e,limit:r}=t||{},i=Math.min(Number(r)>0?Number(r):50,200),n=new URLSearchParams;n.set("membership","true"),n.set("simple","true"),n.set("order_by","last_activity_at"),n.set("sort","desc"),n.set("per_page",String(Math.min(i+1,100))),e&&n.set("search",String(e));let o=await j(`/projects?${n.toString()}`),c=Array.isArray(o)?o:[],a=c.length>i,d=c.slice(0,i).map(l=>({fullPath:l.path_with_namespace,name:l.name,webUrl:l.web_url,defaultBranch:l.default_branch||null,visibility:l.visibility||null}));return JSON.stringify({count:d.length,truncated:a,projects:d})}case"gitlab_list_issues":{let{projectId:e,state:r,labels:i,assigneeUsername:n,authorUsername:o,updatedAfter:c,search:a,sort:d,orderBy:l,limit:u}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",r||"opened"),p.set("per_page",String(u||30)),p.set("order_by",l||"updated_at"),p.set("sort",d||"desc"),i&&p.set("labels",Array.isArray(i)?i.join(","):i),n&&p.set("assignee_username",n),o&&p.set("author_username",o),c&&p.set("updated_after",c),a&&p.set("search",a);let m=await j(`/projects/${$(e)}/issues?${p.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(_=>_.username),userNotesCount:h.user_notes_count,webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,issues:f})}case"gitlab_get_issue":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await j(`/projects/${$(e)}/issues/${r}`);return JSON.stringify({iid:i.iid,projectId:i.project_id,title:i.title,description:(i.description||"").slice(0,5e3),state:i.state,labels:Array.isArray(i.labels)?i.labels:[],author:i.author?.username,assignees:(i.assignees||[]).map(n=>n.username),milestone:i.milestone?.title||null,webUrl:i.web_url,createdAt:i.created_at,updatedAt:i.updated_at,closedAt:i.closed_at})}case"gitlab_add_issue_comment":{let{projectId:e,iid:r,body:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let n=await j(`/projects/${$(e)}/issues/${r}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:n.id,createdAt:n.created_at})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_mrs",description:"List a GitLab project's merge requests, filtered by state and other criteria. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","merged","locked","all"],description:"Filter by state (default: opened)"},targetBranch:{type:"string",description:"Filter by target branch"},sourceBranch:{type:"string",description:"Filter by source branch"},authorUsername:{type:"string",description:"Filter by author username"},labels:{type:"array",items:{type:"string"},description:"Only MRs carrying ALL of these labels"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at","title"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max MRs (default: 20)"}},required:["projectId"]}},{name:"gitlab_list_mr_notes",description:"List the discussion notes on a GitLab merge request (chronological).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},limit:{type:"number",description:"Max notes (default 50)"}},required:["projectId","iid"]}},{name:"gitlab_post_mr_note",description:"Post a general (non-inline) comment on a GitLab merge request. Use for a review summary or a top-level remark.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}},{name:"gitlab_post_mr_discussion",description:"Post an INLINE review comment anchored to a file + line in a GitLab merge request diff. Provide newLine (added/changed line) or oldLine (removed/context line). Pass diffRefs from gitlab_get_mr/gitlab_get_mr_changes, or omit to have the tool fetch them. If the line anchor is rejected, fall back to gitlab_post_mr_note.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr. Omit and the tool fetches them."}},required:["projectId","iid","path","body"]}},{name:"gitlab_create_mr_review",description:"Post a full review on a GitLab merge request in one call: a summary note plus optional inline comments anchored to file/line in the diff. Convenience wrapper over gitlab_post_mr_note + gitlab_post_mr_discussion.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"The review summary (markdown). Posted as a top-level MR note."},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr \u2014 required to anchor inline comments. Omit and the tool fetches them."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line in a file.",items:{type:"object",properties:{path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","body"]}}},required:["projectId","iid"]}},{name:"gitlab_get_discussion",description:"Read a single GitLab merge-request DISCUSSION (thread) by its discussion id: all notes in order plus the diff position (file + line) it is anchored to. Use this to understand a human's reply to a previous review discussion before replying in-thread.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id (from the Note Hook payload or gitlab_list_mr_notes)"}},required:["projectId","iid","discussionId"]}},{name:"gitlab_reply_discussion",description:"Reply IN-THREAD to an existing GitLab merge-request discussion (a conversational reply appended to the SAME thread \u2014 NOT a fresh review). Use after gitlab_get_discussion to answer a human's reply to a review comment.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["projectId","iid","discussionId","body"]}},{name:"gitlab_list_issues",description:"List a GitLab project's issues, filtered by state, labels, and an updatedAfter polling cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","all"],description:"Filter by state (default: opened)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},assigneeUsername:{type:"string",description:"Filter by assignee username"},authorUsername:{type:"string",description:"Filter by author username"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30)"}},required:["projectId"]}},{name:"gitlab_get_issue",description:"Get a single GitLab issue with full detail (title, description, state, labels, assignees, web url).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid (the per-project issue number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_add_issue_comment",description:"Add a comment to a GitLab issue. Also the way to record an MR link on a ticket (post a markdown link).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}}]};import{existsSync as fi}from"fs";import{fileURLToPath as hi}from"url";import{dirname as yi,resolve as gi}from"path";import{resolveIntegrationToken as _i}from"@zibby/core/backend-client.js";function bi(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=yi(hi(import.meta.url)),t=gi(s,"..","bin","mcp-skill.mjs");return fi(t)?t:null}async function fe(s,t={}){let{token:e}=await _i("figma"),r=s.startsWith("https://")?s:`https://api.figma.com${s}`,i={"X-Figma-Token":e,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},n=await fetch(r,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Figma API ${n.status}: ${o.slice(0,300)}`)}return n.json()}var xt={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:I.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes, comments, and render frames as PNGs",promptFragment:`## Figma (connected)
147
+ `)})}catch(w){let A=String(w.message||w).split(a).join("***");return JSON.stringify({error:`Clone failed: ${A}`})}}case"gitlab_create_mr":{let e=t?.project??t?.projectId,r=t?.source_branch??t?.sourceBranch,{title:n}=t||{};if(!e||!r||!n)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let i=j(e),o=t?.target_branch??t?.targetBranch;if(!o)try{o=(await L(`/projects/${i}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(r),target_branch:String(o),title:String(n),description:t?.description?String(t.description):""};try{let c=await L(`/projects/${i}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",state:c.state})}catch(c){let d=String(c.message||c);if(/GitLab API (409|400)/.test(d))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",skippedReason:d});throw c}}case"gitlab_accept_mr":{let e=t?.project??t?.projectId,{iid:r}=t||{};if(!e||!r)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let n=j(e),i={};t.squash!=null&&(i.squash=!!t.squash),t.mergeCommitMessage&&(i.merge_commit_message=String(t.mergeCommitMessage)),t.mergeWhenPipelineSucceeds!=null&&(i.merge_when_pipeline_succeeds=!!t.mergeWhenPipelineSucceeds);try{let o=await L(`/projects/${n}/merge_requests/${r}/merge`,{method:"PUT",body:i});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??r,project:String(e),provider:"gitlab",state:o.state})}catch(o){let a=String(o.message||o);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:r,project:String(e),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let n=await L(`/projects/${j(e)}/merge_requests/${r}`);return JSON.stringify({iid:n.iid,projectId:n.project_id,title:n.title,description:(n.description||"").slice(0,5e3),state:n.state,author:n.author?.username,sourceBranch:n.source_branch,targetBranch:n.target_branch,draft:n.draft??n.work_in_progress??!1,mergeStatus:n.merge_status,changesCount:n.changes_count,labels:Array.isArray(n.labels)?n.labels:[],webUrl:n.web_url,createdAt:n.created_at,updatedAt:n.updated_at,mergedAt:n.merged_at,diffRefs:n.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let n=await L(`/projects/${j(e)}/merge_requests/${r}/changes`),i=Array.isArray(n.changes)?n.changes:[];return JSON.stringify({iid:n.iid,total:i.length,diffRefs:n.diff_refs||null,files:i.map(o=>({oldPath:o.old_path,newPath:o.new_path,newFile:!!o.new_file,deletedFile:!!o.deleted_file,renamedFile:!!o.renamed_file,diff:typeof o.diff=="string"?o.diff.slice(0,3e3):""}))})}case"gitlab_list_mrs":{let{projectId:e,state:r,targetBranch:n,sourceBranch:i,authorUsername:o,labels:a,search:c,sort:d,orderBy:l,limit:u}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",r||"opened"),p.set("per_page",String(u||20)),p.set("order_by",l||"updated_at"),p.set("sort",d||"desc"),n&&p.set("target_branch",n),i&&p.set("source_branch",i),o&&p.set("author_username",o),a&&p.set("labels",Array.isArray(a)?a.join(","):a),c&&p.set("search",c);let m=await L(`/projects/${j(e)}/merge_requests?${p.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:e,iid:r,limit:n}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await L(`/projects/${j(e)}/merge_requests/${r}/notes?per_page=${n||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(i)?i.length:0,notes:(Array.isArray(i)?i:[]).map(o=>({id:o.id,author:o.author?.username,body:(o.body||"").slice(0,1e3),system:!!o.system,createdAt:o.created_at}))})}case"gitlab_post_mr_note":{let{projectId:e,iid:r,body:n}=t||{};if(!e||!r||!n)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await L(`/projects/${j(e)}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}case"gitlab_post_mr_discussion":{let{projectId:e,iid:r,path:n,oldPath:i,newLine:o,oldLine:a,body:c}=t||{};if(!e||!r||!n||!c)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(o==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let d=j(e),l=t.diffRefs||null;if(l||(l=(await L(`/projects/${d}/merge_requests/${r}`)).diff_refs||null),!l||!l.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let u={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:n,old_path:i||n};o!=null&&(u.new_line=Number(o)),a!=null&&(u.old_line=Number(a));try{let p=await L(`/projects/${d}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(c),position:u}});return JSON.stringify({ok:!0,discussionId:p.id})}catch(p){return JSON.stringify({ok:!1,error:`inline anchor rejected (${p.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:e,iid:r,body:n,comments:i}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let o=j(e),a=Array.isArray(i)?i.filter(p=>p&&p.path&&p.body&&(p.newLine!=null||p.oldLine!=null)):[];if(!n&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=t.diffRefs||null;a.length>0&&!c&&(c=(await L(`/projects/${o}/merge_requests/${r}`)).diff_refs||null);let d=!1;n&&(await L(`/projects/${o}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(n)}}),d=!0);let l=0,u=[];if(a.length>0&&c)for(let p of a){let m={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:p.path,old_path:p.oldPath||p.path};p.newLine!=null&&(m.new_line=Number(p.newLine)),p.oldLine!=null&&(m.old_line=Number(p.oldLine));try{await L(`/projects/${o}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(p.body),position:m}}),l+=1}catch(f){u.push(`${p.path}:${p.newLine??p.oldLine} \u2014 ${f.message}`)}}else a.length>0&&!c&&u.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:d,inlinePosted:l,inlineErrors:u.length?u:void 0})}case"gitlab_get_discussion":{let{projectId:e,iid:r,discussionId:n}=t||{};if(!e||!r||!n)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let i=await L(`/projects/${j(e)}/merge_requests/${r}/discussions/${encodeURIComponent(n)}`),o=Array.isArray(i.notes)?i.notes:[],a=o.find(d=>d.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:i.id,individualNote:!!i.individual_note,path:c&&(c.new_path||c.old_path)||null,newLine:c?c.new_line??null:null,oldLine:c?c.old_line??null:null,diffRefs:c?{base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha}:null,notes:o.map(d=>({id:d.id,author:d.author?.username,body:(d.body||"").slice(0,4e3),system:!!d.system,createdAt:d.created_at}))})}case"gitlab_reply_discussion":{let{projectId:e,iid:r,discussionId:n,body:i}=t||{};if(!e||!r||!n||!i)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await L(`/projects/${j(e)}/merge_requests/${r}/discussions/${encodeURIComponent(n)}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:e,limit:r}=t||{},n=Math.min(Number(r)>0?Number(r):50,200),i=new URLSearchParams;i.set("membership","true"),i.set("simple","true"),i.set("order_by","last_activity_at"),i.set("sort","desc"),i.set("per_page",String(Math.min(n+1,100))),e&&i.set("search",String(e));let o=await L(`/projects?${i.toString()}`),a=Array.isArray(o)?o:[],c=a.length>n,d=a.slice(0,n).map(l=>({fullPath:l.path_with_namespace,name:l.name,webUrl:l.web_url,defaultBranch:l.default_branch||null,visibility:l.visibility||null}));return JSON.stringify({count:d.length,truncated:c,projects:d})}case"gitlab_list_issues":{let{projectId:e,state:r,labels:n,assigneeUsername:i,authorUsername:o,updatedAfter:a,search:c,sort:d,orderBy:l,limit:u}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",r||"opened"),p.set("per_page",String(u||30)),p.set("order_by",l||"updated_at"),p.set("sort",d||"desc"),n&&p.set("labels",Array.isArray(n)?n.join(","):n),i&&p.set("assignee_username",i),o&&p.set("author_username",o),a&&p.set("updated_after",a),c&&p.set("search",c);let m=await L(`/projects/${j(e)}/issues?${p.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(_=>_.username),userNotesCount:h.user_notes_count,webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,issues:f})}case"gitlab_get_issue":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let n=await L(`/projects/${j(e)}/issues/${r}`);return JSON.stringify({iid:n.iid,projectId:n.project_id,title:n.title,description:(n.description||"").slice(0,5e3),state:n.state,labels:Array.isArray(n.labels)?n.labels:[],author:n.author?.username,assignees:(n.assignees||[]).map(i=>i.username),milestone:n.milestone?.title||null,webUrl:n.web_url,createdAt:n.created_at,updatedAt:n.updated_at,closedAt:n.closed_at})}case"gitlab_add_issue_comment":{let{projectId:e,iid:r,body:n}=t||{};if(!e||!r||!n)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await L(`/projects/${j(e)}/issues/${r}/notes`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_mrs",description:"List a GitLab project's merge requests, filtered by state and other criteria. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","merged","locked","all"],description:"Filter by state (default: opened)"},targetBranch:{type:"string",description:"Filter by target branch"},sourceBranch:{type:"string",description:"Filter by source branch"},authorUsername:{type:"string",description:"Filter by author username"},labels:{type:"array",items:{type:"string"},description:"Only MRs carrying ALL of these labels"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at","title"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max MRs (default: 20)"}},required:["projectId"]}},{name:"gitlab_list_mr_notes",description:"List the discussion notes on a GitLab merge request (chronological).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},limit:{type:"number",description:"Max notes (default 50)"}},required:["projectId","iid"]}},{name:"gitlab_post_mr_note",description:"Post a general (non-inline) comment on a GitLab merge request. Use for a review summary or a top-level remark.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}},{name:"gitlab_post_mr_discussion",description:"Post an INLINE review comment anchored to a file + line in a GitLab merge request diff. Provide newLine (added/changed line) or oldLine (removed/context line). Pass diffRefs from gitlab_get_mr/gitlab_get_mr_changes, or omit to have the tool fetch them. If the line anchor is rejected, fall back to gitlab_post_mr_note.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr. Omit and the tool fetches them."}},required:["projectId","iid","path","body"]}},{name:"gitlab_create_mr_review",description:"Post a full review on a GitLab merge request in one call: a summary note plus optional inline comments anchored to file/line in the diff. Convenience wrapper over gitlab_post_mr_note + gitlab_post_mr_discussion.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"The review summary (markdown). Posted as a top-level MR note."},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr \u2014 required to anchor inline comments. Omit and the tool fetches them."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line in a file.",items:{type:"object",properties:{path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","body"]}}},required:["projectId","iid"]}},{name:"gitlab_get_discussion",description:"Read a single GitLab merge-request DISCUSSION (thread) by its discussion id: all notes in order plus the diff position (file + line) it is anchored to. Use this to understand a human's reply to a previous review discussion before replying in-thread.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id (from the Note Hook payload or gitlab_list_mr_notes)"}},required:["projectId","iid","discussionId"]}},{name:"gitlab_reply_discussion",description:"Reply IN-THREAD to an existing GitLab merge-request discussion (a conversational reply appended to the SAME thread \u2014 NOT a fresh review). Use after gitlab_get_discussion to answer a human's reply to a review comment.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["projectId","iid","discussionId","body"]}},{name:"gitlab_list_issues",description:"List a GitLab project's issues, filtered by state, labels, and an updatedAfter polling cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","all"],description:"Filter by state (default: opened)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},assigneeUsername:{type:"string",description:"Filter by assignee username"},authorUsername:{type:"string",description:"Filter by author username"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30)"}},required:["projectId"]}},{name:"gitlab_get_issue",description:"Get a single GitLab issue with full detail (title, description, state, labels, assignees, web url).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid (the per-project issue number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_add_issue_comment",description:"Add a comment to a GitLab issue. Also the way to record an MR link on a ticket (post a markdown link).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}}]};import{existsSync as An}from"fs";import{fileURLToPath as En}from"url";import{dirname as Ln,resolve as xn}from"path";import{resolveIntegrationToken as jn}from"@zibby/core/backend-client.js";function $n(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Ln(En(import.meta.url)),t=xn(s,"..","bin","mcp-skill.mjs");return An(t)?t:null}async function ge(s,t={}){let{token:e}=await jn("figma"),r=s.startsWith("https://")?s:`https://api.figma.com${s}`,n={"X-Figma-Token":e,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},i=await fetch(r,{method:t.method||"GET",headers:n,body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Figma API ${i.status}: ${o.slice(0,300)}`)}return i.json()}var Bt={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:v.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes, comments, and render frames as PNGs",promptFragment:`## Figma (connected)
148
148
  You have read access to the user's Figma files via the Figma REST API. Tools:
149
149
 
150
150
  ### Identity
@@ -162,7 +162,7 @@ You have read access to the user's Figma files via the Figma REST API. Tools:
162
162
 
163
163
  ### Notes
164
164
  - The fileKey is NOT the file name \u2014 it's the opaque id segment in the URL.
165
- - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes output.`,resolve(){let s=bi();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/figma.js","figmaSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"figma_get_me":{let e=await fe("/v1/me");return JSON.stringify({id:e.id,handle:e.handle,email:e.email,imgUrl:e.img_url})}case"figma_get_file":{let{fileKey:e,depth:r}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let i=`/v1/files/${encodeURIComponent(e)}`;if(r!=null){let c=Number(r);!Number.isNaN(c)&&c>0&&(i+=`?depth=${c}`)}let n=await fe(i),o=(n.document?.children||[]).map(c=>({id:c.id,name:c.name,type:c.type,childCount:Array.isArray(c.children)?c.children.length:0,children:(c.children||[]).slice(0,50).map(a=>({id:a.id,name:a.name,type:a.type}))}));return JSON.stringify({name:n.name,lastModified:n.lastModified,version:n.version,editorType:n.editorType,role:n.role,pages:o})}case"figma_get_nodes":{let{fileKey:e,ids:r,depth:i}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let c=new URLSearchParams;if(c.set("ids",o.join(",")),i!=null){let l=Number(i);!Number.isNaN(l)&&l>0&&c.set("depth",String(l))}let a=await fe(`/v1/files/${encodeURIComponent(e)}/nodes?${c.toString()}`),d={};for(let[l,u]of Object.entries(a.nodes||{}))d[l]=u?.document?{id:u.document.id,name:u.document.name,type:u.document.type,document:u.document}:u;return JSON.stringify({name:a.name,nodes:d})}case"figma_render_png":{let{fileKey:e,ids:r,scale:i}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let c=new URLSearchParams;c.set("ids",o.join(",")),c.set("format","png");let a=Number(i);(Number.isNaN(a)||a<=0)&&(a=1),a=Math.min(4,Math.max(.01,a)),c.set("scale",String(a));let d=await fe(`/v1/images/${encodeURIComponent(e)}?${c.toString()}`);return d.err?JSON.stringify({error:`Figma render error: ${d.err}`}):JSON.stringify({scale:a,format:"png",images:d.images||{}})}case"figma_get_comments":{let{fileKey:e}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let i=((await fe(`/v1/files/${encodeURIComponent(e)}/comments`)).comments||[]).map(n=>({id:n.id,message:n.message,user:n.user?.handle,createdAt:n.created_at,resolvedAt:n.resolved_at||null,parentId:n.parent_id||null}));return JSON.stringify({count:i.length,comments:i})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree by fileKey (the opaque id segment in a figma.com/file/<fileKey>/ or /design/<fileKey>/ URL \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'The file key from the Figma URL (e.g. "aBcD1234" in figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch (e.g. ["1:23","4:56"]). A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to PNG and return the image URLs (a map of nodeId \u2192 URL). Use this to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (e.g. ["1:23"]). A comma-separated string is also accepted.'},scale:{type:"number",description:"Render scale, 0.01\u20134 (default 1). 2 for retina/hi-dpi."}},required:["fileKey","ids"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"}},required:["fileKey"]}}]};import{existsSync as wi}from"fs";import{fileURLToPath as ki}from"url";import{dirname as Si,resolve as vi}from"path";function Ii(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Si(ki(import.meta.url)),t=vi(s,"..","bin","mcp-skill.mjs");return wi(t)?t:null}var Ni=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Oi(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let s=process.env.LINEAR_API_KEY;if(!s)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return s}async function M(s,t={}){let e=await fetch(Ni,{method:"POST",headers:{Authorization:Oi(),"Content-Type":"application/json"},body:JSON.stringify({query:s,variables:t})});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`Linear API ${e.status}: ${i.slice(0,300)}`)}let r=await e.json().catch(()=>null);if(!r)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(r.errors)&&r.errors.length){let i=r.errors.map(n=>n?.message||String(n)).join("; ");throw new Error(`Linear GraphQL error: ${i.slice(0,300)}`)}return r.data}function ye(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ri(s,t){let e=ye(s),r=ye(t);if(!e||!r)return 0;if(e===r)return 1;if(e.length===1||r.length===1)return e===r?1:0;let i=l=>{let u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},n=i(e),o=i(r),c=0,a=0,d=0;for(let l of n.values())a+=l;for(let l of o.values())d+=l;for(let[l,u]of n.entries())c+=Math.min(u,o.get(l)||0);return 2*c/Math.max(1,a+d)}function Ti(s,t){let e=Array.isArray(s)?s:[];if(!e.length)return{state:null,strategy:"no-states"};let r=ye(t);if(!r)return{state:null,strategy:"no-target"};let i=e.find(c=>ye(c.name)===r);if(i)return{state:i,strategy:"exact"};let n={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[c,a]of Object.entries(n)){if(!a.some(l=>ye(l)===r))continue;let d=e.find(l=>l.type===c);if(d)return{state:d,strategy:"type-alias"}}let o=e.map(c=>({s:c,score:Ri(t,c.name)})).sort((c,a)=>a.score-c.score);return o[0]&&o[0].score>=.5?{state:o[0].s,strategy:"fuzzy"}:{state:null,strategy:"no-match"}}var Ai=`
165
+ - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes output.`,resolve(){let s=$n();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/figma.js","figmaSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"figma_get_me":{let e=await ge("/v1/me");return JSON.stringify({id:e.id,handle:e.handle,email:e.email,imgUrl:e.img_url})}case"figma_get_file":{let{fileKey:e,depth:r}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let n=`/v1/files/${encodeURIComponent(e)}`;if(r!=null){let a=Number(r);!Number.isNaN(a)&&a>0&&(n+=`?depth=${a}`)}let i=await ge(n),o=(i.document?.children||[]).map(a=>({id:a.id,name:a.name,type:a.type,childCount:Array.isArray(a.children)?a.children.length:0,children:(a.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:i.name,lastModified:i.lastModified,version:i.version,editorType:i.editorType,role:i.role,pages:o})}case"figma_get_nodes":{let{fileKey:e,ids:r,depth:n}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;if(a.set("ids",o.join(",")),n!=null){let l=Number(n);!Number.isNaN(l)&&l>0&&a.set("depth",String(l))}let c=await ge(`/v1/files/${encodeURIComponent(e)}/nodes?${a.toString()}`),d={};for(let[l,u]of Object.entries(c.nodes||{}))d[l]=u?.document?{id:u.document.id,name:u.document.name,type:u.document.type,document:u.document}:u;return JSON.stringify({name:c.name,nodes:d})}case"figma_render_png":{let{fileKey:e,ids:r,scale:n}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;a.set("ids",o.join(",")),a.set("format","png");let c=Number(n);(Number.isNaN(c)||c<=0)&&(c=1),c=Math.min(4,Math.max(.01,c)),a.set("scale",String(c));let d=await ge(`/v1/images/${encodeURIComponent(e)}?${a.toString()}`);return d.err?JSON.stringify({error:`Figma render error: ${d.err}`}):JSON.stringify({scale:c,format:"png",images:d.images||{}})}case"figma_get_comments":{let{fileKey:e}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let n=((await ge(`/v1/files/${encodeURIComponent(e)}/comments`)).comments||[]).map(i=>({id:i.id,message:i.message,user:i.user?.handle,createdAt:i.created_at,resolvedAt:i.resolved_at||null,parentId:i.parent_id||null}));return JSON.stringify({count:n.length,comments:n})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree by fileKey (the opaque id segment in a figma.com/file/<fileKey>/ or /design/<fileKey>/ URL \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'The file key from the Figma URL (e.g. "aBcD1234" in figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch (e.g. ["1:23","4:56"]). A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to PNG and return the image URLs (a map of nodeId \u2192 URL). Use this to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (e.g. ["1:23"]). A comma-separated string is also accepted.'},scale:{type:"number",description:"Render scale, 0.01\u20134 (default 1). 2 for retina/hi-dpi."}},required:["fileKey","ids"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"}},required:["fileKey"]}}]};import{existsSync as Cn}from"fs";import{fileURLToPath as Pn}from"url";import{dirname as Un,resolve as qn}from"path";function Dn(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Un(Pn(import.meta.url)),t=qn(s,"..","bin","mcp-skill.mjs");return Cn(t)?t:null}var Jn=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Mn(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let s=process.env.LINEAR_API_KEY;if(!s)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return s}async function M(s,t={}){let e=await fetch(Jn,{method:"POST",headers:{Authorization:Mn(),"Content-Type":"application/json"},body:JSON.stringify({query:s,variables:t})});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`Linear API ${e.status}: ${n.slice(0,300)}`)}let r=await e.json().catch(()=>null);if(!r)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(r.errors)&&r.errors.length){let n=r.errors.map(i=>i?.message||String(i)).join("; ");throw new Error(`Linear GraphQL error: ${n.slice(0,300)}`)}return r.data}function be(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Bn(s,t){let e=be(s),r=be(t);if(!e||!r)return 0;if(e===r)return 1;if(e.length===1||r.length===1)return e===r?1:0;let n=l=>{let u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},i=n(e),o=n(r),a=0,c=0,d=0;for(let l of i.values())c+=l;for(let l of o.values())d+=l;for(let[l,u]of i.entries())a+=Math.min(u,o.get(l)||0);return 2*a/Math.max(1,c+d)}function Kn(s,t){let e=Array.isArray(s)?s:[];if(!e.length)return{state:null,strategy:"no-states"};let r=be(t);if(!r)return{state:null,strategy:"no-target"};let n=e.find(a=>be(a.name)===r);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=>be(l)===r))continue;let d=e.find(l=>l.type===a);if(d)return{state:d,strategy:"type-alias"}}let o=e.map(a=>({s:a,score:Bn(t,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 Gn=`
166
166
  id
167
167
  identifier
168
168
  number
@@ -176,7 +176,7 @@ You have read access to the user's Figma files via the Figma REST API. Tools:
176
176
  assignee { id name displayName email }
177
177
  labels { nodes { id name color } }
178
178
  team { id key name }
179
- `,Pt={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:I.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear (connected)
179
+ `,Gt={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:v.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear (connected)
180
180
  You have direct access to the user's Linear workspace (GraphQL API). Tools:
181
181
 
182
182
  ### Discovery
@@ -194,32 +194,32 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
194
194
 
195
195
  ### Notes
196
196
  - 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.
197
- - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let s={};for(let e of this.envKeys)process.env[e]&&(s[e]=process.env[e]);process.env.LINEAR_API_URL&&(s.LINEAR_API_URL=process.env.LINEAR_API_URL);let t=Ii();return t?{type:"stdio",command:"node",args:[t,"../dist/linear.js","linearSkill"],env:s,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:s,description:this.description}},async handleToolCall(s,t){try{switch(s){case"linear_list_teams":{let r=(await M(`
197
+ - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let s={};for(let e of this.envKeys)process.env[e]&&(s[e]=process.env[e]);process.env.LINEAR_API_URL&&(s.LINEAR_API_URL=process.env.LINEAR_API_URL);let t=Dn();return t?{type:"stdio",command:"node",args:[t,"../dist/linear.js","linearSkill"],env:s,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:s,description:this.description}},async handleToolCall(s,t){try{switch(s){case"linear_list_teams":{let r=(await M(`
198
198
  query Teams($first: Int) {
199
199
  teams(first: $first) {
200
200
  nodes { id key name description }
201
201
  }
202
202
  }
203
- `,{first:t?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:r.length,teams:r})}case"linear_list_states":{let{teamId:e,teamKey:r}=t||{},i=e;if(!i&&r&&(i=await Ct(r)),i){let a=(await M(`
203
+ `,{first:t?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:r.length,teams:r})}case"linear_list_states":{let{teamId:e,teamKey:r}=t||{},n=e;if(!n&&r&&(n=await Kt(r)),n){let c=(await M(`
204
204
  query States($teamId: String!) {
205
205
  team(id: $teamId) {
206
206
  id key name
207
207
  states { nodes { id name type color position } }
208
208
  }
209
209
  }
210
- `,{teamId:i}))?.team,d=(a?.states?.nodes||[]).slice().sort((l,u)=>(l.position||0)-(u.position||0));return JSON.stringify({team:a?{id:a.id,key:a.key,name:a.name}:null,count:d.length,states:d})}let o=(await M(`
210
+ `,{teamId:n}))?.team,d=(c?.states?.nodes||[]).slice().sort((l,u)=>(l.position||0)-(u.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:d.length,states:d})}let o=(await M(`
211
211
  query AllStates($first: Int) {
212
212
  workflowStates(first: $first) {
213
213
  nodes { id name type color team { id key name } }
214
214
  }
215
215
  }
216
- `,{first:t?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:e}=t||{},i=(await M(`
216
+ `,{first:t?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:e}=t||{},n=(await M(`
217
217
  query Labels($first: Int, $filter: IssueLabelFilter) {
218
218
  issueLabels(first: $first, filter: $filter) {
219
219
  nodes { id name color team { id key } }
220
220
  }
221
221
  }
222
- `,{first:t?.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:r,stateId:i,stateName:n,label:o,assigneeId:c,updatedAfter:a,limit:d}=t||{},l={},u=e;!u&&r&&(u=await Ct(r)),u&&(l.team={id:{eq:u}}),i?l.state={id:{eq:i}}:n&&(l.state={name:{eqIgnoreCase:n}}),o&&(l.labels={name:{eqIgnoreCase:o}}),c&&(l.assignee={id:{eq:c}}),a&&(l.updatedAt={gt:a});let m=((await M(`
222
+ `,{first:t?.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:r,stateId:n,stateName:i,label:o,assigneeId:a,updatedAfter:c,limit:d}=t||{},l={},u=e;!u&&r&&(u=await Kt(r)),u&&(l.team={id:{eq:u}}),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 m=((await M(`
223
223
  query Issues($first: Int, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
224
224
  issues(first: $first, filter: $filter, orderBy: $orderBy) {
225
225
  nodes {
@@ -231,57 +231,57 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
231
231
  }
232
232
  }
233
233
  }
234
- `,{first:d||30,filter:Object.keys(l).length?l:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(f=>({id:f.id,identifier:f.identifier,number:f.number,title:f.title,url:f.url,priority:f.priority,state:f.state?.name,stateType:f.state?.type,assignee:f.assignee?.displayName||null,labels:(f.labels?.nodes||[]).map(h=>h.name),team:f.team?.key,createdAt:f.createdAt,updatedAt:f.updatedAt}));return JSON.stringify({count:m.length,issues:m})}case"linear_get_issue":{let e=t?.issueId||t?.identifier||t?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let r=await he(e);return JSON.stringify(r?{id:r.id,identifier:r.identifier,number:r.number,title:r.title,description:r.description||"",url:r.url,priority:r.priority,state:r.state?.name,stateId:r.state?.id,stateType:r.state?.type,assignee:r.assignee?.displayName||r.assignee?.name||null,assigneeId:r.assignee?.id||null,labels:(r.labels?.nodes||[]).map(i=>i.name),team:r.team?{id:r.team.id,key:r.team.key,name:r.team.name}:null,createdAt:r.createdAt,updatedAt:r.updatedAt}:{error:`Issue not found: ${e}`})}case"linear_get_comments":{let e=t?.issueId||t?.identifier||t?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let r=await he(e,`
234
+ `,{first:d||30,filter:Object.keys(l).length?l:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(f=>({id:f.id,identifier:f.identifier,number:f.number,title:f.title,url:f.url,priority:f.priority,state:f.state?.name,stateType:f.state?.type,assignee:f.assignee?.displayName||null,labels:(f.labels?.nodes||[]).map(h=>h.name),team:f.team?.key,createdAt:f.createdAt,updatedAt:f.updatedAt}));return JSON.stringify({count:m.length,issues:m})}case"linear_get_issue":{let e=t?.issueId||t?.identifier||t?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let r=await _e(e);return JSON.stringify(r?{id:r.id,identifier:r.identifier,number:r.number,title:r.title,description:r.description||"",url:r.url,priority:r.priority,state:r.state?.name,stateId:r.state?.id,stateType:r.state?.type,assignee:r.assignee?.displayName||r.assignee?.name||null,assigneeId:r.assignee?.id||null,labels:(r.labels?.nodes||[]).map(n=>n.name),team:r.team?{id:r.team.id,key:r.team.key,name:r.team.name}:null,createdAt:r.createdAt,updatedAt:r.updatedAt}:{error:`Issue not found: ${e}`})}case"linear_get_comments":{let e=t?.issueId||t?.identifier||t?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let r=await _e(e,`
235
235
  id identifier
236
236
  comments(first: ${Number(t?.limit)||50}) {
237
237
  nodes { id body createdAt updatedAt user { id name displayName } }
238
238
  }
239
- `);if(!r)return JSON.stringify({error:`Issue not found: ${e}`});let i=(r.comments?.nodes||[]).map(n=>({id:n.id,author:n.user?.displayName||n.user?.name||"Unknown",body:n.body||"",createdAt:n.createdAt,updatedAt:n.updatedAt})).sort((n,o)=>String(o.createdAt).localeCompare(String(n.createdAt)));return JSON.stringify({count:i.length,issue:r.identifier,comments:i})}case"linear_add_comment":{let e=t?.issueId||t?.identifier||t?.issueKey,r=t?.body;if(!e||!r)return JSON.stringify({error:"issueId/identifier and body are required"});let i=await he(e,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await M(`
239
+ `);if(!r)return JSON.stringify({error:`Issue not found: ${e}`});let n=(r.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:r.identifier,comments:n})}case"linear_add_comment":{let e=t?.issueId||t?.identifier||t?.issueKey,r=t?.body;if(!e||!r)return JSON.stringify({error:"issueId/identifier and body are required"});let n=await _e(e,"id identifier");if(!n)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await M(`
240
240
  mutation AddComment($input: CommentCreateInput!) {
241
241
  commentCreate(input: $input) {
242
242
  success
243
243
  comment { id url createdAt }
244
244
  }
245
245
  }
246
- `,{input:{issueId:i.id,body:r}}))?.commentCreate;return JSON.stringify({ok:!!o?.success,commentId:o?.comment?.id,url:o?.comment?.url})}case"linear_update_state":{let e=t?.issueId||t?.identifier||t?.issueKey,{stateId:r,stateName:i,toStatus:n,status:o}=t||{};if(!e)return JSON.stringify({error:"issueId or identifier is required"});let c=await he(e,`
246
+ `,{input:{issueId:n.id,body:r}}))?.commentCreate;return JSON.stringify({ok:!!o?.success,commentId:o?.comment?.id,url:o?.comment?.url})}case"linear_update_state":{let e=t?.issueId||t?.identifier||t?.issueKey,{stateId:r,stateName:n,toStatus:i,status:o}=t||{};if(!e)return JSON.stringify({error:"issueId or identifier is required"});let a=await _e(e,`
247
247
  id identifier
248
248
  state { id name type }
249
249
  team { id key states { nodes { id name type position } } }
250
- `);if(!c)return JSON.stringify({error:`Issue not found: ${e}`});let a=r,d=r?{strategy:"explicit-id"}:null;if(!a){let p=String(i||n||o||"").trim(),m=(c.team?.states?.nodes||[]).slice().sort((h,_)=>(h.position||0)-(_.position||0));if(!p)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:c.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});let f=Ti(m,p);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${p}" in team ${c.team?.key}`,issue:c.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});a=f.state.id,d={strategy:f.strategy,matchedName:f.state.name}}let u=(await M(`
250
+ `);if(!a)return JSON.stringify({error:`Issue not found: ${e}`});let c=r,d=r?{strategy:"explicit-id"}:null;if(!c){let p=String(n||i||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((h,_)=>(h.position||0)-(_.position||0));if(!p)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});let f=Kn(m,p);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${p}" in team ${a.team?.key}`,issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});c=f.state.id,d={strategy:f.strategy,matchedName:f.state.name}}let u=(await M(`
251
251
  mutation MoveIssue($id: String!, $input: IssueUpdateInput!) {
252
252
  issueUpdate(id: $id, input: $input) {
253
253
  success
254
254
  issue { id identifier state { id name type } }
255
255
  }
256
256
  }
257
- `,{id:c.id,input:{stateId:a}}))?.issueUpdate;return JSON.stringify({ok:!!u?.success,issue:u?.issue?.identifier||c.identifier,stateAfter:u?.issue?.state?.name||null,stateTypeAfter:u?.issue?.state?.type||null,resolution:d})}case"linear_link_attachment":{let e=t?.issueId||t?.identifier||t?.issueKey,{url:r,title:i,subtitle:n}=t||{};if(!e||!r)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await he(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let a=(await M(`
257
+ `,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!u?.success,issue:u?.issue?.identifier||a.identifier,stateAfter:u?.issue?.state?.name||null,stateTypeAfter:u?.issue?.state?.type||null,resolution:d})}case"linear_link_attachment":{let e=t?.issueId||t?.identifier||t?.issueKey,{url:r,title:n,subtitle:i}=t||{};if(!e||!r)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await _e(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let c=(await M(`
258
258
  mutation LinkAttachment($input: AttachmentCreateInput!) {
259
259
  attachmentCreate(input: $input) {
260
260
  success
261
261
  attachment { id url title }
262
262
  }
263
263
  }
264
- `,{input:{issueId:o.id,url:r,title:i||r,subtitle:n||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!a?.success,attachmentId:a?.attachment?.id,url:a?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}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 Ct(s){return(await M(`
264
+ `,{input:{issueId:o.id,url:r,title:n||r,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: ${s}`})}}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 Kt(s){return(await M(`
265
265
  query TeamByKey($filter: TeamFilter) {
266
266
  teams(first: 1, filter: $filter) { nodes { id key } }
267
267
  }
268
- `,{filter:{key:{eq:s}}}))?.teams?.nodes?.[0]?.id||null}async function he(s,t=Ai){let e=String(s).trim(),r=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(e);if(r){let n=r[1].toUpperCase(),o=Number(r[2]);return(await M(`
268
+ `,{filter:{key:{eq:s}}}))?.teams?.nodes?.[0]?.id||null}async function _e(s,t=Gn){let e=String(s).trim(),r=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(e);if(r){let i=r[1].toUpperCase(),o=Number(r[2]);return(await M(`
269
269
  query IssueByIdentifier($filter: IssueFilter) {
270
270
  issues(first: 1, filter: $filter) {
271
271
  nodes { ${t} }
272
272
  }
273
273
  }
274
- `,{filter:{number:{eq:o},team:{key:{eq:n}}}}))?.issues?.nodes?.[0]||null}return(await M(`
274
+ `,{filter:{number:{eq:o},team:{key:{eq:i}}}}))?.issues?.nodes?.[0]||null}return(await M(`
275
275
  query IssueById($id: String!) {
276
276
  issue(id: $id) { ${t} }
277
277
  }
278
- `,{id:e}))?.issue||null}var Ut={id:"plane",serverName:"plane",allowedTools:["mcp__plane__*"],requiresIntegration:I.PLANE,envKeys:["PLANE_API_KEY","PLANE_WORKSPACE_SLUG","PLANE_BASE_URL"],description:"Plane \u2014 projects, work items, cycles, modules, epics, comments (official MCP, API key)",tools:[],promptFragment:`## Plane (connected)
278
+ `,{id:e}))?.issue||null}var Ft={id:"plane",serverName:"plane",allowedTools:["mcp__plane__*"],requiresIntegration:v.PLANE,envKeys:["PLANE_API_KEY","PLANE_WORKSPACE_SLUG","PLANE_BASE_URL"],description:"Plane \u2014 projects, work items, cycles, modules, epics, comments (official MCP, API key)",tools:[],promptFragment:`## Plane (connected)
279
279
  You have direct access to the user's Plane workspace via the official Plane MCP server. All Plane tools are available under the mcp__plane__* namespace \u2014 use them proactively to read and write projects, work items (issues), cycles, modules, epics, sub-issues, comments, labels, states, pages, and workspace data.
280
280
 
281
281
  - List/get projects and work items, then create/update/delete or search work items as needed.
282
282
  - For status changes, read the project's available states first, then set the work item's state.
283
283
  - Cycles and modules group work items \u2014 list them to scope queries before drilling into items.
284
- - Always operate within the connected workspace; the workspace slug and base URL are pre-configured (Plane Cloud, self-hosted, or Zibby-hosted all work transparently).`,resolve(){let s={};for(let t of this.envKeys)process.env[t]&&(s[t]=process.env[t]);return{type:"stdio",command:"uvx",args:["plane-mcp-server","stdio"],env:s,description:this.description}}};import{existsSync as Ei}from"fs";import{fileURLToPath as ji}from"url";import{dirname as Li,resolve as $i}from"path";import{resolveIntegrationToken as xi}from"@zibby/core/backend-client.js";function Ci(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Li(ji(import.meta.url)),t=$i(s,"..","bin","mcp-skill.mjs");return Ei(t)?t:null}async function qt(){let s=await xi(I.OPEN_DESIGN),t=s?.token,e=s?.baseUrl;if(!t||typeof t!="string")throw new Error("OpenDesign is not connected: missing token. Connect it in Integrations.");if(!e||typeof e!="string")throw new Error("OpenDesign is not connected: missing baseUrl. Connect it in Integrations.");let r=e.replace(/\/+$/,"");return{token:t,baseUrl:r}}async function V(s,t={}){let{token:e,baseUrl:r}=await qt(),i=`${r}/api${s}`;if(t.query&&typeof t.query=="object"){let c=new URLSearchParams;for(let[d,l]of Object.entries(t.query))l!=null&&l!==""&&c.set(d,String(l));let a=c.toString();a&&(i+=(i.includes("?")?"&":"?")+a)}let n={Authorization:`Bearer ${e}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},o=await fetch(i,{method:t.method||"GET",headers:n,body:t.body?JSON.stringify(t.body):void 0});return Dt(o,"OpenDesign")}async function Dt(s,t){if(!s.ok){let r=await s.text().catch(()=>""),i=r.slice(0,300);try{let n=JSON.parse(r),o=n?.code||n?.error?.code,c=n?.message||n?.error?.message||n?.error;(o||c)&&(i=[o?`[${o}]`:null,c].filter(Boolean).join(" ")||i)}catch{}throw new Error(`${t} API ${s.status}: ${i}`)}let e=await s.text().catch(()=>"");if(!e)return{};try{return JSON.parse(e)}catch{return{raw:e}}}var Jt={id:"open-design",serverName:"opendesign",allowedTools:["mcp__opendesign__*"],envKeys:[],description:"OpenDesign \u2014 list projects/designs, run the design agent, and export decks to PDF/HTML",promptFragment:`## OpenDesign (optional)
284
+ - Always operate within the connected workspace; the workspace slug and base URL are pre-configured (Plane Cloud, self-hosted, or Zibby-hosted all work transparently).`,resolve(){let s={};for(let t of this.envKeys)process.env[t]&&(s[t]=process.env[t]);return{type:"stdio",command:"uvx",args:["plane-mcp-server","stdio"],env:s,description:this.description}}};import{existsSync as Fn}from"fs";import{fileURLToPath as Hn}from"url";import{dirname as zn,resolve as Yn}from"path";import{resolveIntegrationToken as Wn}from"@zibby/core/backend-client.js";function Zn(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=zn(Hn(import.meta.url)),t=Yn(s,"..","bin","mcp-skill.mjs");return Fn(t)?t:null}async function Ht(){let s=await Wn(v.OPEN_DESIGN),t=s?.token,e=s?.baseUrl;if(!t||typeof t!="string")throw new Error("OpenDesign is not connected: missing token. Connect it in Integrations.");if(!e||typeof e!="string")throw new Error("OpenDesign is not connected: missing baseUrl. Connect it in Integrations.");let r=e.replace(/\/+$/,"");return{token:t,baseUrl:r}}async function V(s,t={}){let{token:e,baseUrl:r}=await Ht(),n=`${r}/api${s}`;if(t.query&&typeof t.query=="object"){let a=new URLSearchParams;for(let[d,l]of Object.entries(t.query))l!=null&&l!==""&&a.set(d,String(l));let c=a.toString();c&&(n+=(n.includes("?")?"&":"?")+c)}let i={Authorization:`Bearer ${e}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},o=await fetch(n,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});return zt(o,"OpenDesign")}async function zt(s,t){if(!s.ok){let r=await s.text().catch(()=>""),n=r.slice(0,300);try{let i=JSON.parse(r),o=i?.code||i?.error?.code,a=i?.message||i?.error?.message||i?.error;(o||a)&&(n=[o?`[${o}]`:null,a].filter(Boolean).join(" ")||n)}catch{}throw new Error(`${t} API ${s.status}: ${n}`)}let e=await s.text().catch(()=>"");if(!e)return{};try{return JSON.parse(e)}catch{return{raw:e}}}var Yt={id:"open-design",serverName:"opendesign",allowedTools:["mcp__opendesign__*"],envKeys:[],description:"OpenDesign \u2014 list projects/designs, run the design agent, and export decks to PDF/HTML",promptFragment:`## OpenDesign (optional)
285
285
  You may have access to the user's OpenDesign workspace (the Zibby-managed design/deck app) via its REST API. These tools are OPTIONAL \u2014 if OpenDesign is not connected they will return a "not connected" error; reach for them only when the task involves OpenDesign projects, designs, or exports. Tools (mcp__opendesign__*):
286
286
 
287
287
  ### Connectivity
@@ -303,32 +303,34 @@ You may have access to the user's OpenDesign workspace (the Zibby-managed design
303
303
 
304
304
  ### Notes
305
305
  - A design artifact lookup ALWAYS needs its projectId (it scopes the query).
306
- - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let s=Ci();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/opendesign.js","opendesignSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"opendesign_health":{let{baseUrl:e}=await qt(),r=await fetch(`${e}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),i=await Dt(r,"OpenDesign");return JSON.stringify({ok:!0,health:i})}case"opendesign_list_projects":{let e=await V("/projects");return JSON.stringify(e)}case"opendesign_get_project":{let e=t?.id||t?.projectId;if(!e)return JSON.stringify({error:"id is required"});let r=await V(`/projects/${encodeURIComponent(e)}`);return JSON.stringify(r)}case"opendesign_list_designs":{let e=t?.projectId;if(!e)return JSON.stringify({error:"projectId is required"});let r=await V("/live-artifacts",{query:{projectId:e}});return JSON.stringify(r)}case"opendesign_get_design":{let e=t?.id,r=t?.projectId;if(!e)return JSON.stringify({error:"id is required"});if(!r)return JSON.stringify({error:"projectId is required"});let i=await V(`/live-artifacts/${encodeURIComponent(e)}`,{query:{projectId:r}});return JSON.stringify(i)}case"opendesign_export_pdf":{let e=t?.projectId||t?.id,{fileName:r,title:i,deck:n}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"fileName is required"});let o={fileName:r};i!==void 0&&(o.title=i),n!==void 0&&(o.deck=n);let c=await V(`/projects/${encodeURIComponent(e)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(c)}case"opendesign_export_html":{let e=t?.projectId||t?.id,r=t?.path;if(!e)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"path is required (the export sub-path)"});let n=String(r).replace(/^\/+/,"").split("/").map(c=>encodeURIComponent(c)).join("/"),o=await V(`/projects/${encodeURIComponent(e)}/export/${n}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:e,message:r,projectId:i,conversationId:n,model:o}=t||{};if(!e)return JSON.stringify({error:"agentId is required"});if(!r)return JSON.stringify({error:"message is required"});let c={agentId:e,message:r};i!==void 0&&(c.projectId=i),n!==void 0&&(c.conversationId=n),o!==void 0&&(c.model=o);let a=await V("/runs",{method:"POST",body:c});return JSON.stringify(a)}case"opendesign_cli_status":{let e=t?.id||t?.runId;if(!e)return JSON.stringify({error:"id (runId) is required"});let r=await V(`/runs/${encodeURIComponent(e)}`);return JSON.stringify(r)}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"opendesign_health",description:"Probe the OpenDesign instance (GET /api/health, no auth). Use to confirm connectivity before other calls.",input_schema:{type:"object",properties:{}}},{name:"opendesign_list_projects",description:"List the projects in the OpenDesign workspace.",input_schema:{type:"object",properties:{}}},{name:"opendesign_get_project",description:"Get a single OpenDesign project by id.",input_schema:{type:"object",properties:{id:{type:"string",description:"The project id."}},required:["id"]}},{name:"opendesign_list_designs",description:"List the live design artifacts in an OpenDesign project. Requires the projectId, which scopes the query.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id whose designs to list."}},required:["projectId"]}},{name:"opendesign_get_design",description:"Get a single live design artifact by id. Requires both the design id and its projectId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The live-artifact (design) id."},projectId:{type:"string",description:"The project id the design belongs to (scopes the lookup)."}},required:["id","projectId"]}},{name:"opendesign_export_pdf",description:"Export an OpenDesign project deck to PDF. Returns the export result (e.g. a download URL/path).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},fileName:{type:"string",description:"The output PDF file name."},title:{type:"string",description:"Optional deck title for the PDF."},deck:{description:"Optional deck payload/override to render instead of the project's current deck."}},required:["projectId","fileName"]}},{name:"opendesign_export_html",description:"Fetch an OpenDesign project's HTML export by sub-path (requested inline). Requires projectId and the export path.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},path:{type:"string",description:'The export sub-path under /projects/:id/export/ (e.g. "index.html" or a slide path).'}},required:["projectId","path"]}},{name:"opendesign_cli_run",description:"Start an OpenDesign agent run. Returns a runId; poll opendesign_cli_status with it until the run finishes.",input_schema:{type:"object",properties:{agentId:{type:"string",description:"The OpenDesign agent id to run."},message:{type:"string",description:"The instruction/message to send to the agent."},projectId:{type:"string",description:"Optional project id to scope the run to."},conversationId:{type:"string",description:"Optional conversation id to continue an existing thread."},model:{type:"string",description:"Optional model id override for the run."}},required:["agentId","message"]}},{name:"opendesign_cli_status",description:"Poll the status of an OpenDesign agent run by its runId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The runId returned by opendesign_cli_run."}},required:["id"]}}]};import{existsSync as Pi}from"fs";import{fileURLToPath as Ui}from"url";import{dirname as qi,resolve as Di}from"path";import{resolveIntegrationToken as Ji}from"@zibby/core/backend-client.js";function Mi(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let s=qi(Ui(import.meta.url)),t=Di(s,"..","bin","mcp-slack.mjs");return Pi(t)?t:null}async function D(s,t={}){let{token:e}=await Ji("slack"),r=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(s),i=`https://slack.com/api/${s}`,n={Authorization:`Bearer ${e}`},o;if(r){let d=new URLSearchParams(t).toString();d&&(i+=`?${d}`)}else n["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(t);let a=await(await fetch(i,{method:r?"GET":"POST",headers:n,body:o})).json();if(!a.ok)throw new Error(`Slack API error: ${a.error}`);return a}var x={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:I.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
306
+ - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let s=Zn();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/opendesign.js","opendesignSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"opendesign_health":{let{baseUrl:e}=await Ht(),r=await fetch(`${e}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),n=await zt(r,"OpenDesign");return JSON.stringify({ok:!0,health:n})}case"opendesign_list_projects":{let e=await V("/projects");return JSON.stringify(e)}case"opendesign_get_project":{let e=t?.id||t?.projectId;if(!e)return JSON.stringify({error:"id is required"});let r=await V(`/projects/${encodeURIComponent(e)}`);return JSON.stringify(r)}case"opendesign_list_designs":{let e=t?.projectId;if(!e)return JSON.stringify({error:"projectId is required"});let r=await V("/live-artifacts",{query:{projectId:e}});return JSON.stringify(r)}case"opendesign_get_design":{let e=t?.id,r=t?.projectId;if(!e)return JSON.stringify({error:"id is required"});if(!r)return JSON.stringify({error:"projectId is required"});let n=await V(`/live-artifacts/${encodeURIComponent(e)}`,{query:{projectId:r}});return JSON.stringify(n)}case"opendesign_export_pdf":{let e=t?.projectId||t?.id,{fileName:r,title:n,deck:i}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"fileName is required"});let o={fileName:r};n!==void 0&&(o.title=n),i!==void 0&&(o.deck=i);let a=await V(`/projects/${encodeURIComponent(e)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(a)}case"opendesign_export_html":{let e=t?.projectId||t?.id,r=t?.path;if(!e)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"path is required (the export sub-path)"});let i=String(r).replace(/^\/+/,"").split("/").map(a=>encodeURIComponent(a)).join("/"),o=await V(`/projects/${encodeURIComponent(e)}/export/${i}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:e,message:r,projectId:n,conversationId:i,model:o}=t||{};if(!e)return JSON.stringify({error:"agentId is required"});if(!r)return JSON.stringify({error:"message is required"});let a={agentId:e,message:r};n!==void 0&&(a.projectId=n),i!==void 0&&(a.conversationId=i),o!==void 0&&(a.model=o);let c=await V("/runs",{method:"POST",body:a});return JSON.stringify(c)}case"opendesign_cli_status":{let e=t?.id||t?.runId;if(!e)return JSON.stringify({error:"id (runId) is required"});let r=await V(`/runs/${encodeURIComponent(e)}`);return JSON.stringify(r)}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"opendesign_health",description:"Probe the OpenDesign instance (GET /api/health, no auth). Use to confirm connectivity before other calls.",input_schema:{type:"object",properties:{}}},{name:"opendesign_list_projects",description:"List the projects in the OpenDesign workspace.",input_schema:{type:"object",properties:{}}},{name:"opendesign_get_project",description:"Get a single OpenDesign project by id.",input_schema:{type:"object",properties:{id:{type:"string",description:"The project id."}},required:["id"]}},{name:"opendesign_list_designs",description:"List the live design artifacts in an OpenDesign project. Requires the projectId, which scopes the query.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id whose designs to list."}},required:["projectId"]}},{name:"opendesign_get_design",description:"Get a single live design artifact by id. Requires both the design id and its projectId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The live-artifact (design) id."},projectId:{type:"string",description:"The project id the design belongs to (scopes the lookup)."}},required:["id","projectId"]}},{name:"opendesign_export_pdf",description:"Export an OpenDesign project deck to PDF. Returns the export result (e.g. a download URL/path).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},fileName:{type:"string",description:"The output PDF file name."},title:{type:"string",description:"Optional deck title for the PDF."},deck:{description:"Optional deck payload/override to render instead of the project's current deck."}},required:["projectId","fileName"]}},{name:"opendesign_export_html",description:"Fetch an OpenDesign project's HTML export by sub-path (requested inline). Requires projectId and the export path.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},path:{type:"string",description:'The export sub-path under /projects/:id/export/ (e.g. "index.html" or a slide path).'}},required:["projectId","path"]}},{name:"opendesign_cli_run",description:"Start an OpenDesign agent run. Returns a runId; poll opendesign_cli_status with it until the run finishes.",input_schema:{type:"object",properties:{agentId:{type:"string",description:"The OpenDesign agent id to run."},message:{type:"string",description:"The instruction/message to send to the agent."},projectId:{type:"string",description:"Optional project id to scope the run to."},conversationId:{type:"string",description:"Optional conversation id to continue an existing thread."},model:{type:"string",description:"Optional model id override for the run."}},required:["agentId","message"]}},{name:"opendesign_cli_status",description:"Poll the status of an OpenDesign agent run by its runId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The runId returned by opendesign_cli_run."}},required:["id"]}}]};import{existsSync as Vn}from"fs";import{fileURLToPath as Qn}from"url";import{dirname as Xn,resolve as ei}from"path";import{resolveIntegrationToken as ti}from"@zibby/core/backend-client.js";function ri(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let s=Xn(Qn(import.meta.url)),t=ei(s,"..","bin","mcp-slack.mjs");return Vn(t)?t:null}async function D(s,t={}){let{token:e}=await ti("slack"),r=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(s),n=`https://slack.com/api/${s}`,i={Authorization:`Bearer ${e}`},o;if(r){let d=new URLSearchParams(t).toString();d&&(n+=`?${d}`)}else i["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(t);let c=await(await fetch(n,{method:r?"GET":"POST",headers:i,body:o})).json();if(!c.ok)throw new Error(`Slack API error: ${c.error}`);return c}var $={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:v.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
307
307
  You have access to the user's Slack workspace. Use these tools:
308
308
  - slack_list_channels, slack_post_message, slack_reply_to_thread
309
309
  - slack_add_reaction, slack_get_channel_history, slack_get_thread_replies
310
310
  - slack_get_users, slack_get_user_profile
311
311
  - slack_lookup_user_by_email (precise email\u2192user_id, prefer this over scanning slack_get_users)
312
- - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let s=Mi();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"slack_list_channels":{let e=await D("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(e.channels||[]).map(r=>({id:r.id,name:r.name,topic:r.topic?.value}))})}case"slack_post_message":{if(!t.channel||!t.text)return JSON.stringify({error:"channel and text are required"});let e=await D("chat.postMessage",{channel:t.channel,text:t.text,...t.blocks?{blocks:t.blocks}:{}});return JSON.stringify({ok:!0,ts:e.ts,channel:e.channel})}case"slack_reply_to_thread":{if(!t.channel||!t.thread_ts||!t.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let e=await D("chat.postMessage",{channel:t.channel,thread_ts:t.thread_ts,text:t.text});return JSON.stringify({ok:!0,ts:e.ts})}case"slack_add_reaction":return!t.channel||!t.timestamp||!t.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await D("reactions.add",{channel:t.channel,timestamp:t.timestamp,name:t.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!t.channel)return JSON.stringify({error:"channel is required"});let e=await D("conversations.history",{channel:t.channel,limit:t.limit||20});return JSON.stringify({messages:(e.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.ts}))})}case"slack_get_thread_replies":{if(!t.channel||!t.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let e=await D("conversations.replies",{channel:t.channel,ts:t.thread_ts});return JSON.stringify({messages:(e.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.ts}))})}case"slack_get_users":{let e=await D("users.list",{limit:100});return JSON.stringify({users:(e.members||[]).filter(r=>!r.is_bot&&!r.deleted).map(r=>({id:r.id,name:r.real_name||r.name}))})}case"slack_get_user_profile":{if(!t.user_id)return JSON.stringify({error:"user_id is required"});let e=await D("users.profile.get",{user:t.user_id});return JSON.stringify({profile:e.profile})}case"slack_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});try{let e=await D("users.lookupByEmail",{email:t.email});return JSON.stringify({ok:!0,user:{id:e.user?.id,name:e.user?.real_name||e.user?.name,email:e.user?.profile?.email||t.email}})}catch(e){if(/users_not_found/.test(e.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw e}}case"slack_list_usergroups":{let e=await D("usergroups.list",{});return JSON.stringify({usergroups:(e.usergroups||[]).map(r=>({id:r.id,handle:r.handle,name:r.name,description:r.description||"",user_count:Number(r.user_count||0)}))})}case"slack_get_usergroup_members":{if(!t.usergroup)return JSON.stringify({error:"usergroup id is required"});let e=await D("usergroups.users.list",{usergroup:t.usergroup});return JSON.stringify({users:e.users||[]})}case"slack_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let r=Math.max(1,Math.min(Number(t.limit)||5,25)),i=[],n,o=5;for(let a=0;a<o;a+=1){let d={limit:200};n&&(d.cursor=n);let l=await D("users.list",d);for(let u of l.members||[])u.deleted||u.is_bot||i.push(u);if(n=l.response_metadata?.next_cursor,!n)break}let c=[];for(let a of i){let d=(a.real_name||"").toLowerCase(),l=(a.profile?.display_name||"").toLowerCase(),u=(a.name||"").toLowerCase(),p=0;d.includes(e)&&(p+=100-Math.abs(d.length-e.length)),l.includes(e)&&(p+=60-Math.abs(l.length-e.length)),u.includes(e)&&(p+=30-Math.abs(u.length-e.length)),(d===e||l===e)&&(p+=200),p>0&&c.push({id:a.id,name:a.real_name||a.profile?.display_name||a.name,email:a.profile?.email||void 0,_score:p})}return c.sort((a,d)=>d._score-a._score),JSON.stringify({ok:!0,matches:c.slice(0,r).map(({_score:a,...d})=>d),scanned:i.length})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as Bi}from"fs";import{fileURLToPath as Ki}from"url";import{dirname as Gi,resolve as Fi}from"path";import{resolveIntegrationToken as Hi}from"@zibby/core/backend-client.js";function zi(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let s=Gi(Ki(import.meta.url)),t=Fi(s,"..","bin","mcp-lark.mjs");return Bi(t)?t:null}var Yi=6e3*1e3,ge=null;async function Wi(){let{appId:s,appSecret:t,host:e}=await Hi("lark");if(ge&&ge.appId===s&&ge.expiresAt>Date.now())return{token:ge.token,host:e};let i=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:s,app_secret:t})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return ge={token:i.tenant_access_token,expiresAt:Date.now()+Yi,appId:s},{token:i.tenant_access_token,host:e}}async function re(s,t,e={}){let{token:r,host:i}=await Wi(),n=`${i}${t}`,o={method:s,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}};s!=="GET"&&(o.body=JSON.stringify(e));let a=await(await fetch(n,o)).json();if(a.code!==0)throw new Error(`Lark API ${t} error: ${a.msg||a.code}`);return a.data||{}}function Mt(s){return JSON.stringify({text:s})}function Zi(s){return!s||typeof s!="string"||s.startsWith("oc_")?"chat_id":s.startsWith("ou_")?"open_id":s.startsWith("on_")?"union_id":s.startsWith("cli_")?"app_id":s.includes("@")?"email":"chat_id"}var K={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:I.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
312
+ - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let s=ri();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"slack_list_channels":{let e=await D("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(e.channels||[]).map(r=>({id:r.id,name:r.name,topic:r.topic?.value}))})}case"slack_post_message":{if(!t.channel||!t.text)return JSON.stringify({error:"channel and text are required"});let e=await D("chat.postMessage",{channel:t.channel,text:t.text,...t.blocks?{blocks:t.blocks}:{}});return JSON.stringify({ok:!0,ts:e.ts,channel:e.channel})}case"slack_reply_to_thread":{if(!t.channel||!t.thread_ts||!t.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let e=await D("chat.postMessage",{channel:t.channel,thread_ts:t.thread_ts,text:t.text});return JSON.stringify({ok:!0,ts:e.ts})}case"slack_add_reaction":return!t.channel||!t.timestamp||!t.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await D("reactions.add",{channel:t.channel,timestamp:t.timestamp,name:t.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!t.channel)return JSON.stringify({error:"channel is required"});let e=await D("conversations.history",{channel:t.channel,limit:t.limit||20});return JSON.stringify({messages:(e.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.ts}))})}case"slack_get_thread_replies":{if(!t.channel||!t.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let e=await D("conversations.replies",{channel:t.channel,ts:t.thread_ts});return JSON.stringify({messages:(e.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.ts}))})}case"slack_get_users":{let e=await D("users.list",{limit:100});return JSON.stringify({users:(e.members||[]).filter(r=>!r.is_bot&&!r.deleted).map(r=>({id:r.id,name:r.real_name||r.name}))})}case"slack_get_user_profile":{if(!t.user_id)return JSON.stringify({error:"user_id is required"});let e=await D("users.profile.get",{user:t.user_id});return JSON.stringify({profile:e.profile})}case"slack_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});try{let e=await D("users.lookupByEmail",{email:t.email});return JSON.stringify({ok:!0,user:{id:e.user?.id,name:e.user?.real_name||e.user?.name,email:e.user?.profile?.email||t.email}})}catch(e){if(/users_not_found/.test(e.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw e}}case"slack_list_usergroups":{let e=await D("usergroups.list",{});return JSON.stringify({usergroups:(e.usergroups||[]).map(r=>({id:r.id,handle:r.handle,name:r.name,description:r.description||"",user_count:Number(r.user_count||0)}))})}case"slack_get_usergroup_members":{if(!t.usergroup)return JSON.stringify({error:"usergroup id is required"});let e=await D("usergroups.users.list",{usergroup:t.usergroup});return JSON.stringify({users:e.users||[]})}case"slack_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let r=Math.max(1,Math.min(Number(t.limit)||5,25)),n=[],i,o=5;for(let c=0;c<o;c+=1){let d={limit:200};i&&(d.cursor=i);let l=await D("users.list",d);for(let u of l.members||[])u.deleted||u.is_bot||n.push(u);if(i=l.response_metadata?.next_cursor,!i)break}let a=[];for(let c of n){let d=(c.real_name||"").toLowerCase(),l=(c.profile?.display_name||"").toLowerCase(),u=(c.name||"").toLowerCase(),p=0;d.includes(e)&&(p+=100-Math.abs(d.length-e.length)),l.includes(e)&&(p+=60-Math.abs(l.length-e.length)),u.includes(e)&&(p+=30-Math.abs(u.length-e.length)),(d===e||l===e)&&(p+=200),p>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:p})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,r).map(({_score:c,...d})=>d),scanned:n.length})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as si}from"fs";import{fileURLToPath as ni}from"url";import{dirname as ii,resolve as oi}from"path";import{resolveIntegrationToken as ai}from"@zibby/core/backend-client.js";function ci(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let s=ii(ni(import.meta.url)),t=oi(s,"..","bin","mcp-lark.mjs");return si(t)?t:null}var li=6e3*1e3,ke=null;async function di(){let{appId:s,appSecret:t,host:e}=await ai("lark");if(ke&&ke.appId===s&&ke.expiresAt>Date.now())return{token:ke.token,host:e};let n=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:s,app_secret:t})})).json();if(n.code!==0)throw new Error(`Lark tenant_access_token failed: ${n.msg||n.code}`);return ke={token:n.tenant_access_token,expiresAt:Date.now()+li,appId:s},{token:n.tenant_access_token,host:e}}async function se(s,t,e={}){let{token:r,host:n}=await di(),i=`${n}${t}`,o={method:s,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}};s!=="GET"&&(o.body=JSON.stringify(e));let c=await(await fetch(i,o)).json();if(c.code!==0)throw new Error(`Lark API ${t} error: ${c.msg||c.code}`);return c.data||{}}function Wt(s){return JSON.stringify({text:s})}function ui(s){return!s||typeof s!="string"||s.startsWith("oc_")?"chat_id":s.startsWith("ou_")?"open_id":s.startsWith("on_")?"union_id":s.startsWith("cli_")?"app_id":s.includes("@")?"email":"chat_id"}var K={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:v.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
313
313
  You can send messages and replies on Lark. Use:
314
314
  - lark_send_message: post a message to a chat, user, or DM
315
315
  - lark_reply: reply to an existing message (threaded)
316
316
  - lark_list_chats: list chats the bot is a member of
317
317
  - lark_get_chat_history: fetch recent messages in a chat
318
318
  - lark_lookup_user_by_email: resolve an email \u2192 open_id for direct DM (prefer this over emailing through lark_send_message when the agent has a user_id already)
319
- When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let s=zi();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},tools:[{name:"lark_send_message",description:"Send a text message to a Lark chat, user, or DM. receive_id can be a chat_id (oc_*), open_id (ou_*), union_id (on_*), or email.",input_schema:{type:"object",properties:{receive_id:{type:"string",description:"Target id: chat_id (oc_*), open_id (ou_*), union_id (on_*), or email"},text:{type:"string",description:"Message text"}},required:["receive_id","text"]}},{name:"lark_reply",description:"Reply to an existing Lark message (creates a thread). Use the message_id from the inbound event.",input_schema:{type:"object",properties:{message_id:{type:"string",description:"Lark message id (om_*) to reply to"},text:{type:"string",description:"Reply text"}},required:["message_id","text"]}},{name:"lark_list_chats",description:"List chats (groups + DMs) the bot is a member of.",input_schema:{type:"object",properties:{page_size:{type:"number",description:"Max results (default 50)"}}}},{name:"lark_get_chat_history",description:"Fetch recent messages in a chat.",input_schema:{type:"object",properties:{chat_id:{type:"string",description:"Chat id (oc_*)"},page_size:{type:"number",description:"Max messages (default 20)"}},required:["chat_id"]}},{name:"lark_lookup_user_by_email",description:"Resolve an email address to a Lark user id (open_id). Returns { ok:true, user:{open_id,email,name} } on hit, { ok:false } if no Lark user has that email. Use the open_id as `receive_id` in lark_send_message to DM.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"lark_search_users",description:'Fuzzy-search users by name across chats the bot is a member of. Lark has no public org-wide user search API for bots \u2014 this walks the bot\'s chat memberships and matches names client-side. Best for "send to Sam" style routing where you have a name but no email. Returns up to `limit` ranked matches { open_id, name }.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against user names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}],async handleToolCall(s,t){try{switch(s){case"lark_send_message":{if(!t.receive_id||!t.text)return JSON.stringify({error:"receive_id and text are required"});let e=Zi(t.receive_id),r=await re("POST",`/open-apis/im/v1/messages?receive_id_type=${e}`,{receive_id:t.receive_id,msg_type:"text",content:Mt(t.text)});return JSON.stringify({ok:!0,message_id:r.message_id})}case"lark_reply":{if(!t.message_id||!t.text)return JSON.stringify({error:"message_id and text are required"});let e=await re("POST",`/open-apis/im/v1/messages/${encodeURIComponent(t.message_id)}/reply`,{msg_type:"text",content:Mt(t.text)});return JSON.stringify({ok:!0,message_id:e.message_id})}case"lark_list_chats":{let e=t.page_size||50,i=((await re("GET",`/open-apis/im/v1/chats?page_size=${e}`)).items||[]).map(n=>({chat_id:n.chat_id,name:n.name,description:n.description,owner_id:n.owner_id,chat_mode:n.chat_mode}));return JSON.stringify({chats:i})}case"lark_get_chat_history":{if(!t.chat_id)return JSON.stringify({error:"chat_id is required"});let e=t.page_size||20,i=((await re("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(t.chat_id)}&page_size=${e}&sort_type=ByCreateTimeDesc`)).items||[]).map(n=>({message_id:n.message_id,sender_id:n.sender?.id,sender_type:n.sender?.sender_type,msg_type:n.msg_type,content:n.body?.content,create_time:n.create_time}));return JSON.stringify({messages:i})}case"lark_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});let r=((await re("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[t.email]})).user_list||[]).find(i=>i.email===t.email&&i.user_id);return JSON.stringify(r?{ok:!0,user:{open_id:r.user_id,email:r.email,name:r.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let r=Math.max(1,Math.min(Number(t.limit)||5,25)),i=200,o=((await re("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(l=>l.chat_id),c=new Set,a=[];for(let l of o){if(a.length>=i)break;try{let u=await re("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let p of u.items||[])if(!(!p.member_id||c.has(p.member_id))&&(c.add(p.member_id),a.push({open_id:p.member_id,name:p.name||""}),a.length>=i))break}catch(u){console.warn(`[lark] member scan failed for ${l}: ${u.message}`)}}let d=[];for(let l of a){let u=(l.name||"").toLowerCase();if(!u)continue;let p=0;u.includes(e)&&(p+=100-Math.abs(u.length-e.length)),u===e&&(p+=200),p>0&&d.push({open_id:l.open_id,name:l.name,_score:p})}return d.sort((l,u)=>u._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,r).map(({_score:l,...u})=>u),scanned:a.length})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}}};import{existsSync as Vi}from"fs";import{fileURLToPath as Qi}from"url";import{dirname as Xi,resolve as en}from"path";import{resolveIntegrationToken as tn}from"@zibby/core/backend-client.js";function rn(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Xi(Qi(import.meta.url)),t=en(s,"..","bin","mcp-skill.mjs");return Vi(t)?t:null}var sn=process.env.DISCORD_API_URL||"https://discord.com/api/v10",nn=2e3;function on(s,t=nn){let e=String(s??"");if(!e.trim())return[];if(e.length<=t)return[e];let r=[],i=e;for(;i.length>t;){let o=i.slice(0,t).lastIndexOf(`
320
- `),c=o>t/2?o+1:t;r.push(i.slice(0,c)),i=i.slice(c)}return i&&r.push(i),r}async function Bt(){let s=(process.env.DISCORD_BOT_TOKEN||"").trim();if(s)return{token:s,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let t=await tn(I.DISCORD),e=(t&&t.token?String(t.token):"").trim();if(!e)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:e,guildId:(t.guildId||"").trim()}}async function Qe(s,t,{token:e,body:r}={}){let i=e.startsWith("Bot ")?e:`Bot ${e}`,n=await fetch(`${sn}${t}`,{method:s,headers:{Authorization:i,...r!==void 0?{"Content-Type":"application/json"}:{}},...r!==void 0?{body:JSON.stringify(r)}:{}}),o=await n.json().catch(()=>null);if(!n.ok){let c=o&&(o.message||o.error)?o.message||o.error:`HTTP ${n.status}`;throw new Error(`Discord API error (${n.status}): ${c}`)}return o}async function an({token:s,guildId:t},e){let r=String(e||"").trim()||t||(process.env.DISCORD_GUILD_ID||"").trim();if(r)return r;let i=await Qe("GET","/users/@me/guilds",{token:s}),n=Array.isArray(i)?i:[];if(n.length===1)return n[0].id;if(n.length===0)throw new Error("The bot is not in any Discord server \u2014 invite it to a server first.");let o=n.slice(0,10).map(c=>`${c.name} (${c.id})`).join(", ");throw new Error(`The bot is in ${n.length} servers \u2014 pass guildId explicitly. Servers: ${o}`)}var Kt={id:"discord",serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:I.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord (connected)
319
+ When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let s=ci();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},tools:[{name:"lark_send_message",description:"Send a text message to a Lark chat, user, or DM. receive_id can be a chat_id (oc_*), open_id (ou_*), union_id (on_*), or email.",input_schema:{type:"object",properties:{receive_id:{type:"string",description:"Target id: chat_id (oc_*), open_id (ou_*), union_id (on_*), or email"},text:{type:"string",description:"Message text"}},required:["receive_id","text"]}},{name:"lark_reply",description:"Reply to an existing Lark message (creates a thread). Use the message_id from the inbound event.",input_schema:{type:"object",properties:{message_id:{type:"string",description:"Lark message id (om_*) to reply to"},text:{type:"string",description:"Reply text"}},required:["message_id","text"]}},{name:"lark_list_chats",description:"List chats (groups + DMs) the bot is a member of.",input_schema:{type:"object",properties:{page_size:{type:"number",description:"Max results (default 50)"}}}},{name:"lark_get_chat_history",description:"Fetch recent messages in a chat.",input_schema:{type:"object",properties:{chat_id:{type:"string",description:"Chat id (oc_*)"},page_size:{type:"number",description:"Max messages (default 20)"}},required:["chat_id"]}},{name:"lark_lookup_user_by_email",description:"Resolve an email address to a Lark user id (open_id). Returns { ok:true, user:{open_id,email,name} } on hit, { ok:false } if no Lark user has that email. Use the open_id as `receive_id` in lark_send_message to DM.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"lark_search_users",description:'Fuzzy-search users by name across chats the bot is a member of. Lark has no public org-wide user search API for bots \u2014 this walks the bot\'s chat memberships and matches names client-side. Best for "send to Sam" style routing where you have a name but no email. Returns up to `limit` ranked matches { open_id, name }.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against user names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}],async handleToolCall(s,t){try{switch(s){case"lark_send_message":{if(!t.receive_id||!t.text)return JSON.stringify({error:"receive_id and text are required"});let e=ui(t.receive_id),r=await se("POST",`/open-apis/im/v1/messages?receive_id_type=${e}`,{receive_id:t.receive_id,msg_type:"text",content:Wt(t.text)});return JSON.stringify({ok:!0,message_id:r.message_id})}case"lark_reply":{if(!t.message_id||!t.text)return JSON.stringify({error:"message_id and text are required"});let e=await se("POST",`/open-apis/im/v1/messages/${encodeURIComponent(t.message_id)}/reply`,{msg_type:"text",content:Wt(t.text)});return JSON.stringify({ok:!0,message_id:e.message_id})}case"lark_list_chats":{let e=t.page_size||50,n=((await se("GET",`/open-apis/im/v1/chats?page_size=${e}`)).items||[]).map(i=>({chat_id:i.chat_id,name:i.name,description:i.description,owner_id:i.owner_id,chat_mode:i.chat_mode}));return JSON.stringify({chats:n})}case"lark_get_chat_history":{if(!t.chat_id)return JSON.stringify({error:"chat_id is required"});let e=t.page_size||20,n=((await se("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(t.chat_id)}&page_size=${e}&sort_type=ByCreateTimeDesc`)).items||[]).map(i=>({message_id:i.message_id,sender_id:i.sender?.id,sender_type:i.sender?.sender_type,msg_type:i.msg_type,content:i.body?.content,create_time:i.create_time}));return JSON.stringify({messages:n})}case"lark_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});let r=((await se("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[t.email]})).user_list||[]).find(n=>n.email===t.email&&n.user_id);return JSON.stringify(r?{ok:!0,user:{open_id:r.user_id,email:r.email,name:r.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let r=Math.max(1,Math.min(Number(t.limit)||5,25)),n=200,o=((await se("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(l=>l.chat_id),a=new Set,c=[];for(let l of o){if(c.length>=n)break;try{let u=await se("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let p of u.items||[])if(!(!p.member_id||a.has(p.member_id))&&(a.add(p.member_id),c.push({open_id:p.member_id,name:p.name||""}),c.length>=n))break}catch(u){console.warn(`[lark] member scan failed for ${l}: ${u.message}`)}}let d=[];for(let l of c){let u=(l.name||"").toLowerCase();if(!u)continue;let p=0;u.includes(e)&&(p+=100-Math.abs(u.length-e.length)),u===e&&(p+=200),p>0&&d.push({open_id:l.open_id,name:l.name,_score:p})}return d.sort((l,u)=>u._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,r).map(({_score:l,...u})=>u),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}}};import{existsSync as pi}from"fs";import{fileURLToPath as mi}from"url";import{dirname as fi,resolve as hi}from"path";import{resolveIntegrationToken as yi}from"@zibby/core/backend-client.js";function gi(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=fi(mi(import.meta.url)),t=hi(s,"..","bin","mcp-skill.mjs");return pi(t)?t:null}var _i=process.env.DISCORD_API_URL||"https://discord.com/api/v10",bi=2e3;function ki(s,t=bi){let e=String(s??"");if(!e.trim())return[];if(e.length<=t)return[e];let r=[],n=e;for(;n.length>t;){let o=n.slice(0,t).lastIndexOf(`
320
+ `),a=o>t/2?o+1:t;r.push(n.slice(0,a)),n=n.slice(a)}return n&&r.push(n),r}async function Zt(){let s=(process.env.DISCORD_BOT_TOKEN||"").trim();if(s)return{token:s,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let t=await yi(v.DISCORD),e=(t&&t.token?String(t.token):"").trim();if(!e)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:e,guildId:(t.guildId||"").trim()}}async function it(s,t,{token:e,body:r}={}){let n=e.startsWith("Bot ")?e:`Bot ${e}`,i=await fetch(`${_i}${t}`,{method:s,headers:{Authorization:n,...r!==void 0?{"Content-Type":"application/json"}:{}},...r!==void 0?{body:JSON.stringify(r)}:{}}),o=await i.json().catch(()=>null);if(!i.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${i.status}`;throw new Error(`Discord API error (${i.status}): ${a}`)}return o}async function wi({token:s,guildId:t},e){let r=String(e||"").trim()||t||(process.env.DISCORD_GUILD_ID||"").trim();if(r)return r;let n=await it("GET","/users/@me/guilds",{token:s}),i=Array.isArray(n)?n:[];if(i.length===1)return i[0].id;if(i.length===0)throw new Error("The bot is not in any Discord server \u2014 invite it to a server first.");let o=i.slice(0,10).map(a=>`${a.name} (${a.id})`).join(", ");throw new Error(`The bot is in ${i.length} servers \u2014 pass guildId explicitly. Servers: ${o}`)}var Vt={id:"discord",serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:v.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord (connected)
321
321
  You can post to the user's Discord server as their bot. Tools:
322
322
  - discord_send_message(channelId, text) \u2014 post a message to a channel (long text is auto-chunked to Discord's 2000-char limit)
323
- - discord_list_channels(guildId?) \u2014 list the server's text channels (id + name) to find where to post; guildId is optional when the bot is in one server`,resolve(){let s={};for(let e of this.envKeys)process.env[e]&&(s[e]=process.env[e]);for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_SELF_HOST","DISCORD_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(s[e]=process.env[e]);let t=rn();return t?{type:"stdio",command:"node",args:[t,"../dist/discord.js","discordSkill"],env:s,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:s,description:this.description}},async handleToolCall(s,t={}){try{switch(s){case"discord_send_message":{let e=String(t.channelId||"").trim(),r=String(t.text||"");if(!e||!r.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let i=await Bt(),n=on(r),o=[];for(let c of n){let a=await Qe("POST",`/channels/${encodeURIComponent(e)}/messages`,{token:i.token,body:{content:c}});o.push(a&&a.id?a.id:"")}return JSON.stringify({ok:!0,channelId:e,messageIds:o,chunks:n.length})}case"discord_list_channels":{let e=await Bt(),r=await an(e,t.guildId),i=await Qe("GET",`/guilds/${encodeURIComponent(r)}/channels`,{token:e.token}),n=(Array.isArray(i)?i:[]).filter(o=>o&&(o.type===0||o.type===5)).map(o=>({id:o.id,name:o.name,type:o.type===5?"announcement":"text",...o.topic?{topic:o.topic}:{}}));return JSON.stringify({ok:!0,guildId:r,channels:n})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"discord_send_message",description:"Post a message to a Discord channel as the connected bot. Text over 2000 chars is automatically split into sequential messages.",input_schema:{type:"object",properties:{channelId:{type:"string",description:"Discord channel id (snowflake). Use discord_list_channels to find it."},text:{type:"string",description:"Message text (Discord markdown supported)"}},required:["channelId","text"]}},{name:"discord_list_channels",description:"List the text channels of the connected Discord server (id + name). Pass guildId only when the bot is in multiple servers.",input_schema:{type:"object",properties:{guildId:{type:"string",description:"Discord server (guild) id \u2014 optional when the bot is in exactly one server or one was captured at connect time"}}}}]};import{existsSync as cn}from"fs";import{fileURLToPath as ln}from"url";import{dirname as dn,resolve as un}from"path";import{resolveIntegrationToken as pn,clearTokenCache as mn}from"@zibby/core/backend-client.js";function fn(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=dn(ln(import.meta.url)),t=un(s,"..","bin","mcp-skill.mjs");return cn(t)?t:null}var hn="2022-06-28",yn="https://api.notion.com/v1",Te=2e4,Gt=25,gn=25;function Ft(s){if(!s||typeof s!="string")return null;let e=s.trim().split(/[?#]/)[0],r=e.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);if(r)return r[0].toLowerCase();let i=e.match(/[0-9a-fA-F]{32}/g);if(i&&i.length){let n=i[i.length-1].toLowerCase();return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return null}async function Xe(s,t={}){let e=async()=>{let{token:r}=await pn("notion");if(typeof r!="string"||!r)throw new Error(`Invalid notion token type: ${typeof r}`);let i=await fetch(`${yn}${s}`,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,"Notion-Version":hn,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Notion API ${i.status}: ${o.slice(0,300)}`)}let n=await i.text().catch(()=>"");if(!n||!n.trim())return{};try{return JSON.parse(n)}catch{return{raw:n}}};try{return await e()}catch(r){let i=String(r?.message||r||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw r;return mn("notion"),e()}}function _e(s){if(!Array.isArray(s))return"";let t="";for(let e of s){let r=e?.plain_text??e?.text?.content??"";if(!r)continue;let i=e.annotations||{};i.code&&(r=`\`${r}\``),i.bold&&(r=`**${r}**`),i.italic&&(r=`_${r}_`),i.strikethrough&&(r=`~~${r}~~`);let n=e?.href||e?.text?.link?.url;n&&(r=`[${r}](${n})`),t+=r}return t}function _n(s,t,e){let r=s?.type,i=s?.[r]||{},n=" ".repeat(Math.max(0,t)),o=(d="rich_text")=>_e(i[d]),c;switch(r){case"paragraph":c=o();break;case"heading_1":c=`# ${o()}`;break;case"heading_2":c=`## ${o()}`;break;case"heading_3":c=`### ${o()}`;break;case"bulleted_list_item":c=`${n}- ${o()}`;break;case"numbered_list_item":c=`${n}1. ${o()}`;break;case"to_do":c=`${n}- [${i.checked?"x":" "}] ${o()}`;break;case"toggle":c=`${n}- ${o()}`;break;case"quote":c=`> ${o()}`;break;case"callout":{c=`> ${i.icon?.emoji?`${i.icon.emoji} `:""}${o()}`;break}case"code":{c=`\`\`\`${i.language||""}
323
+ - discord_list_channels(guildId?) \u2014 list the server's text channels (id + name) to find where to post; guildId is optional when the bot is in one server`,resolve(){let s={};for(let e of this.envKeys)process.env[e]&&(s[e]=process.env[e]);for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_SELF_HOST","DISCORD_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(s[e]=process.env[e]);let t=gi();return t?{type:"stdio",command:"node",args:[t,"../dist/discord.js","discordSkill"],env:s,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:s,description:this.description}},async handleToolCall(s,t={}){try{switch(s){case"discord_send_message":{let e=String(t.channelId||"").trim(),r=String(t.text||"");if(!e||!r.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let n=await Zt(),i=ki(r),o=[];for(let a of i){let c=await it("POST",`/channels/${encodeURIComponent(e)}/messages`,{token:n.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:e,messageIds:o,chunks:i.length})}case"discord_list_channels":{let e=await Zt(),r=await wi(e,t.guildId),n=await it("GET",`/guilds/${encodeURIComponent(r)}/channels`,{token:e.token}),i=(Array.isArray(n)?n:[]).filter(o=>o&&(o.type===0||o.type===5)).map(o=>({id:o.id,name:o.name,type:o.type===5?"announcement":"text",...o.topic?{topic:o.topic}:{}}));return JSON.stringify({ok:!0,guildId:r,channels:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"discord_send_message",description:"Post a message to a Discord channel as the connected bot. Text over 2000 chars is automatically split into sequential messages.",input_schema:{type:"object",properties:{channelId:{type:"string",description:"Discord channel id (snowflake). Use discord_list_channels to find it."},text:{type:"string",description:"Message text (Discord markdown supported)"}},required:["channelId","text"]}},{name:"discord_list_channels",description:"List the text channels of the connected Discord server (id + name). Pass guildId only when the bot is in multiple servers.",input_schema:{type:"object",properties:{guildId:{type:"string",description:"Discord server (guild) id \u2014 optional when the bot is in exactly one server or one was captured at connect time"}}}}]};import{existsSync as Si}from"fs";import{fileURLToPath as Ii}from"url";import{dirname as vi,resolve as Ni}from"path";import{resolveIntegrationToken as Oi,clearTokenCache as Ri}from"@zibby/core/backend-client.js";function Ti(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=vi(Ii(import.meta.url)),t=Ni(s,"..","bin","mcp-skill.mjs");return Si(t)?t:null}var Ai="2022-06-28",Ei="https://api.notion.com/v1",$e=2e4,Qt=25,Li=25;function je(s){if(!s||typeof s!="string")return null;let e=s.trim().split(/[?#]/)[0],r=e.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);if(r)return r[0].toLowerCase();let n=e.match(/[0-9a-fA-F]{32}/g);if(n&&n.length){let i=n[n.length-1].toLowerCase();return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}return null}async function we(s,t={}){let e=async()=>{let{token:r}=await Oi("notion");if(typeof r!="string"||!r)throw new Error(`Invalid notion token type: ${typeof r}`);let n=await fetch(`${Ei}${s}`,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,"Notion-Version":Ai,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Notion API ${n.status}: ${o.slice(0,300)}`)}let i=await n.text().catch(()=>"");if(!i||!i.trim())return{};try{return JSON.parse(i)}catch{return{raw:i}}};try{return await e()}catch(r){let n=String(r?.message||r||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("unauthorized")))throw r;return Ri("notion"),e()}}function de(s){if(!Array.isArray(s))return"";let t="";for(let e of s){let r=e?.plain_text??e?.text?.content??"";if(!r)continue;let n=e.annotations||{};n.code&&(r=`\`${r}\``),n.bold&&(r=`**${r}**`),n.italic&&(r=`_${r}_`),n.strikethrough&&(r=`~~${r}~~`);let i=e?.href||e?.text?.link?.url;i&&(r=`[${r}](${i})`),t+=r}return t}function xi(s,t,e){let r=s?.type,n=s?.[r]||{},i=" ".repeat(Math.max(0,t)),o=(d="rich_text")=>de(n[d]),a;switch(r){case"paragraph":a=o();break;case"heading_1":a=`# ${o()}`;break;case"heading_2":a=`## ${o()}`;break;case"heading_3":a=`### ${o()}`;break;case"bulleted_list_item":a=`${i}- ${o()}`;break;case"numbered_list_item":a=`${i}1. ${o()}`;break;case"to_do":a=`${i}- [${n.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${i}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${n.icon?.emoji?`${n.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${n.language||""}
324
324
  ${o()}
325
- \`\`\``;break}case"divider":c="---";break;case"child_page":c=`[child page: ${i.title||""}]`;break;case"child_database":c=`[child database: ${i.title||""}]`;break;case"bookmark":case"embed":case"link_preview":c=i.url?`<${i.url}>`:"";break;case"equation":c=i.expression?`$${i.expression}$`:"";break;case"table":case"column_list":case"column":c="";break;case"table_row":{let d=(i.cells||[]).map(l=>_e(l).trim());c=`${n}| ${d.join(" | ")} |`;break}default:c=o();break}let a=[];return c&&c.trim()&&a.push(c),e&&e.trim()&&a.push(e),a.join(`
326
- `)}async function zt(s,t,e){let r=[],i,n=0;do{if(e.used>=Te)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let c=await Xe(`/blocks/${s}/children?${o.toString()}`),a=Array.isArray(c.results)?c.results:[];for(let d of a){let l="";d.has_children&&(l=await zt(d.id,t+1,e));let u=_n(d,t,l);if(u&&(r.push(u),e.used+=u.length+1),e.used>=Te)break}i=c.has_more?c.next_cursor:void 0,n+=1}while(i&&n<gn);return r.join(`
327
- `)}function Ht(s){let t=s?.properties||{};for(let e of Object.values(t))if(e?.type==="title"){let r=_e(e.title).trim();if(r)return r}return""}function bn(s){if(!s||!s.type)return"";switch(s.type){case"title":return _e(s.title).trim();case"rich_text":return _e(s.rich_text).trim();case"number":return s.number==null?"":String(s.number);case"select":return s.select?.name||"";case"status":return s.status?.name||"";case"multi_select":return(s.multi_select||[]).map(e=>e.name).join(", ");case"checkbox":return s.checkbox?"true":"false";case"url":return s.url||"";case"email":return s.email||"";case"phone_number":return s.phone_number||"";case"date":return s.date?.start||"";case"people":return(s.people||[]).map(e=>e.name||e.id).join(", ");default:return""}}var Yt={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:I.NOTION,description:"Notion read-only context (pull a page/database as markdown)",promptFragment:`## Notion (connected, read-only context)
325
+ \`\`\``;break}case"divider":a="---";break;case"child_page":a=`[child page: ${n.title||""}]`;break;case"child_database":a=`[child database: ${n.title||""}]`;break;case"bookmark":case"embed":case"link_preview":a=n.url?`<${n.url}>`:"";break;case"equation":a=n.expression?`$${n.expression}$`:"";break;case"table":case"column_list":case"column":a="";break;case"table_row":{let d=(n.cells||[]).map(l=>de(l).trim());a=`${i}| ${d.join(" | ")} |`;break}default:a=o();break}let c=[];return a&&a.trim()&&c.push(a),e&&e.trim()&&c.push(e),c.join(`
326
+ `)}async function tr(s,t,e){let r=[],n,i=0;do{if(e.used>=$e)break;let o=new URLSearchParams({page_size:"100"});n&&o.set("start_cursor",n);let a=await we(`/blocks/${s}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await tr(d.id,t+1,e));let u=xi(d,t,l);if(u&&(r.push(u),e.used+=u.length+1),e.used>=$e)break}n=a.has_more?a.next_cursor:void 0,i+=1}while(n&&i<Li);return r.join(`
327
+ `)}function Xt(s){let t=s?.properties||{};for(let e of Object.values(t))if(e?.type==="title"){let r=de(e.title).trim();if(r)return r}return""}function er(s){let t=String(s??"");if(!t)return[{type:"text",text:{content:""}}];let e=[];for(let r=0;r<t.length;r+=2e3)e.push({type:"text",text:{content:t.slice(r,r+2e3)}});return e}function ji(s){return{id:s?.id||"",discussionId:s?.discussion_id||"",text:de(s?.rich_text).trim(),author:s?.created_by?.id||"",createdTime:s?.created_time||""}}function $i(s){if(!s||!s.type)return"";switch(s.type){case"title":return de(s.title).trim();case"rich_text":return de(s.rich_text).trim();case"number":return s.number==null?"":String(s.number);case"select":return s.select?.name||"";case"status":return s.status?.name||"";case"multi_select":return(s.multi_select||[]).map(e=>e.name).join(", ");case"checkbox":return s.checkbox?"true":"false";case"url":return s.url||"";case"email":return s.email||"";case"phone_number":return s.phone_number||"";case"date":return s.date?.start||"";case"people":return(s.people||[]).map(e=>e.name||e.id).join(", ");default:return""}}var rr={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:v.NOTION,description:"Notion read-only context (pull a page/database as markdown)",promptFragment:`## Notion (connected, read-only context)
328
328
  You can pull a referenced Notion page in as extra context. This is OPTIONAL \u2014 only use it when the task references a Notion page/URL (e.g. an engineering-standards or design doc to review against).
329
329
  - notion_get_page: pass a Notion page id OR a full Notion URL; returns { id, title, url, text } where text is the page flattened to markdown (truncated to ~20k chars). Use the text as reference context.
330
330
  - notion_query_database: pass a database id/URL; returns a small list of rows ({ id, title, url, props }). Use to find a specific page, then notion_get_page it.
331
- Do not block the task if Notion is unavailable \u2014 these tools return { ok:false, error } on failure; treat a missing page as "no extra context" and continue.`,resolve(){let s=fn();return s?{type:"stdio",command:"node",args:[s,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(s,t){try{switch(s){case"notion_get_page":{let e=t?.pageId||t?.page||t?.url||t?.id,r=Ft(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await Xe(`/pages/${r}`),n=Ht(i),o=i?.url||`https://www.notion.so/${r.replace(/-/g,"")}`,a=await zt(r,0,{used:0}),d=!1;return a.length>Te&&(a=a.slice(0,Te),d=!0),JSON.stringify({ok:!0,id:r,title:n,url:o,text:a,...d?{truncated:!0}:{}})}case"notion_query_database":{let e=t?.databaseId||t?.database||t?.url||t?.id,r=Ft(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let n={page_size:Math.max(1,Math.min(Number(t?.maxResults)||Gt,Gt))};t?.filter&&typeof t.filter=="object"&&(n.filter=t.filter);let o=await Xe(`/databases/${r}/query`,{method:"POST",body:n}),a=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[u,p]of Object.entries(d.properties||{})){let m=bn(p);m&&(l[u]=m)}return{id:d.id,title:Ht(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:r,count:a.length,hasMore:!!o.has_more,rows:a})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}}]};import{existsSync as wn}from"fs";import{fileURLToPath as kn}from"url";import{dirname as Sn,resolve as vn}from"path";import{resolveIntegrationToken as Vt,clearTokenCache as In}from"@zibby/core/backend-client.js";function Nn(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Sn(kn(import.meta.url)),t=vn(s,"..","bin","mcp-skill.mjs");return wn(t)?t:null}function On(){let s=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!s)return null;let t=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:s,memberId:t}}function Rn(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function Tn(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var An="You haven't connected your own LinkedIn account \u2014 connect it at https://studio.zibby.dev/integrations (LinkedIn). For privacy, I can't post or act as anyone else's LinkedIn (including the project owner's) on your behalf.";function Qt(){let s=On();if(s)return s;if(Rn()||Tn())throw new Error(An);return null}var En="202506",jn="https://api.linkedin.com";function Wt(s){if(s==null)return null;let t=String(s).trim();if(!t)return null;let e=t.match(/urn:li:organization:(\d+)/i);return e?e[1]:/^\d+$/.test(t)?t:null}function Zt(s){if(!s)return"";if(s.localizedName)return String(s.localizedName);let t=s.name&&s.name.localized;if(t&&typeof t=="object"){let e=Object.values(t)[0];if(e)return String(e)}return""}function Ae(s,t){return s?typeof s.get=="function"?s.get(t):s[t]||s[t.toLowerCase()]||null:null}async function le(s,t={},e="linkedin_business"){let r=async()=>{let i;if(e==="linkedin_personal"){let d=Qt();d&&(i=d.token)}if(i||({token:i}=await Vt(e)),typeof i!="string"||!i)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let n=s.startsWith("https://")?s:`${jn}${s}`,o=await fetch(n,{method:t.method||"GET",headers:{Authorization:`Bearer ${i}`,"LinkedIn-Version":En,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${d.slice(0,300)}`)}let c=await o.text().catch(()=>""),a={};if(c&&c.trim())try{a=JSON.parse(c)}catch{a={raw:c}}return{status:o.status,headers:o.headers,body:a}};try{return await r()}catch(i){let n=String(i?.message||i||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("unauthorized")))throw i;return In(e),r()}}var Xt={id:"linkedin",serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn (connected)
331
+ - notion_list_comments: pass a page/block id OR URL; returns the open comment discussions on it ({ id, discussionId, text, author }). Use to read the comment thread you are replying to.
332
+ - notion_add_comment: post a comment. To REPLY in an existing discussion pass { discussionId, text }; to start a NEW top-level comment on a page pass { pageId, text }. Returns { ok, id, discussionId }. Use this to answer a user who @mentioned Zibby in a Notion comment \u2014 reply in the SAME discussionId.
333
+ Do not block the task if Notion is unavailable \u2014 these tools return { ok:false, error } on failure; treat a missing page as "no extra context" and continue.`,resolve(){let s=Ti();return s?{type:"stdio",command:"node",args:[s,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(s,t){try{switch(s){case"notion_get_page":{let e=t?.pageId||t?.page||t?.url||t?.id,r=je(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=await we(`/pages/${r}`),i=Xt(n),o=n?.url||`https://www.notion.so/${r.replace(/-/g,"")}`,c=await tr(r,0,{used:0}),d=!1;return c.length>$e&&(c=c.slice(0,$e),d=!0),JSON.stringify({ok:!0,id:r,title:i,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let e=t?.databaseId||t?.database||t?.url||t?.id,r=je(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let i={page_size:Math.max(1,Math.min(Number(t?.maxResults)||Qt,Qt))};t?.filter&&typeof t.filter=="object"&&(i.filter=t.filter);let o=await we(`/databases/${r}/query`,{method:"POST",body:i}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[u,p]of Object.entries(d.properties||{})){let m=$i(p);m&&(l[u]=m)}return{id:d.id,title:Xt(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:r,count:c.length,hasMore:!!o.has_more,rows:c})}case"notion_list_comments":{let e=t?.blockId||t?.pageId||t?.block||t?.page||t?.url||t?.id,r=je(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let n=new URLSearchParams({block_id:r,page_size:"100"}),i=await we(`/comments?${n.toString()}`),a=(Array.isArray(i.results)?i.results:[]).map(ji);return JSON.stringify({ok:!0,id:r,count:a.length,comments:a})}case"notion_add_comment":{let e=typeof t?.text=="string"?t.text:typeof t?.body=="string"?t.body:"";if(!e||!e.trim())return JSON.stringify({ok:!1,error:"text is required"});let r=t?.discussionId||t?.discussion_id||null,n;if(r)n={discussion_id:String(r),rich_text:er(e)};else{let o=t?.pageId||t?.page||t?.url||t?.id,a=je(o);if(!a)return JSON.stringify({ok:!1,error:"Either discussionId (to reply) or a valid pageId (to start a comment) is required"});n={parent:{page_id:a},rich_text:er(e)}}let i=await we("/comments",{method:"POST",body:n});return JSON.stringify({ok:!0,id:i?.id||"",discussionId:i?.discussion_id||r||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}},{name:"notion_list_comments",description:"List the open comment discussions on a Notion page/block. Accepts a page/block id OR a full Notion URL. Returns { ok, comments:[{ id, discussionId, text, author }] }. Use to read the comment thread you are replying to.",input_schema:{type:"object",properties:{blockId:{type:"string",description:"Notion page or block id (dashed UUID or 32-char) OR a full Notion URL."}},required:["blockId"]}},{name:"notion_add_comment",description:"Post a comment on Notion. To REPLY within an existing discussion, pass { discussionId, text }. To start a NEW top-level comment on a page, pass { pageId, text }. Returns { ok, id, discussionId }. Use this to answer a user who @mentioned Zibby in a Notion comment (reply in the same discussionId).",input_schema:{type:"object",properties:{discussionId:{type:"string",description:"The discussion_id to reply into (from notion_list_comments). Preferred for replies."},pageId:{type:"string",description:"Page id/URL to start a NEW top-level comment on (used when discussionId is absent)."},text:{type:"string",description:"The comment body (plain text)."}},required:["text"]}}]};import{existsSync as Ci}from"fs";import{fileURLToPath as Pi}from"url";import{dirname as Ui,resolve as qi}from"path";import{resolveIntegrationToken as ir,clearTokenCache as Di}from"@zibby/core/backend-client.js";function Ji(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Ui(Pi(import.meta.url)),t=qi(s,"..","bin","mcp-skill.mjs");return Ci(t)?t:null}function Mi(){let s=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!s)return null;let t=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:s,memberId:t}}function Bi(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function Ki(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var Gi="You haven't connected your own LinkedIn account \u2014 connect it at https://studio.zibby.dev/integrations (LinkedIn). For privacy, I can't post or act as anyone else's LinkedIn (including the project owner's) on your behalf.";function or(){let s=Mi();if(s)return s;if(Bi()||Ki())throw new Error(Gi);return null}var Fi="202506",Hi="https://api.linkedin.com";function sr(s){if(s==null)return null;let t=String(s).trim();if(!t)return null;let e=t.match(/urn:li:organization:(\d+)/i);return e?e[1]:/^\d+$/.test(t)?t:null}function nr(s){if(!s)return"";if(s.localizedName)return String(s.localizedName);let t=s.name&&s.name.localized;if(t&&typeof t=="object"){let e=Object.values(t)[0];if(e)return String(e)}return""}function Ce(s,t){return s?typeof s.get=="function"?s.get(t):s[t]||s[t.toLowerCase()]||null:null}async function ue(s,t={},e="linkedin_business"){let r=async()=>{let n;if(e==="linkedin_personal"){let d=or();d&&(n=d.token)}if(n||({token:n}=await ir(e)),typeof n!="string"||!n)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let i=s.startsWith("https://")?s:`${Hi}${s}`,o=await fetch(i,{method:t.method||"GET",headers:{Authorization:`Bearer ${n}`,"LinkedIn-Version":Fi,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${d.slice(0,300)}`)}let a=await o.text().catch(()=>""),c={};if(a&&a.trim())try{c=JSON.parse(a)}catch{c={raw:a}}return{status:o.status,headers:o.headers,body:c}};try{return await r()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Di(e),r()}}var ar={id:"linkedin",serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn (connected)
332
334
  You can post to LinkedIn two ways \u2014 an ORG company Page (business) and your own member PROFILE (personal). Each path needs its own LinkedIn integration connected.
333
335
 
334
336
  Business (company Page) \u2014 DRAFT only:
@@ -341,25 +343,35 @@ Personal (your own profile) \u2014 PUBLISHES IMMEDIATELY:
341
343
  Notes:
342
344
  - Org-page posts are ALWAYS created as a DRAFT; personal-profile posts are ALWAYS published live \u2014 choose the tool accordingly.
343
345
  - PUBLISHING IS OUTWARD-FACING AND IRREVERSIBLE. linkedin_publish_post posts live to a real audience the instant you call it \u2014 there is no undo and no draft state for member profiles. Only call it after the human has EXPLICITLY approved publishing THIS specific text in THIS conversation. If you wrote or edited the text, show it and get an explicit "yes, publish" first; if you are unsure, HOLD/draft rather than publish. The org draft tool (linkedin_create_draft_post) is the safe default when a human still needs to review.
344
- - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let s=Nn();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/linkedin.js","linkedinSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"linkedin_list_organizations":{let{body:e}=await le("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),r=Array.isArray(e.elements)?e.elements:[],i=[];for(let n of r){let o=n.organizationalTarget||n["organizationalTarget~"]||n.organization,c=Wt(o);if(!c)continue;let a="",d="";try{let l=(await le(`/rest/organizations/${c}`,{},"linkedin_business")).body;a=Zt(l),d=l.vanityName||""}catch{}i.push({id:c,urn:`urn:li:organization:${c}`,name:a,vanityName:d})}return JSON.stringify({ok:!0,count:i.length,organizations:i})}case"linkedin_create_draft_post":{let e=t?.organizationUrn||t?.organizationId||t?.organization||t?.orgId,r=Wt(e);if(!r)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let i=t?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let n=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${r}`;if(t?.dry_run===!0)try{let l="";try{let u=(await le(`/rest/organizations/${r}`,{},"linkedin_business")).body;l=Zt(u)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:l,id:r,urn:o},visibility:n,textPreview:i,note:"DRY RUN \u2014 nothing was posted"})}catch(l){return JSON.stringify({dryRun:!0,ok:!1,error:l.message})}let a=await le("/rest/posts",{method:"POST",body:{author:o,commentary:i,visibility:n,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1}},"linkedin_business"),d=Ae(a.headers,"x-restli-id")||Ae(a.headers,"x-linkedin-id")||a.body?.id||null;return JSON.stringify({ok:!0,postUrn:d,author:o,lifecycleState:"DRAFT",visibility:n,status:a.status})}case"linkedin_publish_post":{let e=Qt(),r=e?e.memberId:(await Vt("linkedin_personal")).memberId;if(!r)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let i=t?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let n=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${r}`;if(t?.dry_run===!0)try{let l=(await le("/v2/userinfo",{},"linkedin_personal")).body,u=l?.name||[l?.given_name,l?.family_name].filter(Boolean).join(" ")||"",p=l?.sub?String(l.sub):r;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:u,id:p,urn:`urn:li:person:${p}`},visibility:n,textPreview:i,note:"DRY RUN \u2014 nothing was posted"})}catch(l){return JSON.stringify({dryRun:!0,ok:!1,error:l.message})}let a=await le("/rest/posts",{method:"POST",body:{author:o,commentary:i,visibility:n,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}},"linkedin_personal"),d=Ae(a.headers,"x-restli-id")||Ae(a.headers,"x-linkedin-id")||a.body?.id||null;return JSON.stringify({ok:!0,postUrn:d,author:o,lifecycleState:"PUBLISHED",visibility:n,status:a.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}}]};import{existsSync as Ln}from"fs";import{fileURLToPath as $n}from"url";import{dirname as xn,resolve as Cn}from"path";import{resolveIntegrationToken as Pn,clearTokenCache as Un}from"@zibby/core/backend-client.js";function qn(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=xn($n(import.meta.url)),t=Cn(s,"..","bin","mcp-skill.mjs");return Ln(t)?t:null}var be="https://docs.googleapis.com/v1",Dn="https://www.googleapis.com/drive/v3";function Jn(){let s=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!s)return null;let t=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:s,email:t}}function Mn(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Bn(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Kn="You haven't connected your own Google account \u2014 connect it at https://studio.zibby.dev/integrations (Google Docs). For privacy, I can't use anyone else's Google (including the project owner's) on your behalf.",et=2e4,Gn=25;function er(s){if(!s||typeof s!="string")return null;let t=s.trim(),e=t.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return e?e[1]:/^[a-zA-Z0-9_-]{20,}$/.test(t)?t:null}async function de(s,t={}){let e=async()=>{let r,i=Jn();if(i)r=i.token;else{if(Bn()||Mn())throw new Error(Kn);({token:r}=await Pn("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);let n=await fetch(s,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let c=await n.text().catch(()=>"");throw new Error(`Google API ${n.status}: ${c.slice(0,300)}`)}let o=await n.text().catch(()=>"");if(!o||!o.trim())return{};try{return JSON.parse(o)}catch{return{raw:o}}};try{return await e()}catch(r){let i=String(r?.message||r||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw r;return Un("google"),e()}}function Fn(s){let t=[],e="",r=0;for(;r<s.length;){let i=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(s.slice(r));if(i){t.push({start:e.length,end:e.length+i[1].length,link:i[2]}),e+=i[1],r+=i[0].length;continue}let n=/^\*\*([^*]+)\*\*/.exec(s.slice(r));if(n){t.push({start:e.length,end:e.length+n[1].length,bold:!0}),e+=n[1],r+=n[0].length;continue}let o=/^`([^`]+)`/.exec(s.slice(r));if(o){t.push({start:e.length,end:e.length+o[1].length,code:!0}),e+=o[1],r+=o[0].length;continue}e+=s[r],r+=1}return{text:e,styles:t}}function tr(s,t){let e=String(s??"").replace(/\r\n/g,`
346
+ - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let s=Ji();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/linkedin.js","linkedinSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"linkedin_list_organizations":{let{body:e}=await ue("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),r=Array.isArray(e.elements)?e.elements:[],n=[];for(let i of r){let o=i.organizationalTarget||i["organizationalTarget~"]||i.organization,a=sr(o);if(!a)continue;let c="",d="";try{let l=(await ue(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=nr(l),d=l.vanityName||""}catch{}n.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:n.length,organizations:n})}case"linkedin_create_draft_post":{let e=t?.organizationUrn||t?.organizationId||t?.organization||t?.orgId,r=sr(e);if(!r)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let n=t?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let i=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${r}`;if(t?.dry_run===!0)try{let l="";try{let u=(await ue(`/rest/organizations/${r}`,{},"linkedin_business")).body;l=nr(u)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:l,id:r,urn:o},visibility:i,textPreview:n,note:"DRY RUN \u2014 nothing was posted"})}catch(l){return JSON.stringify({dryRun:!0,ok:!1,error:l.message})}let c=await ue("/rest/posts",{method:"POST",body:{author:o,commentary:n,visibility:i,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1}},"linkedin_business"),d=Ce(c.headers,"x-restli-id")||Ce(c.headers,"x-linkedin-id")||c.body?.id||null;return JSON.stringify({ok:!0,postUrn:d,author:o,lifecycleState:"DRAFT",visibility:i,status:c.status})}case"linkedin_publish_post":{let e=or(),r=e?e.memberId:(await ir("linkedin_personal")).memberId;if(!r)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let n=t?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let i=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${r}`;if(t?.dry_run===!0)try{let l=(await ue("/v2/userinfo",{},"linkedin_personal")).body,u=l?.name||[l?.given_name,l?.family_name].filter(Boolean).join(" ")||"",p=l?.sub?String(l.sub):r;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:u,id:p,urn:`urn:li:person:${p}`},visibility:i,textPreview:n,note:"DRY RUN \u2014 nothing was posted"})}catch(l){return JSON.stringify({dryRun:!0,ok:!1,error:l.message})}let c=await ue("/rest/posts",{method:"POST",body:{author:o,commentary:n,visibility:i,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}},"linkedin_personal"),d=Ce(c.headers,"x-restli-id")||Ce(c.headers,"x-linkedin-id")||c.body?.id||null;return JSON.stringify({ok:!0,postUrn:d,author:o,lifecycleState:"PUBLISHED",visibility:i,status:c.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}}]};import{existsSync as zi}from"fs";import{fileURLToPath as Yi}from"url";import{dirname as Wi,resolve as Zi}from"path";import{resolveIntegrationToken as Vi,clearTokenCache as Qi}from"@zibby/core/backend-client.js";function Xi(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Wi(Yi(import.meta.url)),t=Zi(s,"..","bin","mcp-skill.mjs");return zi(t)?t:null}var Se="https://docs.googleapis.com/v1",eo="https://www.googleapis.com/drive/v3";function to(){let s=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!s)return null;let t=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:s,email:t}}function ro(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function so(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var no="You haven't connected your own Google account \u2014 connect it at https://studio.zibby.dev/integrations (Google Docs). For privacy, I can't use anyone else's Google (including the project owner's) on your behalf.",ot=2e4,io=25;function cr(s){if(!s||typeof s!="string")return null;let t=s.trim(),e=t.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return e?e[1]:/^[a-zA-Z0-9_-]{20,}$/.test(t)?t:null}async function pe(s,t={}){let e=async()=>{let r,n=to();if(n)r=n.token;else{if(so()||ro())throw new Error(no);({token:r}=await Vi("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);let i=await fetch(s,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`Google API ${i.status}: ${a.slice(0,300)}`)}let o=await i.text().catch(()=>"");if(!o||!o.trim())return{};try{return JSON.parse(o)}catch{return{raw:o}}};try{return await e()}catch(r){let n=String(r?.message||r||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("unauthorized")))throw r;return Qi("google"),e()}}function oo(s){let t=[],e="",r=0;for(;r<s.length;){let n=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(s.slice(r));if(n){t.push({start:e.length,end:e.length+n[1].length,link:n[2]}),e+=n[1],r+=n[0].length;continue}let i=/^\*\*([^*]+)\*\*/.exec(s.slice(r));if(i){t.push({start:e.length,end:e.length+i[1].length,bold:!0}),e+=i[1],r+=i[0].length;continue}let o=/^`([^`]+)`/.exec(s.slice(r));if(o){t.push({start:e.length,end:e.length+o[1].length,code:!0}),e+=o[1],r+=o[0].length;continue}e+=s[r],r+=1}return{text:e,styles:t}}function lr(s,t){let e=String(s??"").replace(/\r\n/g,`
345
347
  `);if(!e.trim())return{requests:[],endIndex:t};let r=e.split(`
346
- `),i="",n=[],o=[];for(let l of r){let u=l,p=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(u),h=/^\s*[-*]\s+(.*)$/.exec(u),_=/^\s*\d+[.)]\s+(.*)$/.exec(u);f?(p=`HEADING_${f[1].length}`,u=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",u=h[1]):_&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",u=_[1]);let{text:g,styles:b}=Fn(u),y=t+i.length;for(let k of b)o.push({...k,start:y+k.start,end:y+k.end});i+=`${g}
347
- `,n.push({start:y,end:t+i.length,named:p,bullet:m})}if(!i)return{requests:[],endIndex:t};let c=[{insertText:{location:{index:t},text:i}}];for(let l of n)l.named&&c.push({updateParagraphStyle:{range:{startIndex:l.start,endIndex:l.end},paragraphStyle:{namedStyleType:l.named},fields:"namedStyleType"}});let a=null,d=()=>{a&&(c.push({createParagraphBullets:{range:{startIndex:a.start,endIndex:a.end},bulletPreset:a.preset}}),a=null)};for(let l of n)l.bullet?a&&a.preset===l.bullet?a.end=l.end:(d(),a={start:l.start,end:l.end,preset:l.bullet}):d();d();for(let l of o)l.end<=l.start||(l.bold?c.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{bold:!0},fields:"bold"}}):l.link?c.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{link:{url:l.link}},fields:"link"}}):l.code&&c.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:c,endIndex:t+i.length}}function Hn(s){let t="",e=r=>{for(let i of Array.isArray(r)?r:[]){if(t.length>=et)return;if(i.paragraph)for(let n of i.paragraph.elements||[])t+=n?.textRun?.content||"";else if(i.table)for(let n of i.table.tableRows||[])for(let o of n.tableCells||[])e(o.content);else i.tableOfContents&&e(i.tableOfContents.content)}};return e(s?.content),t.slice(0,et)}var Ee=s=>`https://docs.google.com/document/d/${s}/edit`,rr=s=>{let t=typeof s?.markdown=="string"?s.markdown:null,e=typeof s?.text=="string"?s.text:null;return t??e},sr={id:"google-docs",serverName:"gdocs",allowedTools:["mcp__gdocs__*"],requiresIntegration:I.GOOGLE,description:"Google Docs \u2014 create, append to, and read Google Docs (drive.file scoped)",promptFragment:`## Google Docs (connected)
348
+ `),n="",i=[],o=[];for(let l of r){let u=l,p=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(u),h=/^\s*[-*]\s+(.*)$/.exec(u),_=/^\s*\d+[.)]\s+(.*)$/.exec(u);f?(p=`HEADING_${f[1].length}`,u=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",u=h[1]):_&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",u=_[1]);let{text:g,styles:b}=oo(u),y=t+n.length;for(let w of b)o.push({...w,start:y+w.start,end:y+w.end});n+=`${g}
349
+ `,i.push({start:y,end:t+n.length,named:p,bullet:m})}if(!n)return{requests:[],endIndex:t};let a=[{insertText:{location:{index:t},text:n}}];for(let l of i)l.named&&a.push({updateParagraphStyle:{range:{startIndex:l.start,endIndex:l.end},paragraphStyle:{namedStyleType:l.named},fields:"namedStyleType"}});let c=null,d=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let l of i)l.bullet?c&&c.preset===l.bullet?c.end=l.end:(d(),c={start:l.start,end:l.end,preset:l.bullet}):d();d();for(let l of o)l.end<=l.start||(l.bold?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{bold:!0},fields:"bold"}}):l.link?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{link:{url:l.link}},fields:"link"}}):l.code&&a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:t+n.length}}function ao(s){let t="",e=r=>{for(let n of Array.isArray(r)?r:[]){if(t.length>=ot)return;if(n.paragraph)for(let i of n.paragraph.elements||[])t+=i?.textRun?.content||"";else if(n.table)for(let i of n.table.tableRows||[])for(let o of i.tableCells||[])e(o.content);else n.tableOfContents&&e(n.tableOfContents.content)}};return e(s?.content),t.slice(0,ot)}var Pe=s=>`https://docs.google.com/document/d/${s}/edit`,dr=s=>{let t=typeof s?.markdown=="string"?s.markdown:null,e=typeof s?.text=="string"?s.text:null;return t??e},ur={id:"google-docs",serverName:"gdocs",allowedTools:["mcp__gdocs__*"],requiresIntegration:v.GOOGLE,description:"Google Docs \u2014 create, append to, and read Google Docs (drive.file scoped)",promptFragment:`## Google Docs (connected)
348
350
  You can create and edit Google Docs for the user. IMPORTANT visibility caveat: the integration uses Google's per-file drive.file scope, so you can only see docs this app CREATED (or the user explicitly picked) \u2014 not the user's whole Drive.
349
351
  Docs access is PER-USER: each teammate connects their OWN Google account (Integrations \u2192 Google Docs). In shared-chat contexts the runtime routes these tools to the SENDER's own Google; a teammate who hasn't connected their own Google gets { ok:false } with connect instructions \u2014 for privacy the project owner's Google is NEVER used on someone else's behalf. Relay those instructions rather than retrying.
350
352
  - gdocs_create_doc: create a new Google Doc from a title + markdown (headings/bold/bullets/links supported) or plain text; returns { documentId, url }. Share the url with the user.
351
353
  - gdocs_append: append markdown/text to the end of a doc you created earlier (pass the documentId or doc URL).
352
354
  - gdocs_get: read a doc back as plain text (works for app-created/user-picked docs; arbitrary docs need the extended documents.readonly connection).
353
355
  - gdocs_list_created: list the Google Docs visible to this app (drive.file \u2192 only docs it created or the user picked).
354
- These tools return { ok:false, error } on failure \u2014 treat an unavailable Google connection as "cannot deliver to Docs" and report it rather than blocking the task.`,resolve(){let s=qn();if(!s)return null;let t={};for(let e of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/googleDocs.js","googleDocsSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"gdocs_create_doc":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let i=(await de(`${be}/documents`,{method:"POST",body:{title:e}}))?.documentId;if(!i)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let n=rr(t);if(n&&n.trim()){let{requests:o}=tr(n,1);o.length&&await de(`${be}/documents/${i}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:i,title:e,url:Ee(i)})}case"gdocs_append":{let e=er(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let r=rr(t);if(!r||!r.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let n=(await de(`${be}/documents/${e}`))?.body,o=Array.isArray(n?.content)?n.content:[],c=o.length&&o[o.length-1].endIndex||2,a=Math.max(1,c-1),d=[],l=a;a>1&&(d.push({insertText:{location:{index:a},text:`
355
- `}}),l=a+1);let u=tr(r,l);return d.push(...u.requests),await de(`${be}/documents/${e}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:e,url:Ee(e)})}case"gdocs_get":{let e=er(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let r=await de(`${be}/documents/${e}`),i=Hn(r?.body);return JSON.stringify({ok:!0,documentId:e,title:r?.title||"",url:Ee(e),text:i,...i.length>=et?{truncated:!0}:{}})}case"gdocs_list_created":{let e=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(Gn),orderBy:"modifiedTime desc"}),r=await de(`${Dn}/files?${e.toString()}`),i=(Array.isArray(r?.files)?r.files:[]).map(n=>({documentId:n.id,title:n.name,modifiedTime:n.modifiedTime,url:n.webViewLink||Ee(n.id)}));return JSON.stringify({ok:!0,count:i.length,files:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). Under the default drive.file scope this works ONLY for docs this app created or the user explicitly picked; reading arbitrary docs requires the extended documents.readonly connection. Returns { ok, documentId, title, url, text }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."}},required:["documentId"]}},{name:"gdocs_list_created",description:"List the Google Docs visible to this integration, newest first (max 25). NOTE: under the drive.file scope this lists ONLY docs the app created or the user explicitly picked \u2014 it is NOT a full Drive search. Returns { ok, count, files:[{ documentId, title, modifiedTime, url }] }.",input_schema:{type:"object",properties:{}}}]};var ir={id:"chat_notify",description:"Chat notification meta-skill \u2014 routes to whichever messaging integration (Slack OR Lark) the user has configured for this project.",envKeys:[...x.envKeys||[],...K.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return x.serverName;if(process.env.LARK_RECEIVE_ID)return K.serverName;if(process.env.SLACK_BOT_TOKEN)return x.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?x.allowedTools||[]:process.env.LARK_RECEIVE_ID?K.allowedTools||[]:process.env.SLACK_BOT_TOKEN?x.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
356
+ These tools return { ok:false, error } on failure \u2014 treat an unavailable Google connection as "cannot deliver to Docs" and report it rather than blocking the task.`,resolve(){let s=Xi();if(!s)return null;let t={};for(let e of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/googleDocs.js","googleDocsSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"gdocs_create_doc":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let n=(await pe(`${Se}/documents`,{method:"POST",body:{title:e}}))?.documentId;if(!n)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let i=dr(t);if(i&&i.trim()){let{requests:o}=lr(i,1);o.length&&await pe(`${Se}/documents/${n}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:n,title:e,url:Pe(n)})}case"gdocs_append":{let e=cr(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let r=dr(t);if(!r||!r.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let i=(await pe(`${Se}/documents/${e}`))?.body,o=Array.isArray(i?.content)?i.content:[],a=o.length&&o[o.length-1].endIndex||2,c=Math.max(1,a-1),d=[],l=c;c>1&&(d.push({insertText:{location:{index:c},text:`
357
+ `}}),l=c+1);let u=lr(r,l);return d.push(...u.requests),await pe(`${Se}/documents/${e}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:e,url:Pe(e)})}case"gdocs_get":{let e=cr(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let r=await pe(`${Se}/documents/${e}`),n=ao(r?.body);return JSON.stringify({ok:!0,documentId:e,title:r?.title||"",url:Pe(e),text:n,...n.length>=ot?{truncated:!0}:{}})}case"gdocs_list_created":{let e=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(io),orderBy:"modifiedTime desc"}),r=await pe(`${eo}/files?${e.toString()}`),n=(Array.isArray(r?.files)?r.files:[]).map(i=>({documentId:i.id,title:i.name,modifiedTime:i.modifiedTime,url:i.webViewLink||Pe(i.id)}));return JSON.stringify({ok:!0,count:n.length,files:n})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). Under the default drive.file scope this works ONLY for docs this app created or the user explicitly picked; reading arbitrary docs requires the extended documents.readonly connection. Returns { ok, documentId, title, url, text }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."}},required:["documentId"]}},{name:"gdocs_list_created",description:"List the Google Docs visible to this integration, newest first (max 25). NOTE: under the drive.file scope this lists ONLY docs the app created or the user explicitly picked \u2014 it is NOT a full Drive search. Returns { ok, count, files:[{ documentId, title, modifiedTime, url }] }.",input_schema:{type:"object",properties:{}}}]};import{existsSync as co}from"fs";import{fileURLToPath as lo}from"url";import{dirname as uo,resolve as po}from"path";import{resolveIntegrationToken as mo}from"@zibby/core/backend-client.js";function fo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=uo(lo(import.meta.url)),t=po(s,"..","bin","mcp-skill.mjs");return co(t)?t:null}var pr=2e4,mr=50,ho=6e3*1e3,Ie=null;async function yo(){let{appId:s,appSecret:t,host:e}=await mo("lark");if(Ie&&Ie.appId===s&&Ie.expiresAt>Date.now())return{token:Ie.token,host:e};let n=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:s,app_secret:t})})).json();if(n.code!==0)throw new Error(`Lark tenant_access_token failed: ${n.msg||n.code}`);return Ie={token:n.tenant_access_token,expiresAt:Date.now()+ho,appId:s},{token:n.tenant_access_token,host:e}}async function Q(s,t,e){let{token:r,host:n}=await yo(),i={method:s,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}};s!=="GET"&&e!==void 0&&(i.body=JSON.stringify(e));let a=await(await fetch(`${n}${t}`,i)).json();if(a.code!==0)throw new Error(`Lark Docx API ${t} error: ${a.msg||a.code}`);return{data:a.data||{},host:n}}function at(s,t){return String(s||"").includes("feishu")?`https://feishu.cn/docx/${t}`:`https://www.larksuite.com/docx/${t}`}function me(s){if(!s||typeof s!="string")return null;let t=s.trim();if(!t)return null;let e=t.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return e?{type:e[1],token:e[2]}:/^[A-Za-z0-9]{10,}$/.test(t)?{type:"docx",token:t}:null}async function ve(s){let t=typeof s=="string"?me(s):s;if(!t)throw new Error("A valid Lark doc id or URL is required");if(t.type==="docx")return t.token;let{data:e}=await Q("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(t.token)}`),r=e?.node||{};if(r.obj_type!=="docx"||!r.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${r.obj_type||"unknown"})`);return r.obj_token}function fr(s){let t=String(s??"").replace(/\r\n/g,`
358
+ `),e=[];for(let r of t.split(`
359
+ `)){let n=r.replace(/\s+$/,"");if(!n.trim())continue;let i=/^(#{1,3})\s+(.*)$/.exec(n),o=/^\s*[-*]\s+(.*)$/.exec(n),a=/^\s*\d+[.)]\s+(.*)$/.exec(n),c,d,l;if(i){let u=i[1].length;c=`heading${u}`,d=2+u,l=i[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=n);e.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return e}function Ue(s){let t=typeof s?.markdown=="string"?s.markdown:null,e=typeof s?.text=="string"?s.text:null;return t??e}async function hr(s,t){let e;for(let r=0;r<t.length;r+=mr){let n=t.slice(r,r+mr);e=(await Q("POST",`/open-apis/docx/v1/documents/${s}/blocks/${s}/children?document_revision_id=-1`,{children:n})).host}return e}var go="docx",_o=50;function yr(s){return[{type:"text_run",text_run:{text:String(s??"")}}]}function bo(s){return Array.isArray(s)?s.map(t=>t?.text_run?.text??t?.docs_link?.url??(t?.person?`@${t.person.user_id||""}`:"")).join(""):""}function ko(s){let t=Array.isArray(s?.reply_list?.replies)?s.reply_list.replies:[];return{commentId:s?.comment_id||"",resolved:!!s?.is_solved,replies:t.map(e=>({replyId:e?.reply_id||"",author:e?.user_id||"",text:bo(e?.content?.elements),createTime:e?.create_time||""}))}}function ct(s){return typeof s?.fileType=="string"&&s.fileType.trim()?s.fileType.trim():go}var gr={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:v.LARK,description:"Lark / Feishu Docs \u2014 read, create, and append Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs (connected)
360
+ You can read, create, and append Lark/Feishu documents (docx). This reuses the same connected Lark app as messaging.
361
+ - larkdoc_get: pass a Lark doc id OR a full doc URL (a /docx/ or /wiki/ link); returns { ok, documentId, title, url, text } where text is the doc as plain text (truncated to ~20k chars). Use it as reference context.
362
+ - larkdoc_create: create a new doc from a title + markdown/text (#/##/### headings, - bullets, 1. ordered supported); returns { ok, documentId, url }. Share the url.
363
+ - larkdoc_append: append markdown/text to the end of an existing doc (pass the documentId or doc URL).
364
+ - larkdoc_list_comments: list the comment threads on a doc (pass the documentId or doc URL); returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.
365
+ - larkdoc_reply_comment: reply INSIDE an existing comment thread \u2014 pass { documentId, commentId, text }. Use this to answer a user who @mentioned Zibby in a doc comment (reply in the SAME commentId).
366
+ - larkdoc_add_comment: post a NEW top-level comment on a doc \u2014 pass { documentId, text }.
367
+ These tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.`,resolve(){let s=fo();return s?{type:"stdio",command:"node",args:[s,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(s,t){try{switch(s){case"larkdoc_get":{let e=t?.documentId||t?.url||t?.id,r=me(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=await ve(r),i="";try{i=(await Q("GET",`/open-apis/docx/v1/documents/${n}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await Q("GET",`/open-apis/docx/v1/documents/${n}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>pr&&(c=c.slice(0,pr),d=!0),JSON.stringify({ok:!0,documentId:n,title:i,url:at(a,n),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let{data:r,host:n}=await Q("POST","/open-apis/docx/v1/documents",{title:e,...t?.folderToken?{folder_token:String(t.folderToken)}:{}}),i=r?.document?.document_id;if(!i)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let o=Ue(t);if(o&&o.trim()){let a=fr(o);a.length&&await hr(i,a)}return JSON.stringify({ok:!0,documentId:i,title:e,url:at(n,i)})}case"larkdoc_append":{let e=t?.documentId||t?.url||t?.id,r=me(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=Ue(t);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let i=await ve(r),o=fr(n);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await hr(i,o);return JSON.stringify({ok:!0,documentId:i,url:at(a,i)})}case"larkdoc_list_comments":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,r=me(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=await ve(r),i=ct(t),o=new URLSearchParams({file_type:i,page_size:String(_o)}),{data:a}=await Q("GET",`/open-apis/drive/v1/files/${n}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(ko);return JSON.stringify({ok:!0,documentId:n,count:d.length,comments:d})}case"larkdoc_add_comment":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,r=me(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=Ue({text:t?.text??t?.body});if(!n||!n.trim())return JSON.stringify({ok:!1,error:"text is required"});let i=await ve(r),o=ct(t),{data:a}=await Q("POST",`/open-apis/drive/v1/files/${i}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:yr(n)}}]}});return JSON.stringify({ok:!0,documentId:i,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,r=me(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=t?.commentId||t?.comment_id;if(!n)return JSON.stringify({ok:!1,error:"commentId is required"});let i=Ue({text:t?.text??t?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await ve(r),a=ct(t),{data:c}=await Q("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(n)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:yr(i)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(n),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root."}},required:["title"]}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};var _r={id:"chat_notify",description:"Chat notification meta-skill \u2014 routes to whichever messaging integration (Slack OR Lark) the user has configured for this project.",envKeys:[...$.envKeys||[],...K.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return $.serverName;if(process.env.LARK_RECEIVE_ID)return K.serverName;if(process.env.SLACK_BOT_TOKEN)return $.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?$.allowedTools||[]:process.env.LARK_RECEIVE_ID?K.allowedTools||[]:process.env.SLACK_BOT_TOKEN?$.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
356
368
  You can post chat messages via:
357
369
  - slack_post_message (channel, text[, blocks]) \u2014 Slack. The \`channel\` is REQUIRED on every call.
358
370
  - lark_send_message (receive_id, text) \u2014 Lark.
359
371
  Where to post:
360
372
  - If SLACK_CHANNEL / LARK_RECEIVE_ID is set, that is the default destination \u2014 use it.
361
373
  - If NO destination env var is set but your instructions name a channel (e.g. "post to #bla"), post to THAT channel \u2014 pass it as the \`channel\` arg (a "#name" or "C0123" id both work).
362
- - If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(s){return process.env.SLACK_CHANNEL&&typeof x.resolve=="function"?x.resolve(s):process.env.LARK_RECEIVE_ID&&typeof K.resolve=="function"?K.resolve(s):process.env.SLACK_BOT_TOKEN&&typeof x.resolve=="function"?x.resolve(s):null},async handleToolCall(s,t,e){return typeof s=="string"&&s.startsWith("slack_")?x.handleToolCall(s,t,e):typeof s=="string"&&s.startsWith("lark_")?K.handleToolCall(s,t,e):JSON.stringify({error:`chat_notify: unknown tool "${s}". Expected slack_* or lark_*.`})},get tools(){return[...x.tools||[],...K.tools||[]]}};import{createRequire as zn}from"module";import{execFileSync as Yn}from"child_process";import{join as nr}from"path";import{existsSync as Wn}from"fs";var Zn=zn(import.meta.url);function Vn(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return Zn.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var or={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:s}=await import("@zibby/ui-memory");return s()}catch{return null}},promptFragment:`BEFORE executing browser actions:
374
+ - If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(s){return process.env.SLACK_CHANNEL&&typeof $.resolve=="function"?$.resolve(s):process.env.LARK_RECEIVE_ID&&typeof K.resolve=="function"?K.resolve(s):process.env.SLACK_BOT_TOKEN&&typeof $.resolve=="function"?$.resolve(s):null},async handleToolCall(s,t,e){return typeof s=="string"&&s.startsWith("slack_")?$.handleToolCall(s,t,e):typeof s=="string"&&s.startsWith("lark_")?K.handleToolCall(s,t,e):JSON.stringify({error:`chat_notify: unknown tool "${s}". Expected slack_* or lark_*.`})},get tools(){return[...$.tools||[],...K.tools||[]]}};import{createRequire as wo}from"module";import{execFileSync as So}from"child_process";import{join as br}from"path";import{existsSync as Io}from"fs";var vo=wo(import.meta.url);function No(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return vo.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var kr={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:s}=await import("@zibby/ui-memory");return s()}catch{return null}},promptFragment:`BEFORE executing browser actions:
363
375
  - Review any test memory/history above. Prefer selectors proven to work.
364
376
  - If a previous run failed, avoid the same approach.
365
377
  - After setup/login completes, navigate directly to the target page instead of clicking through menus.
@@ -371,18 +383,18 @@ DURING execution \u2014 when a selector fails and you switch to a fallback:
371
383
  AFTER completing the test, you MUST call memory_save_insight at least once:
372
384
  - Save any useful finding: reliable selectors, timing quirks, navigation patterns, workarounds.
373
385
  - Category: selector_tip | timing | navigation | workaround | flaky | general
374
- - Be specific \u2014 future runs will read your insights.`,resolve(){let s=Vn();if(!s)throw new Error(`\u274C Memory MCP server not found
386
+ - Be specific \u2014 future runs will read your insights.`,resolve(){let s=No();if(!s)throw new Error(`\u274C Memory MCP server not found
375
387
 
376
388
  Install @zibby/ui-memory:
377
- npm install @zibby/ui-memory`);let t=nr(process.cwd(),".zibby","memory");if(!Wn(nr(t,".dolt")))throw new Error(`\u274C Memory database not initialized
389
+ npm install @zibby/ui-memory`);let t=br(process.cwd(),".zibby","memory");if(!Io(br(t,".dolt")))throw new Error(`\u274C Memory database not initialized
378
390
 
379
391
  Run:
380
- zibby init --mem`);try{let e=Yn("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:t,encoding:"utf-8",timeout:5e3}),r=JSON.parse(e.trim()).rows||[];if(!r[0]||r[0].cnt===0)return console.log("[memory] Database empty \u2014 memory tools activate after first completed run"),null}catch(e){throw new Error(`\u274C Dolt not found or memory database error
392
+ zibby init --mem`);try{let e=So("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:t,encoding:"utf-8",timeout:5e3}),r=JSON.parse(e.trim()).rows||[];if(!r[0]||r[0].cnt===0)return console.log("[memory] Database empty \u2014 memory tools activate after first completed run"),null}catch(e){throw new Error(`\u274C Dolt not found or memory database error
381
393
 
382
394
  Install Dolt:
383
395
  https://docs.dolthub.com/introduction/installation
384
396
 
385
- Error: ${e.message}`,{cause:e})}return{command:"node",args:[s,"--db-path",t],description:this.description}},tools:[{name:"memory_get_test_history",description:"Query recent test runs with pass/fail results and timing",input_schema:{type:"object",properties:{specPath:{type:"string",description:"Filter by spec path (substring match)"},limit:{type:"number",description:"Max results (default 10)"}}}},{name:"memory_get_selectors",description:"Query known selectors for a page with stability metrics",input_schema:{type:"object",properties:{pageUrl:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_page_model",description:"Query page structure \u2014 elements, roles, selectors",input_schema:{type:"object",properties:{url:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_navigation",description:"Query known page-to-page transitions",input_schema:{type:"object",properties:{fromUrl:{type:"string",description:"Filter by source URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_save_insight",description:"Save a useful observation for future runs (selector tips, timing, workarounds)",input_schema:{type:"object",properties:{category:{type:"string",enum:["selector_tip","timing","navigation","workaround","flaky","general"],description:"Type of insight"},content:{type:"string",description:"The insight text \u2014 be specific and actionable"},specPath:{type:"string",description:"Related spec path"},sessionId:{type:"string",description:"Current session ID"}},required:["category","content"]}}]};import{existsSync as Qn,readFileSync as Xn}from"fs";import{homedir as eo}from"os";import{join as to}from"path";import{spawn as ro}from"child_process";var se={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
397
+ Error: ${e.message}`,{cause:e})}return{command:"node",args:[s,"--db-path",t],description:this.description}},tools:[{name:"memory_get_test_history",description:"Query recent test runs with pass/fail results and timing",input_schema:{type:"object",properties:{specPath:{type:"string",description:"Filter by spec path (substring match)"},limit:{type:"number",description:"Max results (default 10)"}}}},{name:"memory_get_selectors",description:"Query known selectors for a page with stability metrics",input_schema:{type:"object",properties:{pageUrl:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_page_model",description:"Query page structure \u2014 elements, roles, selectors",input_schema:{type:"object",properties:{url:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_navigation",description:"Query known page-to-page transitions",input_schema:{type:"object",properties:{fromUrl:{type:"string",description:"Filter by source URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_save_insight",description:"Save a useful observation for future runs (selector tips, timing, workarounds)",input_schema:{type:"object",properties:{category:{type:"string",enum:["selector_tip","timing","navigation","workaround","flaky","general"],description:"Type of insight"},content:{type:"string",description:"The insight text \u2014 be specific and actionable"},specPath:{type:"string",description:"Related spec path"},sessionId:{type:"string",description:"Current session ID"}},required:["category","content"]}}]};import{existsSync as Oo,readFileSync as Ro}from"fs";import{homedir as To}from"os";import{join as Ao}from"path";import{spawn as Eo}from"child_process";var ne={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
386
398
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
387
399
  2. Click "Connect Jira" and authorize via Atlassian OAuth
388
400
  3. After OAuth completes, ask me to install Jira again`},github:{description:"GitHub issues, PRs, repository management",integrationProvider:"github",envKeys:[],setupInstructions:`To connect GitHub:
@@ -394,17 +406,17 @@ AFTER completing the test, you MUST call memory_save_insight at least once:
394
406
  3. After OAuth completes, ask me to install Slack again`},sentry:{description:"Sentry error tracking \u2014 projects, issues, events",integrationProvider:"sentry",envKeys:[],setupInstructions:`To connect Sentry:
395
407
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
396
408
  2. Click "Connect Sentry" and authorize
397
- 3. After OAuth completes, ask me to install Sentry again`},runner:{description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],setupInstructions:"Ready to use. Runs zibby test workflows as background processes \u2014 each with its own browser and session."},browser:{description:"Playwright browser automation (navigate, click, fill, screenshot)",envKeys:[],setupInstructions:"Ready to use. Starts a Playwright browser for web automation."},memory:{description:"Test memory database (Dolt) \u2014 history, selectors, insights",envKeys:[],setupInstructions:"Ready to use. Requires Dolt (https://docs.dolthub.com/introduction/installation) and a memory DB via `zibby init --mem`."},"chat-memory":{description:"Persistent chat memory \u2014 remembers facts, decisions, and task history across sessions (Dolt-backed)",envKeys:[],setupInstructions:'Ready to use. Requires Dolt installed. Tables auto-create on first use. Install with: "add chat memory" or "install chat-memory".'},git:{description:"Clone and explore git repositories locally for codebase analysis",envKeys:[],setupInstructions:"Ready to use. Clone repos with git_checkout, explore with git_explore. Auto-authenticates with GitHub/GitLab tokens."}};function so(){let s=["## Available Skills"];for(let[t,e]of Object.entries(se)){let r=e.integrationProvider?`integration: ${e.integrationProvider}`:"ready";s.push(`- ${t}: ${e.description} [${r}]`)}return s.push(""),s.push("Use the install_skill / uninstall_skill / list_available_skills tools to manage skills."),s.push(`Zibby third party Integration settings page: ${tt()}`),s.push(""),s.push("## Tool-First Policy (mandatory)"),s.push("CRITICAL RULES \u2014 follow these strictly:"),s.push("1. When user asks to do something and a matching skill is available but not installed, IMMEDIATELY call install_skill. Never ask for credentials or confirmation first."),s.push(`2. If install_skill succeeds, the skill's tools are now available. Use them RIGHT AWAY in the same turn \u2014 don't just say "it's connected", actually call the tools.`),s.push("3. If install_skill reports needsIntegration, tell the user to connect via the integration URL and try again after."),s.push("4. When the relevant skill is already installed, use its tools directly \u2014 don't ask for IDs or keys. Each skill's own instructions explain the workflow."),s.push("5. If a task needs multiple skills (e.g. data from one + execution from another), install all of them, then follow each skill's workflow instructions."),s.join(`
398
- `)}function io(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let s=to(eo(),".zibby","config.json");return Qn(s)&&JSON.parse(Xn(s,"utf-8")).sessionToken||null}catch{return null}}function no(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function tt(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function oo(s){try{let t=process.platform;return ro(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",s]:[s],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}async function ao(){let s=io();if(!s)return{checked:!1,statuses:null,reason:"no-session-token"};try{let t=await fetch(`${no()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${s}`}});return t.ok?{checked:!0,statuses:await t.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${t.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function ar(s,t){if(!t||!s)return{connected:null};let e=s[t];return!e||typeof e.connected!="boolean"?{connected:null,details:e||null}:{connected:e.connected,details:e}}var cr={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:se,promptFragment:so,tools:[{name:"install_skill",description:"Install a skill into the current chat session so its tools become available",input_schema:{type:"object",properties:{skillId:{type:"string",description:'Skill identifier to install (e.g. "jira", "github", "browser", "memory")'}},required:["skillId"]}},{name:"uninstall_skill",description:"Remove a skill from the current chat session",input_schema:{type:"object",properties:{skillId:{type:"string",description:"Skill identifier to remove"}},required:["skillId"]}},{name:"list_available_skills",description:"List all skills that can be installed, with their env-var readiness status",input_schema:{type:"object",properties:{}}}],async handleToolCall(s,t,e){let{activeSkills:r}=e,i=await ao();if(s==="list_available_skills"){let n=Object.entries(se).map(([o,c])=>{let a=r.includes(o),d=ar(i.statuses,c.integrationProvider);return{id:o,description:c.description,installed:a,integrationProvider:c.integrationProvider||void 0,integrationConnected:d.connected,setupInstructions:d.connected===!1?c.setupInstructions:void 0}});return JSON.stringify({skills:n})}if(s==="install_skill"){let{skillId:n}=t;if(!n)return JSON.stringify({ok:!1,error:"skillId is required"});if(r.includes(n)){let l=se[n],{getSkill:u}=await import("@zibby/agent-workflow"),m=(u(n)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:n,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?tt():void 0,hint:`${n} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!se[n])return JSON.stringify({ok:!1,error:`Unknown skill "${n}". Available: ${Object.keys(se).join(", ")}`});let o=se[n];if(o.integrationProvider){let l=ar(i.statuses,o.integrationProvider),u=tt();if(i.checked&&l.connected===!1){let p=oo(u);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:u,openedBrowser:p,setupInstructions:`Please connect ${o.integrationProvider} first at ${u}. After you finish OAuth, ask me to install ${n} again.`})}}r.push(n);let{getSkill:c}=await import("@zibby/agent-workflow"),d=(c(n)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:n,description:o.description,availableTools:d,hint:`${n} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(s==="uninstall_skill"){let{skillId:n}=t;if(!n)return JSON.stringify({ok:!1,error:"skillId is required"});if(n==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=r.indexOf(n);return o===-1?JSON.stringify({ok:!1,error:`${n} is not installed`}):(r.splice(o,1),JSON.stringify({ok:!0,uninstalled:n}))}return JSON.stringify({error:`Unknown tool: ${s}`})},resolve(){return null}};import{readFileSync as co,readdirSync as lo,statSync as dr,writeFileSync as uo,mkdirSync as po}from"fs";import{join as ur,resolve as mo,relative as fo}from"path";import{execSync as pr}from"child_process";var lr=256*1024,ho=64*1024,mr={id:"core-tools",description:"File read/write, directory listing, shell commands, open URLs, wait for async operations",envKeys:[],tools:[{name:"read_file",description:"Read the contents of a file. Returns the text content.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"}},required:["path"]}},{name:"write_file",description:"Write content to a file. Creates parent directories if needed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"},content:{type:"string",description:"Content to write"}},required:["path","content"]}},{name:"list_directory",description:"List files and directories in a path. Returns names with type indicators (/ for dirs).",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory path (relative to cwd or absolute). Defaults to cwd."}}}},{name:"run_command",description:"Run a shell command and return its output. Use for grep, git, npm, etc.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},cwd:{type:"string",description:"Working directory (optional, defaults to project root)"}},required:["command"]}},{name:"open_url",description:"Open a URL in the user's default browser. Use for OAuth flows, documentation, integration setup pages.",input_schema:{type:"object",properties:{url:{type:"string",description:"URL to open"}},required:["url"]}},{name:"wait",description:"Wait for N seconds. Use this for async operations (tests, builds, deploys) \u2014 wait, then check status again.",input_schema:{type:"object",properties:{seconds:{type:"number",description:"Seconds to wait (default: 5, max: 300)"},reason:{type:"string",description:"Why waiting (for logging/clarity)"}}}}],async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"read_file":return yo(t,r);case"write_file":return go(t,r);case"list_directory":return _o(t,r);case"run_command":return bo(t,r);case"open_url":return wo(t);case"wait":return await ko(t,e?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function je(s,t){return mo(t,s)}function yo(s,t){let e=je(s.path,t),r=dr(e);return r.size>lr?JSON.stringify({error:`File too large (${(r.size/1024).toFixed(0)}KB). Max: ${lr/1024}KB`}):co(e,"utf-8")}function go(s,t){let e=je(s.path,t),r=ur(e,"..");return po(r,{recursive:!0}),uo(e,s.content,"utf-8"),JSON.stringify({ok:!0,path:fo(t,e)})}function _o(s,t){let e=je(s.path||".",t);return lo(e).map(i=>{try{return dr(ur(e,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
399
- `)}function bo(s,t){let e=s.cwd?je(s.cwd,t):t;return pr(s.command,{cwd:e,encoding:"utf-8",timeout:3e4,maxBuffer:ho,stdio:["pipe","pipe","pipe"]})||"(no output)"}function wo(s){let{url:t}=s;if(!t||!t.startsWith("http://")&&!t.startsWith("https://"))return JSON.stringify({error:"Invalid URL \u2014 must start with http:// or https://"});let e=process.platform,r=e==="darwin"?"open":e==="win32"?"start":"xdg-open";try{return pr(`${r} "${t}"`,{stdio:"ignore",timeout:5e3}),JSON.stringify({ok:!0,opened:t})}catch{return JSON.stringify({ok:!1,error:`Could not open browser. Please visit: ${t}`})}}async function ko(s,t){let e=Math.min(Math.max(s.seconds||5,1),300),r=s.reason||"async operation",i=500,n=Date.now()+e*1e3;for(;Date.now()<n;){if(t?.aborted)return JSON.stringify({ok:!0,waited:Math.round((e*1e3-(n-Date.now()))/1e3),reason:r,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(i,n-Date.now())))}return JSON.stringify({ok:!0,waited:e,reason:r})}import{existsSync as So}from"fs";import{fileURLToPath as vo}from"url";import{dirname as Io,resolve as No}from"path";import{resolveIntegrationToken as $e}from"@zibby/core/backend-client.js";function Oo(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let s=Io(vo(import.meta.url)),t=No(s,"..","bin","mcp-sentry.mjs");return So(t)?t:null}function xe(s){return(s||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Ro(s){let t=s||process.env.SENTRY_ORG;if(!t)throw new Error('Sentry organization not resolved \u2014 reconnect Sentry, or set SENTRY_ORG (self-hosted; the default org slug is "sentry").');return t}async function fr(s,t={}){let{token:e,organizationSlug:r,baseUrl:i}=await $e("sentry"),n=`${xe(i)}/api/0/organizations/${Ro(r)}${s}`,o={method:t.method||"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}};t.body!=null&&(o.body=typeof t.body=="string"?t.body:JSON.stringify(t.body));let c=await fetch(n,o);if(!c.ok){let a=await c.text().catch(()=>"");throw new Error(`Sentry API ${c.status}: ${a.slice(0,300)}`)}return c.json()}async function To(){return fr("/projects/?per_page=50")}async function Ao({query:s="is:unresolved",sort:t="date",project:e,limit:r=25}={}){let i=`/issues/?query=${encodeURIComponent(s)}&sort=${t}&per_page=${r}`;return e&&(i+=`&project=${encodeURIComponent(e)}`),fr(i)}async function Eo(s){if(!s)throw new Error("sentryGetIssue: issueId is required");let{token:t,baseUrl:e}=await $e("sentry"),r=await fetch(`${xe(e)}/api/0/issues/${s}/`,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let i=await r.text().catch(()=>"");throw new Error(`Sentry API ${r.status}: ${i.slice(0,300)}`)}return r.json()}async function jo(s,t={}){if(!s)throw new Error("sentryUpdateIssue: issueId is required");let e={};for(let o of["status","statusDetails","assignedTo","isBookmarked","hasSeen"])t[o]!==void 0&&(e[o]=t[o]);if(Object.keys(e).length===0)throw new Error("sentryUpdateIssue: nothing to update (pass status / statusDetails / assignedTo / isBookmarked / hasSeen)");let{token:r,baseUrl:i}=await $e("sentry"),n=await fetch(`${xe(i)}/api/0/issues/${s}/`,{method:"PUT",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){let o=await n.text().catch(()=>"");throw n.status===403?new Error(`Sentry API 403 updating issue ${s}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access to let Zibby resolve/comment on issues.`):new Error(`Sentry API ${n.status} updating issue ${s}: ${o.slice(0,300)}`)}return n.json()}async function Lo(s,t){if(!s)throw new Error("sentryAddComment: issueId is required");if(!t||!String(t).trim())throw new Error("sentryAddComment: text is required");let{token:e,baseUrl:r}=await $e("sentry"),i=await fetch(`${xe(r)}/api/0/issues/${s}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(t)})});if(!i.ok){let n=await i.text().catch(()=>"");throw i.status===403?new Error(`Sentry API 403 commenting on issue ${s}: ${n.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${i.status} commenting on issue ${s}: ${n.slice(0,300)}`)}return i.json()}var Le={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:I.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
409
+ 3. After OAuth completes, ask me to install Sentry again`},runner:{description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],setupInstructions:"Ready to use. Runs zibby test workflows as background processes \u2014 each with its own browser and session."},browser:{description:"Playwright browser automation (navigate, click, fill, screenshot)",envKeys:[],setupInstructions:"Ready to use. Starts a Playwright browser for web automation."},memory:{description:"Test memory database (Dolt) \u2014 history, selectors, insights",envKeys:[],setupInstructions:"Ready to use. Requires Dolt (https://docs.dolthub.com/introduction/installation) and a memory DB via `zibby init --mem`."},"chat-memory":{description:"Persistent chat memory \u2014 remembers facts, decisions, and task history across sessions (Dolt-backed)",envKeys:[],setupInstructions:'Ready to use. Requires Dolt installed. Tables auto-create on first use. Install with: "add chat memory" or "install chat-memory".'},git:{description:"Clone and explore git repositories locally for codebase analysis",envKeys:[],setupInstructions:"Ready to use. Clone repos with git_checkout, explore with git_explore. Auto-authenticates with GitHub/GitLab tokens."}};function Lo(){let s=["## Available Skills"];for(let[t,e]of Object.entries(ne)){let r=e.integrationProvider?`integration: ${e.integrationProvider}`:"ready";s.push(`- ${t}: ${e.description} [${r}]`)}return s.push(""),s.push("Use the install_skill / uninstall_skill / list_available_skills tools to manage skills."),s.push(`Zibby third party Integration settings page: ${lt()}`),s.push(""),s.push("## Tool-First Policy (mandatory)"),s.push("CRITICAL RULES \u2014 follow these strictly:"),s.push("1. When user asks to do something and a matching skill is available but not installed, IMMEDIATELY call install_skill. Never ask for credentials or confirmation first."),s.push(`2. If install_skill succeeds, the skill's tools are now available. Use them RIGHT AWAY in the same turn \u2014 don't just say "it's connected", actually call the tools.`),s.push("3. If install_skill reports needsIntegration, tell the user to connect via the integration URL and try again after."),s.push("4. When the relevant skill is already installed, use its tools directly \u2014 don't ask for IDs or keys. Each skill's own instructions explain the workflow."),s.push("5. If a task needs multiple skills (e.g. data from one + execution from another), install all of them, then follow each skill's workflow instructions."),s.join(`
410
+ `)}function xo(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let s=Ao(To(),".zibby","config.json");return Oo(s)&&JSON.parse(Ro(s,"utf-8")).sessionToken||null}catch{return null}}function jo(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function lt(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function $o(s){try{let t=process.platform;return Eo(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",s]:[s],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}async function Co(){let s=xo();if(!s)return{checked:!1,statuses:null,reason:"no-session-token"};try{let t=await fetch(`${jo()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${s}`}});return t.ok?{checked:!0,statuses:await t.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${t.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function wr(s,t){if(!t||!s)return{connected:null};let e=s[t];return!e||typeof e.connected!="boolean"?{connected:null,details:e||null}:{connected:e.connected,details:e}}var Sr={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:ne,promptFragment:Lo,tools:[{name:"install_skill",description:"Install a skill into the current chat session so its tools become available",input_schema:{type:"object",properties:{skillId:{type:"string",description:'Skill identifier to install (e.g. "jira", "github", "browser", "memory")'}},required:["skillId"]}},{name:"uninstall_skill",description:"Remove a skill from the current chat session",input_schema:{type:"object",properties:{skillId:{type:"string",description:"Skill identifier to remove"}},required:["skillId"]}},{name:"list_available_skills",description:"List all skills that can be installed, with their env-var readiness status",input_schema:{type:"object",properties:{}}}],async handleToolCall(s,t,e){let{activeSkills:r}=e,n=await Co();if(s==="list_available_skills"){let i=Object.entries(ne).map(([o,a])=>{let c=r.includes(o),d=wr(n.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:d.connected,setupInstructions:d.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:i})}if(s==="install_skill"){let{skillId:i}=t;if(!i)return JSON.stringify({ok:!1,error:"skillId is required"});if(r.includes(i)){let l=ne[i],{getSkill:u}=await import("@zibby/agent-workflow"),m=(u(i)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:i,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?lt():void 0,hint:`${i} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!ne[i])return JSON.stringify({ok:!1,error:`Unknown skill "${i}". Available: ${Object.keys(ne).join(", ")}`});let o=ne[i];if(o.integrationProvider){let l=wr(n.statuses,o.integrationProvider),u=lt();if(n.checked&&l.connected===!1){let p=$o(u);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:u,openedBrowser:p,setupInstructions:`Please connect ${o.integrationProvider} first at ${u}. After you finish OAuth, ask me to install ${i} again.`})}}r.push(i);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(i)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:i,description:o.description,availableTools:d,hint:`${i} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(s==="uninstall_skill"){let{skillId:i}=t;if(!i)return JSON.stringify({ok:!1,error:"skillId is required"});if(i==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=r.indexOf(i);return o===-1?JSON.stringify({ok:!1,error:`${i} is not installed`}):(r.splice(o,1),JSON.stringify({ok:!0,uninstalled:i}))}return JSON.stringify({error:`Unknown tool: ${s}`})},resolve(){return null}};import{readFileSync as Po,readdirSync as Uo,statSync as vr,writeFileSync as qo,mkdirSync as Do}from"fs";import{join as Nr,resolve as Jo,relative as Mo}from"path";import{execSync as Or}from"child_process";var Ir=256*1024,Bo=64*1024,Rr={id:"core-tools",description:"File read/write, directory listing, shell commands, open URLs, wait for async operations",envKeys:[],tools:[{name:"read_file",description:"Read the contents of a file. Returns the text content.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"}},required:["path"]}},{name:"write_file",description:"Write content to a file. Creates parent directories if needed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"},content:{type:"string",description:"Content to write"}},required:["path","content"]}},{name:"list_directory",description:"List files and directories in a path. Returns names with type indicators (/ for dirs).",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory path (relative to cwd or absolute). Defaults to cwd."}}}},{name:"run_command",description:"Run a shell command and return its output. Use for grep, git, npm, etc.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},cwd:{type:"string",description:"Working directory (optional, defaults to project root)"}},required:["command"]}},{name:"open_url",description:"Open a URL in the user's default browser. Use for OAuth flows, documentation, integration setup pages.",input_schema:{type:"object",properties:{url:{type:"string",description:"URL to open"}},required:["url"]}},{name:"wait",description:"Wait for N seconds. Use this for async operations (tests, builds, deploys) \u2014 wait, then check status again.",input_schema:{type:"object",properties:{seconds:{type:"number",description:"Seconds to wait (default: 5, max: 300)"},reason:{type:"string",description:"Why waiting (for logging/clarity)"}}}}],async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"read_file":return Ko(t,r);case"write_file":return Go(t,r);case"list_directory":return Fo(t,r);case"run_command":return Ho(t,r);case"open_url":return zo(t);case"wait":return await Yo(t,e?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(n){return JSON.stringify({error:n.message})}},resolve(){return null}};function qe(s,t){return Jo(t,s)}function Ko(s,t){let e=qe(s.path,t),r=vr(e);return r.size>Ir?JSON.stringify({error:`File too large (${(r.size/1024).toFixed(0)}KB). Max: ${Ir/1024}KB`}):Po(e,"utf-8")}function Go(s,t){let e=qe(s.path,t),r=Nr(e,"..");return Do(r,{recursive:!0}),qo(e,s.content,"utf-8"),JSON.stringify({ok:!0,path:Mo(t,e)})}function Fo(s,t){let e=qe(s.path||".",t);return Uo(e).map(n=>{try{return vr(Nr(e,n)).isDirectory()?`${n}/`:n}catch{return n}}).join(`
411
+ `)}function Ho(s,t){let e=s.cwd?qe(s.cwd,t):t;return Or(s.command,{cwd:e,encoding:"utf-8",timeout:3e4,maxBuffer:Bo,stdio:["pipe","pipe","pipe"]})||"(no output)"}function zo(s){let{url:t}=s;if(!t||!t.startsWith("http://")&&!t.startsWith("https://"))return JSON.stringify({error:"Invalid URL \u2014 must start with http:// or https://"});let e=process.platform,r=e==="darwin"?"open":e==="win32"?"start":"xdg-open";try{return Or(`${r} "${t}"`,{stdio:"ignore",timeout:5e3}),JSON.stringify({ok:!0,opened:t})}catch{return JSON.stringify({ok:!1,error:`Could not open browser. Please visit: ${t}`})}}async function Yo(s,t){let e=Math.min(Math.max(s.seconds||5,1),300),r=s.reason||"async operation",n=500,i=Date.now()+e*1e3;for(;Date.now()<i;){if(t?.aborted)return JSON.stringify({ok:!0,waited:Math.round((e*1e3-(i-Date.now()))/1e3),reason:r,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(n,i-Date.now())))}return JSON.stringify({ok:!0,waited:e,reason:r})}import{existsSync as Wo}from"fs";import{fileURLToPath as Zo}from"url";import{dirname as Vo,resolve as Qo}from"path";import{resolveIntegrationToken as Je}from"@zibby/core/backend-client.js";function Xo(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let s=Vo(Zo(import.meta.url)),t=Qo(s,"..","bin","mcp-sentry.mjs");return Wo(t)?t:null}function Me(s){return(s||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function ea(s){let t=s||process.env.SENTRY_ORG;if(!t)throw new Error('Sentry organization not resolved \u2014 reconnect Sentry, or set SENTRY_ORG (self-hosted; the default org slug is "sentry").');return t}async function Tr(s,t={}){let{token:e,organizationSlug:r,baseUrl:n}=await Je("sentry"),i=`${Me(n)}/api/0/organizations/${ea(r)}${s}`,o={method:t.method||"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}};t.body!=null&&(o.body=typeof t.body=="string"?t.body:JSON.stringify(t.body));let a=await fetch(i,o);if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Sentry API ${a.status}: ${c.slice(0,300)}`)}return a.json()}async function ta(){return Tr("/projects/?per_page=50")}async function ra({query:s="is:unresolved",sort:t="date",project:e,limit:r=25}={}){let n=`/issues/?query=${encodeURIComponent(s)}&sort=${t}&per_page=${r}`;return e&&(n+=`&project=${encodeURIComponent(e)}`),Tr(n)}async function sa(s){if(!s)throw new Error("sentryGetIssue: issueId is required");let{token:t,baseUrl:e}=await Je("sentry"),r=await fetch(`${Me(e)}/api/0/issues/${s}/`,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`Sentry API ${r.status}: ${n.slice(0,300)}`)}return r.json()}async function na(s,t={}){if(!s)throw new Error("sentryUpdateIssue: issueId is required");let e={};for(let o of["status","statusDetails","assignedTo","isBookmarked","hasSeen"])t[o]!==void 0&&(e[o]=t[o]);if(Object.keys(e).length===0)throw new Error("sentryUpdateIssue: nothing to update (pass status / statusDetails / assignedTo / isBookmarked / hasSeen)");let{token:r,baseUrl:n}=await Je("sentry"),i=await fetch(`${Me(n)}/api/0/issues/${s}/`,{method:"PUT",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){let o=await i.text().catch(()=>"");throw i.status===403?new Error(`Sentry API 403 updating issue ${s}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access to let Zibby resolve/comment on issues.`):new Error(`Sentry API ${i.status} updating issue ${s}: ${o.slice(0,300)}`)}return i.json()}async function ia(s,t){if(!s)throw new Error("sentryAddComment: issueId is required");if(!t||!String(t).trim())throw new Error("sentryAddComment: text is required");let{token:e,baseUrl:r}=await Je("sentry"),n=await fetch(`${Me(r)}/api/0/issues/${s}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(t)})});if(!n.ok){let i=await n.text().catch(()=>"");throw n.status===403?new Error(`Sentry API 403 commenting on issue ${s}: ${i.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${n.status} commenting on issue ${s}: ${i.slice(0,300)}`)}return n.json()}var De={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:v.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
400
412
  You have access to the user's Sentry. Use these tools:
401
413
  - sentry_list_projects: List projects in the organization
402
414
  - sentry_list_issues: List errors/issues (supports Sentry search query, project filter, sort)
403
415
  - sentry_get_issue: Get detailed info about a specific issue (requires issueId)
404
416
  - sentry_update_issue: Change an issue's status (resolved / resolvedInNextRelease / ignored / unresolved / muted), assignment, or bookmark (requires issueId; needs write scope)
405
- - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let s=Oo();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE","ZIBBY_SELF_HOST","SENTRY_URL","SENTRY_ORG","SENTRY_AUTH_TOKEN"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},async handleToolCall(s,t={}){try{switch(s){case"sentry_list_projects":{let e=await To();return JSON.stringify({projects:e.map(r=>({slug:r.slug,name:r.name,platform:r.platform}))})}case"sentry_list_issues":{let e=await Ao({query:t.query,sort:t.sort,project:t.project,limit:t.limit});return JSON.stringify({issues:e.map(r=>({id:r.id,title:r.title,culprit:r.culprit,count:r.count,firstSeen:r.firstSeen,lastSeen:r.lastSeen,level:r.level,status:r.status}))})}case"sentry_get_issue":{let e=await Eo(t.issueId);return JSON.stringify({id:e.id,title:e.title,culprit:e.culprit,metadata:e.metadata,count:e.count,userCount:e.userCount,firstSeen:e.firstSeen,lastSeen:e.lastSeen,level:e.level,status:e.status,project:{slug:e.project?.slug,name:e.project?.name}})}case"sentry_update_issue":{let e=await jo(t.issueId,{status:t.status,statusDetails:t.statusDetails,assignedTo:t.assignedTo,isBookmarked:t.isBookmarked,hasSeen:t.hasSeen});return JSON.stringify({ok:!0,id:e.id??t.issueId,status:e.status,assignedTo:e.assignedTo,isBookmarked:e.isBookmarked})}case"sentry_add_comment":{let e=await Lo(t.issueId,t.text);return JSON.stringify({ok:!0,id:e.id,issueId:t.issueId})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},toolsForAssistant:[{name:"sentry_list_projects",description:"List Sentry projects",input_schema:{type:"object",properties:{}}},{name:"sentry_list_issues",description:"List Sentry issues (errors)",input_schema:{type:"object",properties:{project:{type:"string",description:"Project slug (optional)"},query:{type:"string",description:"Sentry search query (default: is:unresolved)"},sort:{type:"string",description:"Sort order: date, new, priority, freq, user (default: date)"},limit:{type:"number",description:"Max issues to return (default 25)"}}}},{name:"sentry_get_issue",description:"Get details of a specific Sentry issue",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"}},required:["issueId"]}},{name:"sentry_update_issue",description:"Update a Sentry issue's status, assignment, or bookmark (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},status:{type:"string",description:"resolved | resolvedInNextRelease | unresolved | ignored | muted"},statusDetails:{type:"object",description:'Optional status details, e.g. { "inRelease": "latest" }'},assignedTo:{type:"string",description:'Assignee actor id, e.g. "user:123" or "team:456" (optional)'},isBookmarked:{type:"boolean",description:"Bookmark/unbookmark the issue (optional)"},hasSeen:{type:"boolean",description:"Mark the issue seen/unseen (optional)"}},required:["issueId"]}},{name:"sentry_add_comment",description:"Post a comment/note on a Sentry issue (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},text:{type:"string",description:"Comment body (markdown)"}},required:["issueId","text"]}}]};Le.tools=Le.toolsForAssistant;import{spawn as Ir}from"child_process";import{writeFileSync as $o,mkdirSync as hr,existsSync as G,readdirSync as qe,readFileSync as Ue,unlinkSync as xo,createWriteStream as Co,statSync as Po}from"fs";import{resolve as ie,join as B}from"path";import{resolveMaxParallelRuns as Nr}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Uo}from"@zibby/core/constants/zibby-scratch.js";var it="sessions",nt=".zibby/output",Ce=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",qo=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",Or=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",P=new Map,Q=[],Do=0,rt=0,yr=3e3;function Rr(){return`run_${++Do}_${Date.now().toString(36)}`}function gr(s){let t=Math.floor(s/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Tr(s){return s.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function C(s,t,e){if(!qo)return;let r=`
417
+ - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let s=Xo();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE","ZIBBY_SELF_HOST","SENTRY_URL","SENTRY_ORG","SENTRY_AUTH_TOKEN"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},async handleToolCall(s,t={}){try{switch(s){case"sentry_list_projects":{let e=await ta();return JSON.stringify({projects:e.map(r=>({slug:r.slug,name:r.name,platform:r.platform}))})}case"sentry_list_issues":{let e=await ra({query:t.query,sort:t.sort,project:t.project,limit:t.limit});return JSON.stringify({issues:e.map(r=>({id:r.id,title:r.title,culprit:r.culprit,count:r.count,firstSeen:r.firstSeen,lastSeen:r.lastSeen,level:r.level,status:r.status}))})}case"sentry_get_issue":{let e=await sa(t.issueId);return JSON.stringify({id:e.id,title:e.title,culprit:e.culprit,metadata:e.metadata,count:e.count,userCount:e.userCount,firstSeen:e.firstSeen,lastSeen:e.lastSeen,level:e.level,status:e.status,project:{slug:e.project?.slug,name:e.project?.name}})}case"sentry_update_issue":{let e=await na(t.issueId,{status:t.status,statusDetails:t.statusDetails,assignedTo:t.assignedTo,isBookmarked:t.isBookmarked,hasSeen:t.hasSeen});return JSON.stringify({ok:!0,id:e.id??t.issueId,status:e.status,assignedTo:e.assignedTo,isBookmarked:e.isBookmarked})}case"sentry_add_comment":{let e=await ia(t.issueId,t.text);return JSON.stringify({ok:!0,id:e.id,issueId:t.issueId})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},toolsForAssistant:[{name:"sentry_list_projects",description:"List Sentry projects",input_schema:{type:"object",properties:{}}},{name:"sentry_list_issues",description:"List Sentry issues (errors)",input_schema:{type:"object",properties:{project:{type:"string",description:"Project slug (optional)"},query:{type:"string",description:"Sentry search query (default: is:unresolved)"},sort:{type:"string",description:"Sort order: date, new, priority, freq, user (default: date)"},limit:{type:"number",description:"Max issues to return (default 25)"}}}},{name:"sentry_get_issue",description:"Get details of a specific Sentry issue",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"}},required:["issueId"]}},{name:"sentry_update_issue",description:"Update a Sentry issue's status, assignment, or bookmark (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},status:{type:"string",description:"resolved | resolvedInNextRelease | unresolved | ignored | muted"},statusDetails:{type:"object",description:'Optional status details, e.g. { "inRelease": "latest" }'},assignedTo:{type:"string",description:'Assignee actor id, e.g. "user:123" or "team:456" (optional)'},isBookmarked:{type:"boolean",description:"Bookmark/unbookmark the issue (optional)"},hasSeen:{type:"boolean",description:"Mark the issue seen/unseen (optional)"}},required:["issueId"]}},{name:"sentry_add_comment",description:"Post a comment/note on a Sentry issue (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},text:{type:"string",description:"Comment body (markdown)"}},required:["issueId","text"]}}]};De.tools=De.toolsForAssistant;import{spawn as qr}from"child_process";import{writeFileSync as oa,mkdirSync as Ar,existsSync as G,readdirSync as Fe,readFileSync as Ge,unlinkSync as aa,createWriteStream as ca,statSync as la}from"fs";import{resolve as ie,join as B}from"path";import{resolveMaxParallelRuns as Dr}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as da}from"@zibby/core/constants/zibby-scratch.js";var pt="sessions",mt=".zibby/output",Be=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",ua=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",Jr=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",P=new Map,X=[],pa=0,dt=0,Er=3e3;function Mr(){return`run_${++pa}_${Date.now().toString(36)}`}function Lr(s){let t=Math.floor(s/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Br(s){return s.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function C(s,t,e){if(!ua)return;let r=`
406
418
  ${t} [${s}] ${e}
407
- `;try{process.stderr.write(r)}catch{}}function ot(){Q.length=0;for(let[,s]of P)if(s.status==="queued"&&(s.status="cancelled"),s.status==="running"&&s._child)try{s._child.kill("SIGTERM")}catch{}}process.on("exit",ot);process.on("SIGINT",()=>{ot(),process.exit(0)});process.on("SIGTERM",()=>{ot(),process.exit(0)});var Ar={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
419
+ `;try{process.stderr.write(r)}catch{}}function ft(){X.length=0;for(let[,s]of P)if(s.status==="queued"&&(s.status="cancelled"),s.status==="running"&&s._child)try{s._child.kill("SIGTERM")}catch{}}process.on("exit",ft);process.on("SIGINT",()=>{ft(),process.exit(0)});process.on("SIGTERM",()=>{ft(),process.exit(0)});var Kr={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
408
420
  You can run zibby test workflows directly from chat:
409
421
 
410
422
  **CRITICAL: When user asks to test a ticket:**
@@ -541,35 +553,35 @@ Each run generates:
541
553
  - events.json: All browser events
542
554
  - raw_stream_output.txt: Agent log
543
555
 
544
- Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"run_generate":return await Jo(t,r);case"run_test":return await Ho(t,r,e);case"run_status":return zo(t);case"run_cancel":return Yo(t);case"run_artifacts":return Vo(t,r);case"run_diagnose":return Qo(t,r);case"list_specs":return Xo(t,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"run_generate",description:"Generate specs from codebase. CRITICAL: DO NOT USE if ticket has test steps in comments. Only use when: (1) NO steps in ticket AND (2) local codebase exists (not external URLs). For tickets with steps, use run_test with inline format.",input_schema:{type:"object",properties:{ticket:{type:"string",description:"Jira ticket key (e.g. SCRUM-123). Auto-fetches ticket details."},description:{type:"string",description:"Ticket description text (use if no Jira key available)"},input:{type:"string",description:"Path to a file containing ticket/requirements text"},repo:{type:"string",description:"Path to the codebase (default: current directory)"},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},output:{type:"string",description:"Output directory for spec files (default: test-specs)"}}}},{name:"run_test",description:"Start a test (async, returns runId). spec = file path, or inline:+steps, or a Jira-shaped issue key (e.g. PROJ-123): when Jira is connected, the runner loads that issue's description+comments into an inline spec. After starting, tell the user and let them ask for progress via run_status.",input_schema:{type:"object",properties:{spec:{type:"string",description:"Workspace file path; or inline:+steps; or Jira issue key (KEY-123) to auto-fetch from Jira when the jira skill is active."},ticketKey:{type:"string",description:"Optional label (e.g. SCRUM-123). If spec is an issue key, this defaults to that key."},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},headless:{type:"boolean",description:"Run browser headless (default false)"},workflow:{type:"string",description:"Workflow override (e.g. quick-smoke)"}},required:["spec"]}},{name:"run_status",description:'Instant progress check \u2014 returns immediately. Use this whenever user asks about test progress. ALWAYS use runId="all".',input_schema:{type:"object",properties:{runId:{type:"string",description:'Use "all" to see all runs in this session (recommended). Or a specific run ID if known.'}},required:["runId"]}},{name:"run_cancel",description:'Cancel/kill a running test. ONLY use when the USER explicitly asks to cancel or stop a run. NEVER auto-cancel \u2014 tests take 1-5 minutes and "running" is normal. Use runId="all" to cancel all active runs.',input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID to cancel, or "all" to cancel all active runs'}},required:["runId"]}},{name:"run_artifacts",description:"Read artifacts from a test run session. Can list files, read results/events/logs, or search across all sessions.",input_schema:{type:"object",properties:{runId:{type:"string",description:"Run ID from run_test. Omit to search across all sessions."},type:{type:"string",enum:["list","result","events","log","search"],description:'What to retrieve: "list" = all files in session, "result" = result.json, "events" = events.json, "log" = raw output tail, "search" = search text across sessions'},node:{type:"string",description:'Node name to read from (e.g. "execute_live", "generate_script"). Default: "execute_live"'},query:{type:"string",description:'Search text (only for type="search"). Searches across all session logs/events.'},tail:{type:"number",description:"Number of characters from end of log to return (default: 3000)"}},required:["type"]}},{name:"run_diagnose",description:"Diagnose one or all runs, especially failed ones. Uses run logs + known error patterns and returns likely root cause with suggested next action.",input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID from run_test, or "all" (default) to diagnose all known runs'},tail:{type:"number",description:"Characters of run log tail to inspect (default: 2000)"}}}},{name:"list_specs",description:"List available test spec files in the project",input_schema:{type:"object",properties:{directory:{type:"string",description:'Directory to scan (default: "test-specs")'}}}}]};function st(){let s=0;for(let[,t]of P)t.status==="running"&&s++;return s}function _r(){for(;Q.length>0;){let s=Nr(Q[0]?.context?.options?.config);if(st()>=s)break;let{args:t,cwd:e,context:r}=Q.shift();Er(t,e,r)}}async function Jo(s,t){let{ticket:e,description:r,input:i,repo:n,agent:o,output:c}=s,a=["generate"];e&&a.push("--ticket",e),r&&a.push("--description",r),i&&a.push("--input",i),n&&a.push("--repo",n),c&&a.push("--output",c);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,u=l&&d.includes(l)?l:null;u&&a.push("--agent",u);let p=e||"generate";return C(p,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{Or&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${a.map(g=>/\s/.test(g)?JSON.stringify(g):g).join(" ")} cwd=${t}`);let f=Ir("zibby",a,{cwd:t,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",_="";f.stdout.on("data",g=>{let b=g.toString();h+=b;for(let y of b.split(`
545
- `)){let k=Tr(y).trim();k.startsWith("\u2705")?C(p,"\u2705",k.slice(2).trim()):k.startsWith("\u2713")&&C(p,"\u2714",k.slice(2).trim())}}),f.stderr.on("data",g=>{_+=g.toString()}),f.on("close",g=>{if(g!==0){C(p,"\u274C",`Generation failed (exit ${g})`),m(JSON.stringify({error:`zibby generate failed with exit code ${g}`,stderr:_.slice(-1e3)}));return}let b=ie(t,c||"test-specs"),y=[];try{let k=e?e.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";y=qe(b).filter(A=>A.endsWith(".txt")&&(!k||A.startsWith(k))).map(A=>B(b,A))}catch{}C(p,"\u2705",`Generated ${y.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:e||null,specFiles:y.map(k=>k.replace(`${t}/`,"")),total:y.length,message:`Generated ${y.length} specs. Now call run_test for each file.`}))}),f.on("error",g=>{C(p,"\u274C",`Spawn error: ${g.message}`),m(JSON.stringify({error:g.message}))})})}var br=1e5,wr=/^[A-Z][A-Z0-9]+-\d+$/,Mo=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Bo(s,t){if(!t||!t.length)return s;let e=s;for(let r of t)r.type==="strong"?e=`**${e}**`:r.type==="em"?e=`_${e}_`:r.type==="code"?e=`\`${e}\``:r.type==="strike"?e=`~~${e}~~`:r.type==="link"&&r.attrs?.href&&(e=`[${e}](${r.attrs.href})`);return e}function Pe(s,t=0){if(!Array.isArray(s))return"";let e=[];for(let r of s){if(r.type==="text"){e.push(Bo(r.text||"",r.marks));continue}if(r.type==="hardBreak"){e.push(`
556
+ Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"run_generate":return await ma(t,r);case"run_test":return await ba(t,r,e);case"run_status":return ka(t);case"run_cancel":return wa(t);case"run_artifacts":return va(t,r);case"run_diagnose":return Na(t,r);case"list_specs":return Oa(t,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(n){return JSON.stringify({error:n.message})}},tools:[{name:"run_generate",description:"Generate specs from codebase. CRITICAL: DO NOT USE if ticket has test steps in comments. Only use when: (1) NO steps in ticket AND (2) local codebase exists (not external URLs). For tickets with steps, use run_test with inline format.",input_schema:{type:"object",properties:{ticket:{type:"string",description:"Jira ticket key (e.g. SCRUM-123). Auto-fetches ticket details."},description:{type:"string",description:"Ticket description text (use if no Jira key available)"},input:{type:"string",description:"Path to a file containing ticket/requirements text"},repo:{type:"string",description:"Path to the codebase (default: current directory)"},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},output:{type:"string",description:"Output directory for spec files (default: test-specs)"}}}},{name:"run_test",description:"Start a test (async, returns runId). spec = file path, or inline:+steps, or a Jira-shaped issue key (e.g. PROJ-123): when Jira is connected, the runner loads that issue's description+comments into an inline spec. After starting, tell the user and let them ask for progress via run_status.",input_schema:{type:"object",properties:{spec:{type:"string",description:"Workspace file path; or inline:+steps; or Jira issue key (KEY-123) to auto-fetch from Jira when the jira skill is active."},ticketKey:{type:"string",description:"Optional label (e.g. SCRUM-123). If spec is an issue key, this defaults to that key."},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},headless:{type:"boolean",description:"Run browser headless (default false)"},workflow:{type:"string",description:"Workflow override (e.g. quick-smoke)"}},required:["spec"]}},{name:"run_status",description:'Instant progress check \u2014 returns immediately. Use this whenever user asks about test progress. ALWAYS use runId="all".',input_schema:{type:"object",properties:{runId:{type:"string",description:'Use "all" to see all runs in this session (recommended). Or a specific run ID if known.'}},required:["runId"]}},{name:"run_cancel",description:'Cancel/kill a running test. ONLY use when the USER explicitly asks to cancel or stop a run. NEVER auto-cancel \u2014 tests take 1-5 minutes and "running" is normal. Use runId="all" to cancel all active runs.',input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID to cancel, or "all" to cancel all active runs'}},required:["runId"]}},{name:"run_artifacts",description:"Read artifacts from a test run session. Can list files, read results/events/logs, or search across all sessions.",input_schema:{type:"object",properties:{runId:{type:"string",description:"Run ID from run_test. Omit to search across all sessions."},type:{type:"string",enum:["list","result","events","log","search"],description:'What to retrieve: "list" = all files in session, "result" = result.json, "events" = events.json, "log" = raw output tail, "search" = search text across sessions'},node:{type:"string",description:'Node name to read from (e.g. "execute_live", "generate_script"). Default: "execute_live"'},query:{type:"string",description:'Search text (only for type="search"). Searches across all session logs/events.'},tail:{type:"number",description:"Number of characters from end of log to return (default: 3000)"}},required:["type"]}},{name:"run_diagnose",description:"Diagnose one or all runs, especially failed ones. Uses run logs + known error patterns and returns likely root cause with suggested next action.",input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID from run_test, or "all" (default) to diagnose all known runs'},tail:{type:"number",description:"Characters of run log tail to inspect (default: 2000)"}}}},{name:"list_specs",description:"List available test spec files in the project",input_schema:{type:"object",properties:{directory:{type:"string",description:'Directory to scan (default: "test-specs")'}}}}]};function ut(){let s=0;for(let[,t]of P)t.status==="running"&&s++;return s}function xr(){for(;X.length>0;){let s=Dr(X[0]?.context?.options?.config);if(ut()>=s)break;let{args:t,cwd:e,context:r}=X.shift();Gr(t,e,r)}}async function ma(s,t){let{ticket:e,description:r,input:n,repo:i,agent:o,output:a}=s,c=["generate"];e&&c.push("--ticket",e),r&&c.push("--description",r),n&&c.push("--input",n),i&&c.push("--repo",i),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,u=l&&d.includes(l)?l:null;u&&c.push("--agent",u);let p=e||"generate";return C(p,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{Jr&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(g=>/\s/.test(g)?JSON.stringify(g):g).join(" ")} cwd=${t}`);let f=qr("zibby",c,{cwd:t,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",_="";f.stdout.on("data",g=>{let b=g.toString();h+=b;for(let y of b.split(`
557
+ `)){let w=Br(y).trim();w.startsWith("\u2705")?C(p,"\u2705",w.slice(2).trim()):w.startsWith("\u2713")&&C(p,"\u2714",w.slice(2).trim())}}),f.stderr.on("data",g=>{_+=g.toString()}),f.on("close",g=>{if(g!==0){C(p,"\u274C",`Generation failed (exit ${g})`),m(JSON.stringify({error:`zibby generate failed with exit code ${g}`,stderr:_.slice(-1e3)}));return}let b=ie(t,a||"test-specs"),y=[];try{let w=e?e.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";y=Fe(b).filter(A=>A.endsWith(".txt")&&(!w||A.startsWith(w))).map(A=>B(b,A))}catch{}C(p,"\u2705",`Generated ${y.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:e||null,specFiles:y.map(w=>w.replace(`${t}/`,"")),total:y.length,message:`Generated ${y.length} specs. Now call run_test for each file.`}))}),f.on("error",g=>{C(p,"\u274C",`Spawn error: ${g.message}`),m(JSON.stringify({error:g.message}))})})}var jr=1e5,$r=/^[A-Z][A-Z0-9]+-\d+$/,fa=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function ha(s,t){if(!t||!t.length)return s;let e=s;for(let r of t)r.type==="strong"?e=`**${e}**`:r.type==="em"?e=`_${e}_`:r.type==="code"?e=`\`${e}\``:r.type==="strike"?e=`~~${e}~~`:r.type==="link"&&r.attrs?.href&&(e=`[${e}](${r.attrs.href})`);return e}function Ke(s,t=0){if(!Array.isArray(s))return"";let e=[];for(let r of s){if(r.type==="text"){e.push(ha(r.text||"",r.marks));continue}if(r.type==="hardBreak"){e.push(`
546
558
  `);continue}if(r.type==="rule"){e.push(`
547
559
  ---
548
- `);continue}let i=r.content?Pe(r.content,t+1):"";if(r.type==="listItem")e.push(i);else if(r.type==="bulletList"){let n=(r.content||[]).map(o=>`- ${Pe(o.content||[],t+1).trim()}`);e.push(`
549
- ${n.join(`
560
+ `);continue}let n=r.content?Ke(r.content,t+1):"";if(r.type==="listItem")e.push(n);else if(r.type==="bulletList"){let i=(r.content||[]).map(o=>`- ${Ke(o.content||[],t+1).trim()}`);e.push(`
561
+ ${i.join(`
550
562
  `)}
551
- `)}else if(r.type==="orderedList"){let n=(r.content||[]).map((o,c)=>`${c+1}. ${Pe(o.content||[],t+1).trim()}`);e.push(`
552
- ${n.join(`
563
+ `)}else if(r.type==="orderedList"){let i=(r.content||[]).map((o,a)=>`${a+1}. ${Ke(o.content||[],t+1).trim()}`);e.push(`
564
+ ${i.join(`
553
565
  `)}
554
- `)}else if(r.type==="heading"){let n=r.attrs?.level||2;e.push(`
566
+ `)}else if(r.type==="heading"){let i=r.attrs?.level||2;e.push(`
555
567
 
556
- ${"#".repeat(n)} ${i.trim()}
568
+ ${"#".repeat(i)} ${n.trim()}
557
569
 
558
- `)}else Mo.has(r.type)?e.push(`
570
+ `)}else fa.has(r.type)?e.push(`
559
571
 
560
- ${i}
561
- `):e.push(i)}return e.join("").replace(/\n{3,}/g,`
572
+ ${n}
573
+ `):e.push(n)}return e.join("").replace(/\n{3,}/g,`
562
574
 
563
- `)}function Ko(s){return s==null||s===""?"":typeof s=="string"?s.trim():typeof s=="object"&&Array.isArray(s.content)?Pe(s.content).trim():""}async function Go(s){let{getSkill:t}=await import("@zibby/agent-workflow"),e=t("jira");if(!e||typeof e.handleToolCall!="function")return null;try{let r=await e.handleToolCall("jira_get_issue",{issueKey:s}),i=JSON.parse(r);if(i?.error)return null;let n=await e.handleToolCall("jira_get_comments",{issueKey:s,maxResults:50}),o=JSON.parse(n);if(o?.error)return null;let c=Ko(i.description),a=[];c&&a.push(c);let d=Array.isArray(o.comments)?o.comments:[];if(d.length>0){let u=d.map(p=>String(p.body||"").trim()).filter(Boolean).join(`
575
+ `)}function ya(s){return s==null||s===""?"":typeof s=="string"?s.trim():typeof s=="object"&&Array.isArray(s.content)?Ke(s.content).trim():""}async function ga(s){let{getSkill:t}=await import("@zibby/agent-workflow"),e=t("jira");if(!e||typeof e.handleToolCall!="function")return null;try{let r=await e.handleToolCall("jira_get_issue",{issueKey:s}),n=JSON.parse(r);if(n?.error)return null;let i=await e.handleToolCall("jira_get_comments",{issueKey:s,maxResults:50}),o=JSON.parse(i);if(o?.error)return null;let a=ya(n.description),c=[];a&&c.push(a);let d=Array.isArray(o.comments)?o.comments:[];if(d.length>0){let u=d.map(p=>String(p.body||"").trim()).filter(Boolean).join(`
564
576
 
565
- `);u&&a.push(u)}let l=a.join(`
577
+ `);u&&c.push(u)}let l=c.join(`
566
578
 
567
- `).trim();return l?(l.length>br&&(l=`${l.slice(0,br)}
579
+ `).trim();return l?(l.length>jr&&(l=`${l.slice(0,jr)}
568
580
 
569
- ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:s}):null}catch{return null}}function Fo(s,t){try{let e=JSON.parse(s);return JSON.stringify({...e,...t})}catch{return s}}async function Ho(s,t,e){let r={...s},i=String(r.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let n=null;if(wr.test(i)&&!i.startsWith("inline:")){let l=await Go(i);l&&(i=l.inlineSpec,r.spec=i,String(r.ticketKey||"").trim()||(r.ticketKey=l.issueKey),n=l.issueKey)}let o=String(r.ticketKey||"").trim();if(o){for(let[l,u]of P.entries())if(u?.ticketKey===o&&!(u?.status!=="running"&&u?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:u.status,reused:!0,message:`A run for ${o} is already ${u.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let l=ie(t,i);if(!G(l))return wr.test(i)?JSON.stringify({error:`Invalid run_test spec: "${i}" is an issue id, not a spec.`,reason:"Jira auto-load was attempted but did not return usable text, or Jira is not configured.",doNext:["Confirm the jira skill is active and authenticated.",'Or call tracker tools yourself, then run_test with spec: "inline:" + steps.'],validExample:{spec:"inline:1. Open https://example.com \u2026 2. Verify \u2026",ticketKey:i},invalidExample:{spec:i,ticketKey:i}}):JSON.stringify({error:`Test spec not found: ${i}`,hint:'If this should be issue steps, load the issue with your tracker tools first, then run_test with spec: "inline:" + steps. Otherwise use a real file path.'})}let c=Nr(e?.options?.config);if(st()>=c){let l=Rr(),u=r.ticketKey||l,p={runId:l,spec:r.ticketKey?`${r.ticketKey}: ${r.spec}`:r.spec,ticketKey:r.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};P.set(l,p),Q.push({args:{...r,_queuedRunId:l},cwd:t,context:e}),C(u,"\u23F3",`Queued (${st()}/${c} running, ${Q.length} queued)`);let m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${c} concurrent).`};return n&&(m.resolvedFromJiraIssue=n,m.message+=` (spec built from Jira ${n})`),JSON.stringify(m)}let a=Date.now()-rt;a<yr&&rt>0&&await new Promise(l=>setTimeout(l,yr-a)),rt=Date.now();let d=Er(r,t,e);return n?Fo(d,{resolvedFromJiraIssue:n,message:`Spec was loaded from Jira issue ${n} (description + comments).`}):d}function Er(s,t,e){let{spec:r,ticketKey:i,agent:n,headless:o,workflow:c,_queuedRunId:a}=s,d=a||Rr(),l=r,u=!1;if(r.startsWith("inline:")){u=!0;let T=Uo(t);hr(T,{recursive:!0}),l=B(T,`${d}.txt`),$o(l,r.slice(7).trim(),"utf-8")}let p=ie(t,".zibby","output","runs");hr(p,{recursive:!0});let m=B(p,`${d}.log`),f=Co(m,{flags:"a"}),_=n&&["assistant","cursor","claude","codex","gemini"].includes(n)?n:null,g=["test",l];_&&g.push("--agent",_),o&&g.push("--headless"),c&&g.push("--workflow",c),Or&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${g.map(T=>/\s/.test(T)?JSON.stringify(T):T).join(" ")} cwd=${t}`);let b=Ir("zibby",g,{cwd:t,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),y={runId:d,spec:i?`${i}: ${r}`:r,ticketKey:i||null,specPath:l,logPath:m,isInline:u,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=i||d,A="";function W(T){let O=Tr(T).trim();if(!O)return;if(O.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let L=JSON.parse(O.slice(22));L.phase==="node_begin"?y.currentNode=L.node:L.phase==="node_end"&&(L.node&&!y.completedNodes.includes(L.node)&&y.completedNodes.push(L.node),y.currentNode===L.node&&(y.currentNode=null))}catch{}return}let J=O.match(/Session\s+(\S+)/);if(J&&!y.sessionId&&(y.sessionId=J[1],y.sessionPath=ie(t,nt,it,y.sessionId)),O.startsWith("\u250C ")||O.startsWith("\u250C ")){let L=O.slice(2).trim();y.currentNode=L,Ce&&C(k,"\u25B6",`${L}`)}else if(O.startsWith("\u2514 ")||O.startsWith("\u2514 ")){let L=O.slice(2).trim();L.startsWith("done")?(y.currentNode&&!y.completedNodes.includes(y.currentNode)&&y.completedNodes.push(y.currentNode),Ce&&C(k,"\u2714",`${y.currentNode||"node"} done ${L.replace("done","").trim()}`),y.currentNode=null):L.startsWith("failed")&&(Ce&&C(k,"\u2718",`${y.currentNode||"node"} failed ${L.replace("failed","").trim()}`),y.currentNode=null)}else O.includes("Workflow completed")&&(y.currentNode=null,Ce&&C(k,"\u2714",`Workflow completed (${gr(Date.now()-y.startTime)})`))}function Ye(T){let O=T.toString();y.output+=O,f.write(O),y.output.length>5e4&&(y.output=y.output.slice(-3e4)),A+=O;let J=A.split(`
570
- `);A=J.pop();for(let L of J)W(L)}return b.stdout.on("data",Ye),b.stderr.on("data",T=>{let O=T.toString();y.error+=O,f.write(O),y.error.length>2e4&&(y.error=y.error.slice(-1e4))}),b.on("close",T=>{y.status=T===0?"passed":"failed",y.exitCode=T,y.endTime=Date.now(),A&&W(A),f.end();let O=gr(Date.now()-y.startTime);if(T===0?C(k,"\u2705",`Passed (${O})`):C(k,"\u274C",`Failed (${O})`),y.isInline)try{xo(y.specPath)}catch{}_r()}),b.on("error",T=>{y.status="error",y.error+=`
571
- Spawn error: ${T.message}`,C(k,"\u274C",`Spawn error: ${T.message}`),f.end(),_r()}),y._child=b,P.set(d,y),JSON.stringify({runId:d,spec:y.spec,ticketKey:y.ticketKey,status:"running",pid:b.pid,logFile:m})}function kr(s){let t=Math.round(((s.endTime||Date.now())-s.startTime)/1e3),e=s.completedNodes||[],r=s.currentNode||null;if(s.status!=="running")return{elapsed:t,stage:s.status,completedNodes:e,currentNode:null};let i;return r?(i=`Actively executing node "${r}"`,e.length&&(i+=` (completed: ${e.join(", ")})`)):e.length?i=`Between nodes (completed: ${e.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${t}s. This is normal progress \u2014 do not cancel.`,{elapsed:t,stage:"running",currentNode:r,completedNodes:e,progress:i}}function zo(s){let{runId:t}=s;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let n=[...P.entries()].map(([l,u])=>{let p=kr(u),m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:u.status,elapsed:p.elapsed,exitCode:u.exitCode,sessionId:u.sessionId||null};return u.status==="running"?(m.currentNode=p.currentNode,m.completedNodes=p.completedNodes,m.progress=p.progress):m.outputTail=u.output.slice(-500),m}),o=n.filter(l=>l.status==="running").length,c=n.filter(l=>l.status==="passed").length,a=n.filter(l=>l.status==="failed").length,d={total:n.length,running:o,passed:c,failed:a,runs:n};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let e=P.get(t);if(!e)return JSON.stringify({error:`Run not found: ${t}`});let r=kr(e),i={runId:t,spec:e.spec,ticketKey:e.ticketKey,status:e.status,elapsed:r.elapsed,exitCode:e.exitCode,sessionId:e.sessionId||null};return e.status==="running"?(i.currentNode=r.currentNode,i.completedNodes=r.completedNodes,i.progress=r.progress):(i.outputTail=e.output.slice(-1e3),i.errorTail=e.error.slice(-500)),e.status==="running"&&(i._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(i)}function Sr(s,t){if(t.status==="queued"){let e=Q.findIndex(r=>r.args._queuedRunId===s);return e>=0&&Q.splice(e,1),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:s,status:"cancelled"}}if(t.status!=="running")return{ok:!1,runId:s,error:`Run is not active (status: ${t.status})`};try{return t._child.kill("SIGTERM"),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:s,status:"cancelled"}}catch(e){return{ok:!1,runId:s,error:`Failed to cancel: ${e.message}`}}}function Yo(s){let{runId:t}=s;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let r=[];for(let[i,n]of P.entries())(n.status==="running"||n.status==="queued")&&r.push(Sr(i,n));return r.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:r.length,results:r})}let e=P.get(t);return JSON.stringify(e?Sr(t,e):{error:`Run not found: ${t}`})}function Wo(s,t){let e=P.get(s);if(e?.sessionPath&&G(e.sessionPath))return e.sessionPath;if(e?.sessionId){let r=ie(t,nt,it,e.sessionId);if(G(r))return r}return null}function jr(s,t=""){let e=[];if(!G(s))return e;for(let r of qe(s,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;if(r.isDirectory())e.push(...jr(B(s,r.name),i));else{let n=Po(B(s,r.name));e.push({path:i,size:n.size})}}return e}function vr(s){if(!G(s))return null;try{return JSON.parse(Ue(s,"utf-8"))}catch{return null}}function Lr(s,t=2e3){if(!s||!G(s))return"";try{return Ue(s,"utf-8").slice(-Math.max(200,Number(t)||2e3))}catch{return""}}function Zo({run:s,logTail:t,errorTail:e}){let i=`${t||""}
572
- ${e||""}`.toLowerCase(),n={runId:s?.runId||null,status:s?.status||null,exitCode:s?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return s?.status==="running"||s?.status==="queued"?{...n,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:i.includes("test spec not found")?{...n,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:i.includes("unknown command")&&i.includes("'run'")?{...n,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:i.includes("missing openai_api_key")||i.includes("didn't provide an api key")||i.includes("401")?{...n,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:i.includes("spawn error")||i.includes("enoent")?{...n,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:i.includes("security command failed")||i.includes("security process exited with code: 45")||i.includes("password not found for account")?{...n,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:n}function Vo(s,t){let{runId:e,type:r,node:i="execute_live",query:n,tail:o=3e3}=s;if(r==="search"){if(!n)return JSON.stringify({error:'query is required for type="search"'});let a=ie(t,nt,it);if(!G(a))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=n.toLowerCase();for(let u of qe(a,{withFileTypes:!0})){if(!u.isDirectory())continue;let p=B(a,u.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let _=B(p,f);if(G(_))try{let g=Ue(_,"utf-8");if(g.toLowerCase().includes(l)){let b=g.toLowerCase().indexOf(l),y=Math.max(0,b-100),k=Math.min(g.length,b+n.length+100);d.push({sessionId:u.name,artifact:h,snippet:g.slice(y,k)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:n,matches:d,total:d.length})}if(!e)return JSON.stringify({error:"runId is required for this type"});if(r==="log"){let a=P.get(e),d=Lr(a?.logPath,o);if(d)return JSON.stringify({runId:e,source:"run-log",totalLength:d.length,tail:d})}let c=Wo(e,t);if(!c)return JSON.stringify({error:`No session found for run ${e}. The run may still be starting.`});switch(r){case"list":{let a=jr(c);return JSON.stringify({sessionId:c.split("/").pop(),files:a,total:a.length})}case"result":{let a=vr(B(c,i,"result.json"));return JSON.stringify(a?{sessionId:c.split("/").pop(),node:i,result:a}:{error:`No result.json found in ${i}`})}case"events":{let a=vr(B(c,i,"events.json"));if(!a)return JSON.stringify({error:`No events.json found in ${i}`});let d=Array.isArray(a)?a:a.events||[];return JSON.stringify({sessionId:c.split("/").pop(),node:i,totalEvents:d.length,events:d.slice(-50)})}case"log":{let a=B(c,i,"raw_stream_output.txt");if(!G(a))return JSON.stringify({error:`No log found in ${i}`});let d=Ue(a,"utf-8");return JSON.stringify({sessionId:c.split("/").pop(),node:i,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${r}. Use: list, result, events, log, search`})}}function Qo(s,t){let e=String(s?.runId||"all"),r=Number(s?.tail||2e3),i=e==="all"?[...P.keys()]:[e];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let n=i.map(a=>{let d=P.get(a);if(!d)return{runId:a,error:`Run not found: ${a}`};let l=Lr(d.logPath,r),u=String(d.error||"").slice(-Math.max(200,r));return{...Zo({run:d,logTail:l,errorTail:u}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:u}}),o=n.filter(a=>a.status==="failed"||a.status==="error"),c=n.filter(a=>a.status==="running"||a.status==="queued");return JSON.stringify({total:n.length,failed:o.length,active:c.length,diagnoses:n})}function Xo(s,t){let e=s?.directory||"test-specs",r=ie(t,e);if(!G(r))return JSON.stringify({specs:[],directory:e,message:`Directory not found: ${e}`});try{let n=function(o,c){for(let a of qe(o,{withFileTypes:!0})){let d=c?`${c}/${a.name}`:a.name;a.isDirectory()?n(B(o,a.name),d):(a.name.endsWith(".txt")||a.name.endsWith(".md"))&&i.push(d)}},i=[];return n(r,""),JSON.stringify({specs:i.map(o=>`${e}/${o}`),total:i.length,directory:e})}catch(i){return JSON.stringify({error:i.message})}}import{spawn as ea}from"child_process";import{existsSync as F,mkdirSync as ta,readdirSync as $r,statSync as ra,readFileSync as sa}from"fs";import{resolve as at,join as H,basename as ia}from"path";var ct=".zibby/repos";function De(s,t,e={}){return new Promise((r,i)=>{let n=ea(s,{cwd:t,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),o="",c="";n.stdout.on("data",a=>{o+=a.toString()}),n.stderr.on("data",a=>{c+=a.toString()}),n.on("close",a=>{a!==0?i(new Error(`Exit ${a}: ${c.trim()||o.trim()}`)):r(o.trim())}),n.on("error",a=>i(a))})}var X={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
581
+ ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:s}):null}catch{return null}}function _a(s,t){try{let e=JSON.parse(s);return JSON.stringify({...e,...t})}catch{return s}}async function ba(s,t,e){let r={...s},n=String(r.spec??"").trim();if(!n)return JSON.stringify({error:"spec is required"});let i=null;if($r.test(n)&&!n.startsWith("inline:")){let l=await ga(n);l&&(n=l.inlineSpec,r.spec=n,String(r.ticketKey||"").trim()||(r.ticketKey=l.issueKey),i=l.issueKey)}let o=String(r.ticketKey||"").trim();if(o){for(let[l,u]of P.entries())if(u?.ticketKey===o&&!(u?.status!=="running"&&u?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:u.status,reused:!0,message:`A run for ${o} is already ${u.status}. Reusing existing run instead of starting a duplicate.`})}if(!n.startsWith("inline:")){let l=ie(t,n);if(!G(l))return $r.test(n)?JSON.stringify({error:`Invalid run_test spec: "${n}" is an issue id, not a spec.`,reason:"Jira auto-load was attempted but did not return usable text, or Jira is not configured.",doNext:["Confirm the jira skill is active and authenticated.",'Or call tracker tools yourself, then run_test with spec: "inline:" + steps.'],validExample:{spec:"inline:1. Open https://example.com \u2026 2. Verify \u2026",ticketKey:n},invalidExample:{spec:n,ticketKey:n}}):JSON.stringify({error:`Test spec not found: ${n}`,hint:'If this should be issue steps, load the issue with your tracker tools first, then run_test with spec: "inline:" + steps. Otherwise use a real file path.'})}let a=Dr(e?.options?.config);if(ut()>=a){let l=Mr(),u=r.ticketKey||l,p={runId:l,spec:r.ticketKey?`${r.ticketKey}: ${r.spec}`:r.spec,ticketKey:r.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};P.set(l,p),X.push({args:{...r,_queuedRunId:l},cwd:t,context:e}),C(u,"\u23F3",`Queued (${ut()}/${a} running, ${X.length} queued)`);let m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return i&&(m.resolvedFromJiraIssue=i,m.message+=` (spec built from Jira ${i})`),JSON.stringify(m)}let c=Date.now()-dt;c<Er&&dt>0&&await new Promise(l=>setTimeout(l,Er-c)),dt=Date.now();let d=Gr(r,t,e);return i?_a(d,{resolvedFromJiraIssue:i,message:`Spec was loaded from Jira issue ${i} (description + comments).`}):d}function Gr(s,t,e){let{spec:r,ticketKey:n,agent:i,headless:o,workflow:a,_queuedRunId:c}=s,d=c||Mr(),l=r,u=!1;if(r.startsWith("inline:")){u=!0;let T=da(t);Ar(T,{recursive:!0}),l=B(T,`${d}.txt`),oa(l,r.slice(7).trim(),"utf-8")}let p=ie(t,".zibby","output","runs");Ar(p,{recursive:!0});let m=B(p,`${d}.log`),f=ca(m,{flags:"a"}),_=i&&["assistant","cursor","claude","codex","gemini"].includes(i)?i:null,g=["test",l];_&&g.push("--agent",_),o&&g.push("--headless"),a&&g.push("--workflow",a),Jr&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${g.map(T=>/\s/.test(T)?JSON.stringify(T):T).join(" ")} cwd=${t}`);let b=qr("zibby",g,{cwd:t,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),y={runId:d,spec:n?`${n}: ${r}`:r,ticketKey:n||null,specPath:l,logPath:m,isInline:u,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},w=n||d,A="";function W(T){let O=Br(T).trim();if(!O)return;if(O.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let x=JSON.parse(O.slice(22));x.phase==="node_begin"?y.currentNode=x.node:x.phase==="node_end"&&(x.node&&!y.completedNodes.includes(x.node)&&y.completedNodes.push(x.node),y.currentNode===x.node&&(y.currentNode=null))}catch{}return}let J=O.match(/Session\s+(\S+)/);if(J&&!y.sessionId&&(y.sessionId=J[1],y.sessionPath=ie(t,mt,pt,y.sessionId)),O.startsWith("\u250C ")||O.startsWith("\u250C ")){let x=O.slice(2).trim();y.currentNode=x,Be&&C(w,"\u25B6",`${x}`)}else if(O.startsWith("\u2514 ")||O.startsWith("\u2514 ")){let x=O.slice(2).trim();x.startsWith("done")?(y.currentNode&&!y.completedNodes.includes(y.currentNode)&&y.completedNodes.push(y.currentNode),Be&&C(w,"\u2714",`${y.currentNode||"node"} done ${x.replace("done","").trim()}`),y.currentNode=null):x.startsWith("failed")&&(Be&&C(w,"\u2718",`${y.currentNode||"node"} failed ${x.replace("failed","").trim()}`),y.currentNode=null)}else O.includes("Workflow completed")&&(y.currentNode=null,Be&&C(w,"\u2714",`Workflow completed (${Lr(Date.now()-y.startTime)})`))}function tt(T){let O=T.toString();y.output+=O,f.write(O),y.output.length>5e4&&(y.output=y.output.slice(-3e4)),A+=O;let J=A.split(`
582
+ `);A=J.pop();for(let x of J)W(x)}return b.stdout.on("data",tt),b.stderr.on("data",T=>{let O=T.toString();y.error+=O,f.write(O),y.error.length>2e4&&(y.error=y.error.slice(-1e4))}),b.on("close",T=>{y.status=T===0?"passed":"failed",y.exitCode=T,y.endTime=Date.now(),A&&W(A),f.end();let O=Lr(Date.now()-y.startTime);if(T===0?C(w,"\u2705",`Passed (${O})`):C(w,"\u274C",`Failed (${O})`),y.isInline)try{aa(y.specPath)}catch{}xr()}),b.on("error",T=>{y.status="error",y.error+=`
583
+ Spawn error: ${T.message}`,C(w,"\u274C",`Spawn error: ${T.message}`),f.end(),xr()}),y._child=b,P.set(d,y),JSON.stringify({runId:d,spec:y.spec,ticketKey:y.ticketKey,status:"running",pid:b.pid,logFile:m})}function Cr(s){let t=Math.round(((s.endTime||Date.now())-s.startTime)/1e3),e=s.completedNodes||[],r=s.currentNode||null;if(s.status!=="running")return{elapsed:t,stage:s.status,completedNodes:e,currentNode:null};let n;return r?(n=`Actively executing node "${r}"`,e.length&&(n+=` (completed: ${e.join(", ")})`)):e.length?n=`Between nodes (completed: ${e.join(", ")})`:n="Starting up (initializing workflow)",n+=`. Elapsed: ${t}s. This is normal progress \u2014 do not cancel.`,{elapsed:t,stage:"running",currentNode:r,completedNodes:e,progress:n}}function ka(s){let{runId:t}=s;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let i=[...P.entries()].map(([l,u])=>{let p=Cr(u),m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:u.status,elapsed:p.elapsed,exitCode:u.exitCode,sessionId:u.sessionId||null};return u.status==="running"?(m.currentNode=p.currentNode,m.completedNodes=p.completedNodes,m.progress=p.progress):m.outputTail=u.output.slice(-500),m}),o=i.filter(l=>l.status==="running").length,a=i.filter(l=>l.status==="passed").length,c=i.filter(l=>l.status==="failed").length,d={total:i.length,running:o,passed:a,failed:c,runs:i};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let e=P.get(t);if(!e)return JSON.stringify({error:`Run not found: ${t}`});let r=Cr(e),n={runId:t,spec:e.spec,ticketKey:e.ticketKey,status:e.status,elapsed:r.elapsed,exitCode:e.exitCode,sessionId:e.sessionId||null};return e.status==="running"?(n.currentNode=r.currentNode,n.completedNodes=r.completedNodes,n.progress=r.progress):(n.outputTail=e.output.slice(-1e3),n.errorTail=e.error.slice(-500)),e.status==="running"&&(n._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(n)}function Pr(s,t){if(t.status==="queued"){let e=X.findIndex(r=>r.args._queuedRunId===s);return e>=0&&X.splice(e,1),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:s,status:"cancelled"}}if(t.status!=="running")return{ok:!1,runId:s,error:`Run is not active (status: ${t.status})`};try{return t._child.kill("SIGTERM"),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:s,status:"cancelled"}}catch(e){return{ok:!1,runId:s,error:`Failed to cancel: ${e.message}`}}}function wa(s){let{runId:t}=s;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let r=[];for(let[n,i]of P.entries())(i.status==="running"||i.status==="queued")&&r.push(Pr(n,i));return r.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:r.length,results:r})}let e=P.get(t);return JSON.stringify(e?Pr(t,e):{error:`Run not found: ${t}`})}function Sa(s,t){let e=P.get(s);if(e?.sessionPath&&G(e.sessionPath))return e.sessionPath;if(e?.sessionId){let r=ie(t,mt,pt,e.sessionId);if(G(r))return r}return null}function Fr(s,t=""){let e=[];if(!G(s))return e;for(let r of Fe(s,{withFileTypes:!0})){let n=t?`${t}/${r.name}`:r.name;if(r.isDirectory())e.push(...Fr(B(s,r.name),n));else{let i=la(B(s,r.name));e.push({path:n,size:i.size})}}return e}function Ur(s){if(!G(s))return null;try{return JSON.parse(Ge(s,"utf-8"))}catch{return null}}function Hr(s,t=2e3){if(!s||!G(s))return"";try{return Ge(s,"utf-8").slice(-Math.max(200,Number(t)||2e3))}catch{return""}}function Ia({run:s,logTail:t,errorTail:e}){let n=`${t||""}
584
+ ${e||""}`.toLowerCase(),i={runId:s?.runId||null,status:s?.status||null,exitCode:s?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return s?.status==="running"||s?.status==="queued"?{...i,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:n.includes("test spec not found")?{...i,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:n.includes("unknown command")&&n.includes("'run'")?{...i,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:n.includes("missing openai_api_key")||n.includes("didn't provide an api key")||n.includes("401")?{...i,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:n.includes("spawn error")||n.includes("enoent")?{...i,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:n.includes("security command failed")||n.includes("security process exited with code: 45")||n.includes("password not found for account")?{...i,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:i}function va(s,t){let{runId:e,type:r,node:n="execute_live",query:i,tail:o=3e3}=s;if(r==="search"){if(!i)return JSON.stringify({error:'query is required for type="search"'});let c=ie(t,mt,pt);if(!G(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=i.toLowerCase();for(let u of Fe(c,{withFileTypes:!0})){if(!u.isDirectory())continue;let p=B(c,u.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let _=B(p,f);if(G(_))try{let g=Ge(_,"utf-8");if(g.toLowerCase().includes(l)){let b=g.toLowerCase().indexOf(l),y=Math.max(0,b-100),w=Math.min(g.length,b+i.length+100);d.push({sessionId:u.name,artifact:h,snippet:g.slice(y,w)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:i,matches:d,total:d.length})}if(!e)return JSON.stringify({error:"runId is required for this type"});if(r==="log"){let c=P.get(e),d=Hr(c?.logPath,o);if(d)return JSON.stringify({runId:e,source:"run-log",totalLength:d.length,tail:d})}let a=Sa(e,t);if(!a)return JSON.stringify({error:`No session found for run ${e}. The run may still be starting.`});switch(r){case"list":{let c=Fr(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=Ur(B(a,n,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:n,result:c}:{error:`No result.json found in ${n}`})}case"events":{let c=Ur(B(a,n,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${n}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:n,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=B(a,n,"raw_stream_output.txt");if(!G(c))return JSON.stringify({error:`No log found in ${n}`});let d=Ge(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:n,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${r}. Use: list, result, events, log, search`})}}function Na(s,t){let e=String(s?.runId||"all"),r=Number(s?.tail||2e3),n=e==="all"?[...P.keys()]:[e];if(n.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let i=n.map(c=>{let d=P.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=Hr(d.logPath,r),u=String(d.error||"").slice(-Math.max(200,r));return{...Ia({run:d,logTail:l,errorTail:u}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:u}}),o=i.filter(c=>c.status==="failed"||c.status==="error"),a=i.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:i.length,failed:o.length,active:a.length,diagnoses:i})}function Oa(s,t){let e=s?.directory||"test-specs",r=ie(t,e);if(!G(r))return JSON.stringify({specs:[],directory:e,message:`Directory not found: ${e}`});try{let i=function(o,a){for(let c of Fe(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?i(B(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&n.push(d)}},n=[];return i(r,""),JSON.stringify({specs:n.map(o=>`${e}/${o}`),total:n.length,directory:e})}catch(n){return JSON.stringify({error:n.message})}}import{spawn as Ra}from"child_process";import{existsSync as F,mkdirSync as Ta,readdirSync as zr,statSync as Aa,readFileSync as Ea}from"fs";import{resolve as ht,join as H,basename as La}from"path";var yt=".zibby/repos";function He(s,t,e={}){return new Promise((r,n)=>{let i=Ra(s,{cwd:t,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),o="",a="";i.stdout.on("data",c=>{o+=c.toString()}),i.stderr.on("data",c=>{a+=c.toString()}),i.on("close",c=>{c!==0?n(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):r(o.trim())}),i.on("error",c=>n(c))})}var ee={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
573
585
  You can clone and explore git repositories locally for codebase analysis:
574
586
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
575
587
  - git_list_repos: List locally cloned repos
@@ -580,7 +592,7 @@ When a test ticket lacks context, use this workflow:
580
592
  2. Use git_explore to understand the project structure
581
593
  3. Use shell commands (grep, cat) to read specific files for deeper understanding
582
594
  4. Use GitHub/GitLab skills to read related PRs and commits
583
- 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"git_checkout":return await na(t,r);case"git_list_repos":return oa(t,r);case"git_explore":return aa(t,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"git_checkout",description:"Clone a git repository locally (or pull latest if already cloned). Auto-authenticates with GitHub/GitLab tokens if available.",input_schema:{type:"object",properties:{url:{type:"string",description:'Repository URL (e.g. "https://github.com/org/repo" or "org/repo" shorthand for GitHub)'},branch:{type:"string",description:"Branch to checkout (default: repo default branch)"},shallow:{type:"boolean",description:"Shallow clone with depth 1 (default: true, faster)"},name:{type:"string",description:"Local directory name override (default: repo name from URL)"}},required:["url"]}},{name:"git_list_repos",description:"List locally cloned repositories",input_schema:{type:"object",properties:{}}},{name:"git_explore",description:"Quick structural overview of a cloned repo: key files, package.json info, directory tree (top 2 levels), detected framework/language",input_schema:{type:"object",properties:{repo:{type:"string",description:"Repo name (as listed by git_list_repos)"},depth:{type:"number",description:"Directory tree depth (default: 2)"}},required:["repo"]}}]};async function na(s,t){let{url:e,branch:r,shallow:i=!0,name:n}=s;!e.includes("://")&&!e.startsWith("git@")&&(e=`https://github.com/${e}`);let o=n||ia(e.replace(/\.git$/,"")),c=at(t,ct);ta(c,{recursive:!0});let a=H(c,o),d=e,l=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,p=process.env.GITLAB_URL;if(e.includes("github.com")&&l)d=e.replace("https://github.com",`https://x-access-token:${l}@github.com`);else if(u&&p)try{let h=new URL(p).host;e.includes(h)&&(d=e.replace(`https://${h}`,`https://oauth2:${u}@${h}`))}catch{}if(F(H(a,".git"))){let h=r?`git -C "${a}" fetch origin ${r} && git -C "${a}" checkout ${r} && git -C "${a}" pull origin ${r}`:`git -C "${a}" pull`;await De(h,t);let _=await De(`git -C "${a}" log -1 --format="%h %s"`,t);return JSON.stringify({action:"updated",repo:o,path:a,branch:r||"default",head:_})}let m=["git","clone"];i&&m.push("--depth","1"),r&&m.push("--branch",r),m.push(`"${d}"`,`"${a}"`),await De(m.join(" "),t);let f=await De(`git -C "${a}" log -1 --format="%h %s"`,t);return JSON.stringify({action:"cloned",repo:o,path:a,branch:r||"default",shallow:i,head:f})}function oa(s,t){let e=at(t,ct);if(!F(e))return JSON.stringify({repos:[],message:"No repos cloned yet"});let r=[];for(let i of $r(e,{withFileTypes:!0})){if(!i.isDirectory())continue;let n=H(e,i.name);if(!F(H(n,".git")))continue;let o=ra(n);r.push({name:i.name,path:n,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:r,total:r.length,directory:e})}function aa(s,t){let{repo:e,depth:r=2}=s,i=at(t,ct,e);if(!F(i))return JSON.stringify({error:`Repo not found: ${e}. Run git_checkout first.`});let n={repo:e,path:i},o=H(i,"package.json");if(F(o))try{let m=JSON.parse(sa(o,"utf-8"));n.packageJson={name:m.name,version:m.version,scripts:m.scripts?Object.keys(m.scripts):[],dependencies:m.dependencies?Object.keys(m.dependencies).slice(0,30):[],devDependencies:m.devDependencies?Object.keys(m.devDependencies).slice(0,20):[]},m.dependencies?.react?n.framework="React":m.dependencies?.next?n.framework="Next.js":m.dependencies?.vue?n.framework="Vue":m.dependencies?.angular?n.framework="Angular":m.dependencies?.express?n.framework="Express":m.dependencies?.fastify&&(n.framework="Fastify")}catch{}let c=H(i,"pyproject.toml");F(c)&&(n.language="Python");let a=H(i,"go.mod");F(a)&&(n.language="Go");let d=H(i,"Cargo.toml");F(d)&&(n.language="Rust"),F(o)&&(n.language=n.language||"JavaScript/TypeScript");let l=[];function u(m,f,h){if(h>r)return;let _;try{_=$r(m,{withFileTypes:!0})}catch{return}let g=_.filter(b=>!b.name.startsWith(".")&&b.name!=="node_modules"&&b.name!=="__pycache__"&&b.name!=="dist"&&b.name!=="build"&&b.name!==".git").sort((b,y)=>b.isDirectory()!==y.isDirectory()?b.isDirectory()?-1:1:b.name.localeCompare(y.name));for(let b of g){let y=b.isDirectory();l.push(`${f}${y?"\u{1F4C1}":"\u{1F4C4}"} ${b.name}`),y&&h<r&&u(H(m,b.name),`${f} `,h+1)}}u(i,"",1),n.tree=l.slice(0,80),l.length>80&&(n.treeTruncated=!0);let p=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return n.keyFilesFound=p.filter(m=>F(H(i,m))),JSON.stringify(n)}function xr(s){let t=(s||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return t?{provider:"github",owner:t[1],repo:t[2]}:(t=(s||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),t?{provider:"gitlab",owner:t[1],repo:t[2]}:null)}var Cr={...X,id:"git-write",envKeys:[...X.envKeys||[],...ae.envKeys||[],...ce.envKeys||[]].filter((s,t,e)=>e.indexOf(s)===t),promptFragment:`${X.promptFragment}
595
+ 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"git_checkout":return await xa(t,r);case"git_list_repos":return ja(t,r);case"git_explore":return $a(t,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(n){return JSON.stringify({error:n.message})}},tools:[{name:"git_checkout",description:"Clone a git repository locally (or pull latest if already cloned). Auto-authenticates with GitHub/GitLab tokens if available.",input_schema:{type:"object",properties:{url:{type:"string",description:'Repository URL (e.g. "https://github.com/org/repo" or "org/repo" shorthand for GitHub)'},branch:{type:"string",description:"Branch to checkout (default: repo default branch)"},shallow:{type:"boolean",description:"Shallow clone with depth 1 (default: true, faster)"},name:{type:"string",description:"Local directory name override (default: repo name from URL)"}},required:["url"]}},{name:"git_list_repos",description:"List locally cloned repositories",input_schema:{type:"object",properties:{}}},{name:"git_explore",description:"Quick structural overview of a cloned repo: key files, package.json info, directory tree (top 2 levels), detected framework/language",input_schema:{type:"object",properties:{repo:{type:"string",description:"Repo name (as listed by git_list_repos)"},depth:{type:"number",description:"Directory tree depth (default: 2)"}},required:["repo"]}}]};async function xa(s,t){let{url:e,branch:r,shallow:n=!0,name:i}=s;!e.includes("://")&&!e.startsWith("git@")&&(e=`https://github.com/${e}`);let o=i||La(e.replace(/\.git$/,"")),a=ht(t,yt);Ta(a,{recursive:!0});let c=H(a,o),d=e,l=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,p=process.env.GITLAB_URL;if(e.includes("github.com")&&l)d=e.replace("https://github.com",`https://x-access-token:${l}@github.com`);else if(u&&p)try{let h=new URL(p).host;e.includes(h)&&(d=e.replace(`https://${h}`,`https://oauth2:${u}@${h}`))}catch{}if(F(H(c,".git"))){let h=r?`git -C "${c}" fetch origin ${r} && git -C "${c}" checkout ${r} && git -C "${c}" pull origin ${r}`:`git -C "${c}" pull`;await He(h,t);let _=await He(`git -C "${c}" log -1 --format="%h %s"`,t);return JSON.stringify({action:"updated",repo:o,path:c,branch:r||"default",head:_})}let m=["git","clone"];n&&m.push("--depth","1"),r&&m.push("--branch",r),m.push(`"${d}"`,`"${c}"`),await He(m.join(" "),t);let f=await He(`git -C "${c}" log -1 --format="%h %s"`,t);return JSON.stringify({action:"cloned",repo:o,path:c,branch:r||"default",shallow:n,head:f})}function ja(s,t){let e=ht(t,yt);if(!F(e))return JSON.stringify({repos:[],message:"No repos cloned yet"});let r=[];for(let n of zr(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let i=H(e,n.name);if(!F(H(i,".git")))continue;let o=Aa(i);r.push({name:n.name,path:i,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:r,total:r.length,directory:e})}function $a(s,t){let{repo:e,depth:r=2}=s,n=ht(t,yt,e);if(!F(n))return JSON.stringify({error:`Repo not found: ${e}. Run git_checkout first.`});let i={repo:e,path:n},o=H(n,"package.json");if(F(o))try{let m=JSON.parse(Ea(o,"utf-8"));i.packageJson={name:m.name,version:m.version,scripts:m.scripts?Object.keys(m.scripts):[],dependencies:m.dependencies?Object.keys(m.dependencies).slice(0,30):[],devDependencies:m.devDependencies?Object.keys(m.devDependencies).slice(0,20):[]},m.dependencies?.react?i.framework="React":m.dependencies?.next?i.framework="Next.js":m.dependencies?.vue?i.framework="Vue":m.dependencies?.angular?i.framework="Angular":m.dependencies?.express?i.framework="Express":m.dependencies?.fastify&&(i.framework="Fastify")}catch{}let a=H(n,"pyproject.toml");F(a)&&(i.language="Python");let c=H(n,"go.mod");F(c)&&(i.language="Go");let d=H(n,"Cargo.toml");F(d)&&(i.language="Rust"),F(o)&&(i.language=i.language||"JavaScript/TypeScript");let l=[];function u(m,f,h){if(h>r)return;let _;try{_=zr(m,{withFileTypes:!0})}catch{return}let g=_.filter(b=>!b.name.startsWith(".")&&b.name!=="node_modules"&&b.name!=="__pycache__"&&b.name!=="dist"&&b.name!=="build"&&b.name!==".git").sort((b,y)=>b.isDirectory()!==y.isDirectory()?b.isDirectory()?-1:1:b.name.localeCompare(y.name));for(let b of g){let y=b.isDirectory();l.push(`${f}${y?"\u{1F4C1}":"\u{1F4C4}"} ${b.name}`),y&&h<r&&u(H(m,b.name),`${f} `,h+1)}}u(n,"",1),i.tree=l.slice(0,80),l.length>80&&(i.treeTruncated=!0);let p=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return i.keyFilesFound=p.filter(m=>F(H(n,m))),JSON.stringify(i)}function Yr(s){let t=(s||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return t?{provider:"github",owner:t[1],repo:t[2]}:(t=(s||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),t?{provider:"gitlab",owner:t[1],repo:t[2]}:null)}var Wr={...ee,id:"git-write",envKeys:[...ee.envKeys||[],...ce.envKeys||[],...le.envKeys||[]].filter((s,t,e)=>e.indexOf(s)===t),promptFragment:`${ee.promptFragment}
584
596
 
585
597
  ## Opening a pull request / merge request (git_open_pr)
586
598
  After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
@@ -592,7 +604,7 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
592
604
  To MERGE an open PR/MR, use the provider-agnostic tool:
593
605
  - git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
594
606
  { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
595
- Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(s,t,e){if(s!=="git_open_pr"&&s!=="git_merge_pr")return X.handleToolCall(s,t,e);try{let r=t||{},i=r.repoUrl||r.repo_url||r.url;if(!i)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(s==="git_merge_pr"){let l=r.number??r.iid??r.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let u=xr(i);return u?u.provider==="github"?ae.handleToolCall("github_merge_pr",{owner:u.owner,repo:u.repo,number:l,mergeMethod:r.mergeMethod},e):ce.handleToolCall("gitlab_accept_mr",{project:`${u.owner}/${u.repo}`,iid:l},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_merge_pr supports github.com and gitlab.com.`})}let n=r.head||r.source_branch||r.sourceBranch||r.branch,o=r.base||r.target_branch||r.targetBranch,{title:c,body:a}=r;if(!n||!c)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=xr(i);return d?d.provider==="github"?ae.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:n,base:o,title:c,body:a},e):ce.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:n,target_branch:o,title:c,description:a},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_open_pr supports github.com and gitlab.com.`})}catch(r){return JSON.stringify({error:r.message})}},tools:[...X.tools||[],{name:"git_open_pr",description:"Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. The provider is auto-detected from repoUrl. Returns the REAL provider-returned url (pr_url = GitHub html_url / GitLab web_url) \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR is opened against (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},head:{type:"string",description:"Source branch to merge FROM (must already be pushed). GitLab alias: source_branch."},base:{type:"string",description:"Target branch to merge INTO (default: the repo/project default branch). GitLab alias: target_branch."},title:{type:"string",description:"PR/MR title"},body:{type:"string",description:"PR/MR description (markdown)"}},required:["repoUrl","head","title"]}},{name:"git_merge_pr",description:"Merge a pull request (GitHub) or accept a merge request (GitLab) by number. The provider is auto-detected from repoUrl. Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider \u2014 never fabricate it. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR belongs to (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},number:{type:"number",description:"The PR (GitHub) / MR (GitLab) number to merge. GitLab alias: iid."},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (GitHub only; default: squash). Ignored for GitLab."}},required:["repoUrl","number"]}}]};import{execFileSync as Jr}from"child_process";import{existsSync as ft,mkdirSync as Mr}from"fs";import{join as z,basename as ca}from"path";import{randomBytes as la}from"crypto";import{pathToFileURL as ke}from"url";import{createRequire as Br}from"module";var ut=".zibby/memory",Kr="dolt",Gr={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},pt="mem0",lt=new Map,Je=new Map,Me=!1,da=Br(import.meta.url),Fe=()=>la(8).toString("hex"),ne=()=>new Date().toISOString(),ua=[`CREATE TABLE IF NOT EXISTS chat_memory (
607
+ Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(s,t,e){if(s!=="git_open_pr"&&s!=="git_merge_pr")return ee.handleToolCall(s,t,e);try{let r=t||{},n=r.repoUrl||r.repo_url||r.url;if(!n)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(s==="git_merge_pr"){let l=r.number??r.iid??r.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let u=Yr(n);return u?u.provider==="github"?ce.handleToolCall("github_merge_pr",{owner:u.owner,repo:u.repo,number:l,mergeMethod:r.mergeMethod},e):le.handleToolCall("gitlab_accept_mr",{project:`${u.owner}/${u.repo}`,iid:l},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${n}. git_merge_pr supports github.com and gitlab.com.`})}let i=r.head||r.source_branch||r.sourceBranch||r.branch,o=r.base||r.target_branch||r.targetBranch,{title:a,body:c}=r;if(!i||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=Yr(n);return d?d.provider==="github"?ce.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:i,base:o,title:a,body:c},e):le.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:i,target_branch:o,title:a,description:c},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${n}. git_open_pr supports github.com and gitlab.com.`})}catch(r){return JSON.stringify({error:r.message})}},tools:[...ee.tools||[],{name:"git_open_pr",description:"Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. The provider is auto-detected from repoUrl. Returns the REAL provider-returned url (pr_url = GitHub html_url / GitLab web_url) \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR is opened against (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},head:{type:"string",description:"Source branch to merge FROM (must already be pushed). GitLab alias: source_branch."},base:{type:"string",description:"Target branch to merge INTO (default: the repo/project default branch). GitLab alias: target_branch."},title:{type:"string",description:"PR/MR title"},body:{type:"string",description:"PR/MR description (markdown)"}},required:["repoUrl","head","title"]}},{name:"git_merge_pr",description:"Merge a pull request (GitHub) or accept a merge request (GitLab) by number. The provider is auto-detected from repoUrl. Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider \u2014 never fabricate it. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR belongs to (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},number:{type:"number",description:"The PR (GitHub) / MR (GitLab) number to merge. GitLab alias: iid."},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (GitHub only; default: squash). Ignored for GitLab."}},required:["repoUrl","number"]}}]};import{execFileSync as es}from"child_process";import{existsSync as St,mkdirSync as ts}from"fs";import{join as z,basename as Ca}from"path";import{randomBytes as Pa}from"crypto";import{pathToFileURL as Oe}from"url";import{createRequire as rs}from"module";var bt=".zibby/memory",ss="dolt",ns={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},kt="mem0",gt=new Map,ze=new Map,Ye=!1,Ua=rs(import.meta.url),Qe=()=>Pa(8).toString("hex"),oe=()=>new Date().toISOString(),qa=[`CREATE TABLE IF NOT EXISTS chat_memory (
596
608
  id VARCHAR(64) PRIMARY KEY,
597
609
  memory_key VARCHAR(160),
598
610
  category VARCHAR(32) NOT NULL,
@@ -623,10 +635,10 @@ To MERGE an open PR/MR, use the provider-agnostic tool:
623
635
  tasks_failed INT DEFAULT 0,
624
636
  key_facts TEXT,
625
637
  created_at VARCHAR(32) NOT NULL
626
- )`],Pr=new Set;function U(s,t){return Jr(Kr,t,{...Gr,cwd:s})}function ee(s,t){try{let e=U(s,["sql","-q",t,"-r","json"]);return JSON.parse(e.trim()).rows||[]}catch{return[]}}function q(s,t){U(s,["sql","-q",t])}function Be(s){if(Pr.has(s))return!0;if(!ft(z(s,".dolt"))){if(!pa())return!1;Mr(s,{recursive:!0}),U(s,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let t=`${ua.join(`;
627
- `)};`;q(s,t);try{q(s,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{q(s,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return Pr.add(s),!0}function pa(){try{return Jr(Kr,["version"],{...Gr,timeout:5e3}),!0}catch{return!1}}function S(s){return s==null?"NULL":`'${String(s).replace(/'/g,"''")}'`}function mt(s){return String(s||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function ue(s){return s==="long"?3:s==="mid"?2:s==="short"?1:0}function ht(s,t){let e=["short","mid","long"].includes(s)?s:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(t||"").toLowerCase())&&e==="short"?"mid":e}function Fr(s){let t=new Map;for(let e of s||[]){let r=mt(e.content),i=e.memory_key?`key:${e.memory_key}`:r?`norm:${r}`:"";if(!i)continue;let n=t.get(i);if(!n){t.set(i,e);continue}let o=ue(n.tier),c=ue(e.tier);if(c>o){t.set(i,e);continue}c===o&&Number(e.relevance||0)>Number(n.relevance||0)&&t.set(i,e)}return[...t.values()]}function Ge(s,t){let e=String(s??"");return e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}\u2026`}function we(s,t){let e={recentSessions:Array.isArray(s?.recentSessions)?s.recentSessions:[],topMemories:Array.isArray(s?.topMemories)?s.topMemories:[],taskStats:Array.isArray(s?.taskStats)?s.taskStats:[],ticketFilter:s?.ticketFilter||null,backend:t||String(s?.backend||pt),error:s?.error||null};return e.backend==="mem0"?{...e,recentSessions:[],taskStats:[]}:e}function Ur(s){let t=[];if(s.recentSessions?.length>0){t.push("Recent sessions:");for(let e of s.recentSessions.slice(0,3))e?.summary?.trim()&&t.push(`- ${Ge(e.summary,150)}${e.tickets?` [${e.tickets}]`:""}`)}if(s.topMemories?.length>0){t.push("Known facts:");for(let e of s.topMemories.slice(0,10)){let r=e.tier==="long"?"\u2605":"\xB7";t.push(`${r} [${e.category}] ${Ge(e.content,120)}`)}}return t.length===0?"":`## Memory Context
638
+ )`],Zr=new Set;function U(s,t){return es(ss,t,{...ns,cwd:s})}function te(s,t){try{let e=U(s,["sql","-q",t,"-r","json"]);return JSON.parse(e.trim()).rows||[]}catch{return[]}}function q(s,t){U(s,["sql","-q",t])}function We(s){if(Zr.has(s))return!0;if(!St(z(s,".dolt"))){if(!Da())return!1;ts(s,{recursive:!0}),U(s,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let t=`${qa.join(`;
639
+ `)};`;q(s,t);try{q(s,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{q(s,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return Zr.add(s),!0}function Da(){try{return es(ss,["version"],{...ns,timeout:5e3}),!0}catch{return!1}}function S(s){return s==null?"NULL":`'${String(s).replace(/'/g,"''")}'`}function wt(s){return String(s||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function fe(s){return s==="long"?3:s==="mid"?2:s==="short"?1:0}function It(s,t){let e=["short","mid","long"].includes(s)?s:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(t||"").toLowerCase())&&e==="short"?"mid":e}function is(s){let t=new Map;for(let e of s||[]){let r=wt(e.content),n=e.memory_key?`key:${e.memory_key}`:r?`norm:${r}`:"";if(!n)continue;let i=t.get(n);if(!i){t.set(n,e);continue}let o=fe(i.tier),a=fe(e.tier);if(a>o){t.set(n,e);continue}a===o&&Number(e.relevance||0)>Number(i.relevance||0)&&t.set(n,e)}return[...t.values()]}function Ve(s,t){let e=String(s??"");return e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}\u2026`}function Ne(s,t){let e={recentSessions:Array.isArray(s?.recentSessions)?s.recentSessions:[],topMemories:Array.isArray(s?.topMemories)?s.topMemories:[],taskStats:Array.isArray(s?.taskStats)?s.taskStats:[],ticketFilter:s?.ticketFilter||null,backend:t||String(s?.backend||kt),error:s?.error||null};return e.backend==="mem0"?{...e,recentSessions:[],taskStats:[]}:e}function Vr(s){let t=[];if(s.recentSessions?.length>0){t.push("Recent sessions:");for(let e of s.recentSessions.slice(0,3))e?.summary?.trim()&&t.push(`- ${Ve(e.summary,150)}${e.tickets?` [${e.tickets}]`:""}`)}if(s.topMemories?.length>0){t.push("Known facts:");for(let e of s.topMemories.slice(0,10)){let r=e.tier==="long"?"\u2605":"\xB7";t.push(`${r} [${e.category}] ${Ve(e.content,120)}`)}}return t.length===0?"":`## Memory Context
628
640
  ${t.join(`
629
- `)}`}function Ke(s){return{backend:s.backend,recentSessions:s.recentSessions.slice(0,3).map(t=>({summary:Ge(String(t?.summary||""),160),tickets:t?.tickets||null,created_at:t?.created_at||null})),topMemories:s.topMemories.slice(0,8).map(t=>({category:t?.category||null,tier:t?.tier||null,content:Ge(String(t?.content||""),140),source:t?.source||null})),taskStats:s.taskStats,error:s.error||null}}async function ma(s,t){let e=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(e==="mem0"||e==="dolt")return e;let r=String(t?.options?.memoryBackend||t?.options?.config?.memory?.backend||"").trim().toLowerCase();if(r==="mem0"||r==="dolt")return r;if(Je.has(s))return Je.get(s);try{let i=z(s,".zibby.config.mjs");if(ft(i)){let n=await import(ke(i).href),o=String(n?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return Je.set(s,o),o}}catch{}return Je.set(s,pt),pt}function Hr(s){let t=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return t||`workspace:${ca(s||process.cwd())}`}var fa="mem0";function zr(s){let t=z(s,ut,fa);return{dir:t,vectorDbPath:z(t,"vectors.db"),historyDbPath:z(t,"history.db")}}function ha(s){let t=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!t)return null;let e=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),r=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),i=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),n=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:c}=zr(s||process.cwd());return{llm:{provider:"openai",config:{model:r,baseURL:t,...e?{apiKey:e}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:n,baseURL:t,...e?{apiKey:e}:{}}},vectorStore:{provider:"memory",config:{dimension:n,dbPath:o}},historyDbPath:c}}async function Yr(s){let t=s||process.cwd();if(lt.has(t))return lt.get(t);let e;try{let c=Br(ke(z(t,"package.json")).href).resolve("mem0ai/oss");e=await import(ke(c).href)}catch{try{let o=da.resolve("mem0ai/oss");e=await import(ke(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${t}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let r=e?.Memory;if(!r)throw new Error("mem0ai/oss does not export Memory");let i=ha(t);if(i)try{Mr(zr(t).dir,{recursive:!0})}catch{}let n=i?new r(i):new r;return lt.set(t,n),n}function qr(s,t="mid"){return(Array.isArray(s)?s:Array.isArray(s?.results)?s.results:[]).map(r=>({id:r?.id||Fe(),memory_key:r?.metadata?.memoryKey||r?.metadata?.memory_key||null,category:r?.metadata?.category||"fact",content:r?.memory||r?.content||"",source:r?.metadata?.source||"mem0",ticket_key:r?.metadata?.ticketKey||r?.metadata?.ticket_key||null,tier:ht(r?.metadata?.tier||t,r?.metadata?.category||"fact"),relevance:Number(r?.score??r?.metadata?.relevance??.8),created_at:r?.created_at||r?.metadata?.created_at||ne()})).filter(r=>String(r.content||"").trim().length>0)}var pe={id:"dolt",store:(s,t)=>Zr(s,t),recall:(s,t)=>ka(s,t),brief:(s,t)=>Sa(s,t),endSession:(s,t)=>Qr(s,t),logTask:(s,t)=>Xr(s,t),taskHistory:(s,t)=>es(s,t)},ya={id:"mem0",store:(s,t,e)=>wa(s,t,e),recall:(s,t,e)=>Vr(s,t,e),brief:(s,t,e)=>va(s,t,e),endSession:(s,t)=>Qr(s,t),logTask:(s,t)=>Xr(s,t),taskHistory:(s,t)=>es(s,t)},ga={dolt:pe,mem0:ya};async function Dr(s,t){let e=await ma(s,t);return ga[e]||pe}var Wr={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
641
+ `)}`}function Ze(s){return{backend:s.backend,recentSessions:s.recentSessions.slice(0,3).map(t=>({summary:Ve(String(t?.summary||""),160),tickets:t?.tickets||null,created_at:t?.created_at||null})),topMemories:s.topMemories.slice(0,8).map(t=>({category:t?.category||null,tier:t?.tier||null,content:Ve(String(t?.content||""),140),source:t?.source||null})),taskStats:s.taskStats,error:s.error||null}}async function Ja(s,t){let e=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(e==="mem0"||e==="dolt")return e;let r=String(t?.options?.memoryBackend||t?.options?.config?.memory?.backend||"").trim().toLowerCase();if(r==="mem0"||r==="dolt")return r;if(ze.has(s))return ze.get(s);try{let n=z(s,".zibby.config.mjs");if(St(n)){let i=await import(Oe(n).href),o=String(i?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return ze.set(s,o),o}}catch{}return ze.set(s,kt),kt}function os(s){let t=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return t||`workspace:${Ca(s||process.cwd())}`}var Ma="mem0";function as(s){let t=z(s,bt,Ma);return{dir:t,vectorDbPath:z(t,"vectors.db"),historyDbPath:z(t,"history.db")}}function Ba(s){let t=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!t)return null;let e=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),r=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),n=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),i=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=as(s||process.cwd());return{llm:{provider:"openai",config:{model:r,baseURL:t,...e?{apiKey:e}:{}}},embedder:{provider:"openai",config:{model:n,embeddingDims:i,baseURL:t,...e?{apiKey:e}:{}}},vectorStore:{provider:"memory",config:{dimension:i,dbPath:o}},historyDbPath:a}}async function cs(s){let t=s||process.cwd();if(gt.has(t))return gt.get(t);let e;try{let a=rs(Oe(z(t,"package.json")).href).resolve("mem0ai/oss");e=await import(Oe(a).href)}catch{try{let o=Ua.resolve("mem0ai/oss");e=await import(Oe(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${t}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let r=e?.Memory;if(!r)throw new Error("mem0ai/oss does not export Memory");let n=Ba(t);if(n)try{ts(as(t).dir,{recursive:!0})}catch{}let i=n?new r(n):new r;return gt.set(t,i),i}function Qr(s,t="mid"){return(Array.isArray(s)?s:Array.isArray(s?.results)?s.results:[]).map(r=>({id:r?.id||Qe(),memory_key:r?.metadata?.memoryKey||r?.metadata?.memory_key||null,category:r?.metadata?.category||"fact",content:r?.memory||r?.content||"",source:r?.metadata?.source||"mem0",ticket_key:r?.metadata?.ticketKey||r?.metadata?.ticket_key||null,tier:It(r?.metadata?.tier||t,r?.metadata?.category||"fact"),relevance:Number(r?.score??r?.metadata?.relevance??.8),created_at:r?.created_at||r?.metadata?.created_at||oe()})).filter(r=>String(r.content||"").trim().length>0)}var he={id:"dolt",store:(s,t)=>ds(s,t),recall:(s,t)=>Ya(s,t),brief:(s,t)=>Wa(s,t),endSession:(s,t)=>ps(s,t),logTask:(s,t)=>ms(s,t),taskHistory:(s,t)=>fs(s,t)},Ka={id:"mem0",store:(s,t,e)=>za(s,t,e),recall:(s,t,e)=>us(s,t,e),brief:(s,t,e)=>Za(s,t,e),endSession:(s,t)=>ps(s,t),logTask:(s,t)=>ms(s,t),taskHistory:(s,t)=>fs(s,t)},Ga={dolt:he,mem0:Ka};async function Xr(s,t){let e=await Ja(s,t);return Ga[e]||he}var ls={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
630
642
  You have persistent memory across sessions. Use it to avoid losing context:
631
643
  - **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
632
644
  - **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
@@ -642,40 +654,40 @@ You have persistent memory across sessions. Use it to avoid losing context:
642
654
  - When the user's request is complete: call memory_end_session
643
655
 
644
656
  ### Categories for memory_store
645
- fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(s,t={}){let e=s?.options?.workspace||process.cwd(),r=z(e,ut),i=await Dr(e,s),n=i.id;if(n==="dolt"&&!Be(r)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:n,brief:we({backend:n,error:o},n),promptContext:"",debugPreview:Ke(we({backend:n,error:o},n)),error:o}}try{let o=await i.brief(t,r,e),c=JSON.parse(o||"{}"),a=we({...c,backend:n},n);return{backend:n,brief:a,promptContext:Ur(a),debugPreview:Ke(a),error:a.error||null}}catch(o){if(n==="mem0"&&i!==pe&&Be(r)){if(!Me){Me=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
646
- `)}catch{}}try{let d=await pe.brief(t,r,e),l=JSON.parse(d||"{}"),u=we({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:u,promptContext:Ur(u),debugPreview:Ke(u),error:u.error||null,degradedFrom:"mem0"}}catch{}}let c=String(o?.message||o),a=we({backend:n,error:c},n);return{backend:n,brief:a,promptContext:"",debugPreview:Ke(a),error:c}}},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd(),i=z(r,ut),n=await Dr(r,e),o=n.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(s))&&!Be(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let a=d=>{switch(s){case"memory_store":return d.store(t,i,r);case"memory_recall":return d.recall(t,i,r);case"memory_brief":return d.brief(t,i,r);case"memory_end_session":return d.endSession(t,i,r);case"task_log":return d.logTask(t,i,r);case"task_history":return d.taskHistory(t,i,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}};try{return await a(n)}catch(d){if(o==="mem0"&&n!==pe){if(Be(i)){if(!Me){Me=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
647
- `)}catch{}}try{return await a(pe)}catch(l){return JSON.stringify({error:l.message,backend:"dolt",degradedFrom:"mem0"})}}return JSON.stringify({error:`mem0 unavailable (${d.message}); dolt fallback also unavailable`,backend:"mem0"})}return JSON.stringify({error:d.message})}},tools:[{name:"memory_store",description:"Save a fact, decision, or context to persistent memory. Survives across sessions.",input_schema:{type:"object",properties:{memoryKey:{type:"string",description:"Stable semantic identity key (e.g. user.jira.default_board)"},content:{type:"string",description:"The information to remember"},category:{type:"string",enum:["fact","decision","context","insight","preference","credential","url","error","workaround"],description:"Category of memory"},tier:{type:"string",enum:["short","mid","long"],description:"Memory tier: short (session/24h), mid (days/weeks), long (permanent)"},source:{type:"string",description:'Where this info came from (e.g. "jira", "github", "user", "test_run")'},ticketKey:{type:"string",description:"Related ticket key (optional)"},infer:{type:"boolean",description:"true = LLM distills/dedupes facts (costs tokens); false = store raw, embed-only, free",default:!1}},required:["content","category"]}},{name:"memory_recall",description:"Search persistent memory by keyword, category, ticket, or tier. Returns matching facts and context.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search text (matches content)"},category:{type:"string",description:"Filter by category"},ticketKey:{type:"string",description:"Filter by ticket key"},tier:{type:"string",enum:["short","mid","long"],description:"Filter by memory tier"},limit:{type:"number",description:"Max results (default: 20)"}}}},{name:"memory_brief",description:"Get a compact briefing: recent session summaries + top relevant facts. Call at the start of a conversation.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Focus briefing on a specific ticket (optional)"}}}},{name:"memory_end_session",description:"End the current session and save a summary for future recall. Call when a task is complete.",input_schema:{type:"object",properties:{summary:{type:"string",description:"What happened in this session (1-3 sentences)"},tickets:{type:"string",description:"Comma-separated ticket keys covered"},tasksRun:{type:"number",description:"Number of tasks/tests run"},tasksPassed:{type:"number",description:"Number passed"},tasksFailed:{type:"number",description:"Number failed"},keyFacts:{type:"string",description:"Key facts worth remembering from this session (semicolon-separated)"}},required:["summary"]}},{name:"task_log",description:"Record a completed task (test run, analysis, generation) to persistent history.",input_schema:{type:"object",properties:{title:{type:"string",description:"Task description"},type:{type:"string",enum:["test_run","generate","analysis","research","other"],description:"Task type"},status:{type:"string",enum:["passed","failed","cancelled","error"],description:"Outcome"},ticketKey:{type:"string",description:"Related ticket key"},specPath:{type:"string",description:"Spec file path (if test run)"},resultSummary:{type:"string",description:"Brief result description"}},required:["title","type","status"]}},{name:"task_history",description:"Query past tasks by ticket, status, or type. See what was done before.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Filter by ticket key"},type:{type:"string",description:"Filter by task type"},status:{type:"string",description:"Filter by status"},limit:{type:"number",description:"Max results (default: 20)"}}}}]};function Zr(s,t){let{content:e,category:r,source:i,ticketKey:n,tier:o,memoryKey:c}=s;if(!e||!r)return JSON.stringify({error:"content and category are required"});let a=mt(e);if(!a)return JSON.stringify({error:"content is empty after normalization"});let d=ht(o,r),l=d==="long"?1:d==="mid"?.8:.5,u=String(c||"").trim().slice(0,160);if(u){let g=ee(t,`SELECT id, tier, relevance
657
+ fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(s,t={}){let e=s?.options?.workspace||process.cwd(),r=z(e,bt),n=await Xr(e,s),i=n.id;if(i==="dolt"&&!We(r)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:i,brief:Ne({backend:i,error:o},i),promptContext:"",debugPreview:Ze(Ne({backend:i,error:o},i)),error:o}}try{let o=await n.brief(t,r,e),a=JSON.parse(o||"{}"),c=Ne({...a,backend:i},i);return{backend:i,brief:c,promptContext:Vr(c),debugPreview:Ze(c),error:c.error||null}}catch(o){if(i==="mem0"&&n!==he&&We(r)){if(!Ye){Ye=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
658
+ `)}catch{}}try{let d=await he.brief(t,r,e),l=JSON.parse(d||"{}"),u=Ne({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:u,promptContext:Vr(u),debugPreview:Ze(u),error:u.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=Ne({backend:i,error:a},i);return{backend:i,brief:c,promptContext:"",debugPreview:Ze(c),error:a}}},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd(),n=z(r,bt),i=await Xr(r,e),o=i.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(s))&&!We(n))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(s){case"memory_store":return d.store(t,n,r);case"memory_recall":return d.recall(t,n,r);case"memory_brief":return d.brief(t,n,r);case"memory_end_session":return d.endSession(t,n,r);case"task_log":return d.logTask(t,n,r);case"task_history":return d.taskHistory(t,n,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}};try{return await c(i)}catch(d){if(o==="mem0"&&i!==he){if(We(n)){if(!Ye){Ye=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
659
+ `)}catch{}}try{return await c(he)}catch(l){return JSON.stringify({error:l.message,backend:"dolt",degradedFrom:"mem0"})}}return JSON.stringify({error:`mem0 unavailable (${d.message}); dolt fallback also unavailable`,backend:"mem0"})}return JSON.stringify({error:d.message})}},tools:[{name:"memory_store",description:"Save a fact, decision, or context to persistent memory. Survives across sessions.",input_schema:{type:"object",properties:{memoryKey:{type:"string",description:"Stable semantic identity key (e.g. user.jira.default_board)"},content:{type:"string",description:"The information to remember"},category:{type:"string",enum:["fact","decision","context","insight","preference","credential","url","error","workaround"],description:"Category of memory"},tier:{type:"string",enum:["short","mid","long"],description:"Memory tier: short (session/24h), mid (days/weeks), long (permanent)"},source:{type:"string",description:'Where this info came from (e.g. "jira", "github", "user", "test_run")'},ticketKey:{type:"string",description:"Related ticket key (optional)"},infer:{type:"boolean",description:"true = LLM distills/dedupes facts (costs tokens); false = store raw, embed-only, free",default:!1}},required:["content","category"]}},{name:"memory_recall",description:"Search persistent memory by keyword, category, ticket, or tier. Returns matching facts and context.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search text (matches content)"},category:{type:"string",description:"Filter by category"},ticketKey:{type:"string",description:"Filter by ticket key"},tier:{type:"string",enum:["short","mid","long"],description:"Filter by memory tier"},limit:{type:"number",description:"Max results (default: 20)"}}}},{name:"memory_brief",description:"Get a compact briefing: recent session summaries + top relevant facts. Call at the start of a conversation.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Focus briefing on a specific ticket (optional)"}}}},{name:"memory_end_session",description:"End the current session and save a summary for future recall. Call when a task is complete.",input_schema:{type:"object",properties:{summary:{type:"string",description:"What happened in this session (1-3 sentences)"},tickets:{type:"string",description:"Comma-separated ticket keys covered"},tasksRun:{type:"number",description:"Number of tasks/tests run"},tasksPassed:{type:"number",description:"Number passed"},tasksFailed:{type:"number",description:"Number failed"},keyFacts:{type:"string",description:"Key facts worth remembering from this session (semicolon-separated)"}},required:["summary"]}},{name:"task_log",description:"Record a completed task (test run, analysis, generation) to persistent history.",input_schema:{type:"object",properties:{title:{type:"string",description:"Task description"},type:{type:"string",enum:["test_run","generate","analysis","research","other"],description:"Task type"},status:{type:"string",enum:["passed","failed","cancelled","error"],description:"Outcome"},ticketKey:{type:"string",description:"Related ticket key"},specPath:{type:"string",description:"Spec file path (if test run)"},resultSummary:{type:"string",description:"Brief result description"}},required:["title","type","status"]}},{name:"task_history",description:"Query past tasks by ticket, status, or type. See what was done before.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Filter by ticket key"},type:{type:"string",description:"Filter by task type"},status:{type:"string",description:"Filter by status"},limit:{type:"number",description:"Max results (default: 20)"}}}}]};function ds(s,t){let{content:e,category:r,source:n,ticketKey:i,tier:o,memoryKey:a}=s;if(!e||!r)return JSON.stringify({error:"content and category are required"});let c=wt(e);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=It(o,r),l=d==="long"?1:d==="mid"?.8:.5,u=String(a||"").trim().slice(0,160);if(u){let g=te(t,`SELECT id, tier, relevance
648
660
  FROM chat_memory
649
661
  WHERE memory_key = ${S(u)}
650
662
  ORDER BY created_at DESC
651
- LIMIT 1`)[0];if(g){let b=String(g.tier||"mid"),y=Number(g.relevance||0),k=ue(d)>ue(b)?d:b,A=Math.max(l,y);q(t,`UPDATE chat_memory
663
+ LIMIT 1`)[0];if(g){let b=String(g.tier||"mid"),y=Number(g.relevance||0),w=fe(d)>fe(b)?d:b,A=Math.max(l,y);q(t,`UPDATE chat_memory
652
664
  SET content = ${S(e)},
653
665
  category = ${S(r)},
654
- source = ${S(i)},
655
- ticket_key = ${S(n)},
656
- tier = ${S(k)},
666
+ source = ${S(n)},
667
+ ticket_key = ${S(i)},
668
+ tier = ${S(w)},
657
669
  relevance = ${A},
658
- created_at = ${S(ne())}
659
- WHERE id = ${S(g.id)}`);try{U(t,["add","."]),U(t,["commit","-m",`memory upsert: ${r} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:g.id,category:r,tier:k,memoryKey:u,upserted:!0})}}let m=ee(t,`SELECT id, content, tier, relevance
670
+ created_at = ${S(oe())}
671
+ WHERE id = ${S(g.id)}`);try{U(t,["add","."]),U(t,["commit","-m",`memory upsert: ${r} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:g.id,category:r,tier:w,memoryKey:u,upserted:!0})}}let m=te(t,`SELECT id, content, tier, relevance
660
672
  FROM chat_memory
661
673
  WHERE category = ${S(r)}
662
674
  ORDER BY created_at DESC
663
- LIMIT 200`).find(_=>mt(_.content)===a);if(m){let _=String(m.tier||"mid"),g=Number(m.relevance||0),b=ue(d)>ue(_),y=l>g;if(b||y){q(t,`UPDATE chat_memory
675
+ LIMIT 200`).find(_=>wt(_.content)===c);if(m){let _=String(m.tier||"mid"),g=Number(m.relevance||0),b=fe(d)>fe(_),y=l>g;if(b||y){q(t,`UPDATE chat_memory
664
676
  SET tier = ${S(b?d:_)},
665
677
  relevance = ${Math.max(l,g)}
666
- WHERE id = ${S(m.id)}`);try{U(t,["add","."]),U(t,["commit","-m",`memory promote: ${r} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:r,tier:b?d:_,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:r,tier:_,deduped:!0,promoted:!1})}let f=Fe(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;q(t,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
667
- VALUES (${S(f)}, ${S(u||null)}, ${S(r)}, ${S(e)}, ${S(i)}, ${S(n)}, ${S(h)}, ${S(d)}, ${l}, ${S(ne())})`);try{U(t,["add","."]),U(t,["commit","-m",`memory: ${r} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:r,tier:d,memoryKey:u||null,stored:e.slice(0,100)})}function _a(s){let t=String(s||"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var dt=new Map;async function ba(s,t){if(typeof s=="boolean")return s;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return _a(process.env.ZIBBY_MEM0_INFER);let e=t||process.cwd();if(dt.has(e))return dt.get(e);let r=!1;try{let i=z(e,".zibby.config.mjs");ft(i)&&(r=(await import(ke(i).href))?.default?.memory?.infer===!0)}catch{}return dt.set(e,r),r}async function wa(s,t,e){let{content:r,category:i,source:n,ticketKey:o,tier:c,memoryKey:a,infer:d}=s;if(!r||!i)return JSON.stringify({error:"content and category are required"});try{let l=await Yr(e),u=Hr(e),p=ht(c,i),m=await ba(d,e);return await l.add([{role:"user",content:String(r)}],{userId:u,infer:m,metadata:{memoryKey:a||null,category:i,tier:p,source:n||"zibby-chat",ticketKey:o||null,created_at:ne()}}),JSON.stringify({ok:!0,backend:"mem0",userId:u,category:i,tier:p,infer:m,memoryKey:a||null,stored:String(r).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function ka(s,t){let{query:e,category:r,ticketKey:i,tier:n,limit:o=20}=s,c=[];e&&c.push(`content LIKE ${S(`%${e}%`)}`),r&&c.push(`category = ${S(r)}`),i&&c.push(`ticket_key = ${S(i)}`),n&&c.push(`tier = ${S(n)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
668
- FROM chat_memory ${c.length>0?`WHERE ${c.join(" AND ")}`:""}
678
+ WHERE id = ${S(m.id)}`);try{U(t,["add","."]),U(t,["commit","-m",`memory promote: ${r} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:r,tier:b?d:_,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:r,tier:_,deduped:!0,promoted:!1})}let f=Qe(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;q(t,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
679
+ VALUES (${S(f)}, ${S(u||null)}, ${S(r)}, ${S(e)}, ${S(n)}, ${S(i)}, ${S(h)}, ${S(d)}, ${l}, ${S(oe())})`);try{U(t,["add","."]),U(t,["commit","-m",`memory: ${r} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:r,tier:d,memoryKey:u||null,stored:e.slice(0,100)})}function Fa(s){let t=String(s||"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var _t=new Map;async function Ha(s,t){if(typeof s=="boolean")return s;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return Fa(process.env.ZIBBY_MEM0_INFER);let e=t||process.cwd();if(_t.has(e))return _t.get(e);let r=!1;try{let n=z(e,".zibby.config.mjs");St(n)&&(r=(await import(Oe(n).href))?.default?.memory?.infer===!0)}catch{}return _t.set(e,r),r}async function za(s,t,e){let{content:r,category:n,source:i,ticketKey:o,tier:a,memoryKey:c,infer:d}=s;if(!r||!n)return JSON.stringify({error:"content and category are required"});try{let l=await cs(e),u=os(e),p=It(a,n),m=await Ha(d,e);return await l.add([{role:"user",content:String(r)}],{userId:u,infer:m,metadata:{memoryKey:c||null,category:n,tier:p,source:i||"zibby-chat",ticketKey:o||null,created_at:oe()}}),JSON.stringify({ok:!0,backend:"mem0",userId:u,category:n,tier:p,infer:m,memoryKey:c||null,stored:String(r).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function Ya(s,t){let{query:e,category:r,ticketKey:n,tier:i,limit:o=20}=s,a=[];e&&a.push(`content LIKE ${S(`%${e}%`)}`),r&&a.push(`category = ${S(r)}`),n&&a.push(`ticket_key = ${S(n)}`),i&&a.push(`tier = ${S(i)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
680
+ FROM chat_memory ${a.length>0?`WHERE ${a.join(" AND ")}`:""}
669
681
  ORDER BY relevance DESC, created_at DESC
670
- LIMIT ${o}`,l=ee(t,d);return JSON.stringify({total:l.length,memories:l})}async function Vr(s,t,e){let{query:r,category:i,ticketKey:n,tier:o,limit:c=20}=s;try{let a=await Yr(e),d=Hr(e),l=[];if(r&&String(r).trim()){let u=await a.search(String(r),{filters:{user_id:d},topK:c});l=qr(u)}else{let u=await a.getAll({filters:{user_id:d},topK:Math.max(c,50)});l=qr(u)}return i&&(l=l.filter(u=>u.category===i)),n&&(l=l.filter(u=>u.ticket_key===n)),o&&(l=l.filter(u=>u.tier===o)),l=l.slice(0,c),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(a){throw new Error(`mem0 recall failed: ${a.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:a})}}function Sa(s,t){let{ticketKey:e}=s;Na(t);let i=ee(t,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
671
- FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),n=e?`AND ticket_key = ${S(e)}`:"",o=ee(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
672
- WHERE tier = 'long' ${n} ORDER BY relevance DESC, created_at DESC LIMIT 10`),c=ee(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
673
- WHERE tier = 'mid' ${n} ORDER BY relevance DESC, created_at DESC LIMIT 8`),d=ee(t,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
674
- GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=Fr([...o,...c]);return JSON.stringify({recentSessions:i,topMemories:l,taskStats:d,ticketFilter:e||null})}async function va(s,t,e){let{ticketKey:r}=s,i=await Vr({limit:80},t,e),n=JSON.parse(i||"{}"),o=Array.isArray(n.memories)?n.memories:[];r&&(o=o.filter(p=>p.ticket_key===r));let c=p=>{let m=Date.parse(String(p?.created_at||""))||0;return Number(p?.relevance||0)*1e12+m},a=(p,m)=>c(m)-c(p),d=o.filter(p=>p.tier==="long").sort(a).slice(0,10),l=o.filter(p=>p.tier==="mid").sort(a).slice(0,8),u=Fr([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:u,taskStats:[],ticketFilter:r||null,backend:"mem0"})}function Qr(s,t){let{summary:e,tickets:r,tasksRun:i=0,tasksPassed:n=0,tasksFailed:o=0,keyFacts:c}=s;if(!e)return JSON.stringify({error:"summary is required"});let a=process.env.ZIBBY_CHAT_SESSION_ID||`session_${Fe()}`;if(q(t,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
675
- VALUES (${S(a)}, ${S(e)}, ${S(r)}, ${i}, ${n}, ${o}, ${S(c)}, ${S(ne())})`),c)for(let d of c.split(";").map(l=>l.trim()).filter(Boolean))Zr({content:d,category:"fact",source:"session_summary",tier:"mid"},t);Ia(t);try{U(t,["add","."]),U(t,["commit","-m",`session end: ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:a,summary:e.slice(0,200)})}function Xr(s,t){let{title:e,type:r,status:i,ticketKey:n,specPath:o,resultSummary:c}=s;if(!e||!r||!i)return JSON.stringify({error:"title, type, and status are required"});let a=Fe(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;q(t,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
676
- VALUES (${S(a)}, ${S(n)}, ${S(r)}, ${S(e)}, ${S(i)}, ${S(o)}, ${S(d)}, ${S(c)}, ${S(ne())}, ${S(ne())})`);try{U(t,["add","."]),U(t,["commit","-m",`task: ${i} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:a,title:e,type:r,status:i})}function es(s,t){let{ticketKey:e,type:r,status:i,limit:n=20}=s,o=[];e&&o.push(`ticket_key = ${S(e)}`),r&&o.push(`type = ${S(r)}`),i&&o.push(`status = ${S(i)}`);let a=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
682
+ LIMIT ${o}`,l=te(t,d);return JSON.stringify({total:l.length,memories:l})}async function us(s,t,e){let{query:r,category:n,ticketKey:i,tier:o,limit:a=20}=s;try{let c=await cs(e),d=os(e),l=[];if(r&&String(r).trim()){let u=await c.search(String(r),{filters:{user_id:d},topK:a});l=Qr(u)}else{let u=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=Qr(u)}return n&&(l=l.filter(u=>u.category===n)),i&&(l=l.filter(u=>u.ticket_key===i)),o&&(l=l.filter(u=>u.tier===o)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function Wa(s,t){let{ticketKey:e}=s;Qa(t);let n=te(t,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
683
+ FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),i=e?`AND ticket_key = ${S(e)}`:"",o=te(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
684
+ WHERE tier = 'long' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=te(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
685
+ WHERE tier = 'mid' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 8`),d=te(t,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
686
+ GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=is([...o,...a]);return JSON.stringify({recentSessions:n,topMemories:l,taskStats:d,ticketFilter:e||null})}async function Za(s,t,e){let{ticketKey:r}=s,n=await us({limit:80},t,e),i=JSON.parse(n||"{}"),o=Array.isArray(i.memories)?i.memories:[];r&&(o=o.filter(p=>p.ticket_key===r));let a=p=>{let m=Date.parse(String(p?.created_at||""))||0;return Number(p?.relevance||0)*1e12+m},c=(p,m)=>a(m)-a(p),d=o.filter(p=>p.tier==="long").sort(c).slice(0,10),l=o.filter(p=>p.tier==="mid").sort(c).slice(0,8),u=is([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:u,taskStats:[],ticketFilter:r||null,backend:"mem0"})}function ps(s,t){let{summary:e,tickets:r,tasksRun:n=0,tasksPassed:i=0,tasksFailed:o=0,keyFacts:a}=s;if(!e)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${Qe()}`;if(q(t,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
687
+ VALUES (${S(c)}, ${S(e)}, ${S(r)}, ${n}, ${i}, ${o}, ${S(a)}, ${S(oe())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))ds({content:d,category:"fact",source:"session_summary",tier:"mid"},t);Va(t);try{U(t,["add","."]),U(t,["commit","-m",`session end: ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:e.slice(0,200)})}function ms(s,t){let{title:e,type:r,status:n,ticketKey:i,specPath:o,resultSummary:a}=s;if(!e||!r||!n)return JSON.stringify({error:"title, type, and status are required"});let c=Qe(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;q(t,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
688
+ VALUES (${S(c)}, ${S(i)}, ${S(r)}, ${S(e)}, ${S(n)}, ${S(o)}, ${S(d)}, ${S(a)}, ${S(oe())}, ${S(oe())})`);try{U(t,["add","."]),U(t,["commit","-m",`task: ${n} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:e,type:r,status:n})}function fs(s,t){let{ticketKey:e,type:r,status:n,limit:i=20}=s,o=[];e&&o.push(`ticket_key = ${S(e)}`),r&&o.push(`type = ${S(r)}`),n&&o.push(`status = ${S(n)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
677
689
  FROM chat_tasks ${o.length>0?`WHERE ${o.join(" AND ")}`:""}
678
- ORDER BY created_at DESC LIMIT ${n}`,d=ee(t,a);return JSON.stringify({total:d.length,tasks:d})}function Ia(s){try{q(s,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),q(s,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),q(s,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),q(s,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function Na(s){try{let t=new Date(Date.now()-864e5).toISOString();q(s,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(t)}`)}catch{}}import{existsSync as ts,readFileSync as Oa}from"node:fs";import{homedir as Ra}from"node:os";import{join as Ta,dirname as Aa,resolve as Ea}from"node:path";import{fileURLToPath as ja}from"node:url";function La(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Aa(ja(import.meta.url)),t=Ea(s,"..","bin","mcp-skill.mjs");return ts(t)?t:null}function $a(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let s=Ta(Ra(),".zibby","config.json");return ts(s)&&JSON.parse(Oa(s,"utf-8")).sessionToken||null}catch{return null}}function xa(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function Ca(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function yt(s){return`${Ca()}:${s}`}async function gt(s,t){let e=$a();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let r=`${xa()}/credits/review-memory`,i=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:s,...t})});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`KV memory ${s} failed (${i.status}): ${n.slice(0,300)}`)}return i.json()}var rs={id:"kv-memory",serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
690
+ ORDER BY created_at DESC LIMIT ${i}`,d=te(t,c);return JSON.stringify({total:d.length,tasks:d})}function Va(s){try{q(s,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),q(s,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),q(s,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),q(s,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function Qa(s){try{let t=new Date(Date.now()-864e5).toISOString();q(s,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(t)}`)}catch{}}import{existsSync as hs,readFileSync as Xa}from"node:fs";import{homedir as ec}from"node:os";import{join as tc,dirname as rc,resolve as sc}from"node:path";import{fileURLToPath as nc}from"node:url";function ic(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=rc(nc(import.meta.url)),t=sc(s,"..","bin","mcp-skill.mjs");return hs(t)?t:null}function oc(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let s=tc(ec(),".zibby","config.json");return hs(s)&&JSON.parse(Xa(s,"utf-8")).sessionToken||null}catch{return null}}function ac(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function cc(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function vt(s){return`${cc()}:${s}`}async function Nt(s,t){let e=oc();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let r=`${ac()}/credits/review-memory`,n=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:s,...t})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`KV memory ${s} failed (${n.status}): ${i.slice(0,300)}`)}return n.json()}var ys={id:"kv-memory",serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
679
691
  You have a PRIVATE per-agent key-value memory that survives across your
680
692
  stateless runs. It is automatically namespaced to YOU (this agent type) \u2014 other
681
693
  agents cannot see or collide with your entries, and you don't need to prefix
@@ -690,7 +702,7 @@ Tools:
690
702
  Use to record durable facts \u2014 e.g. dedup markers, prior decisions, summaries.
691
703
 
692
704
  Your namespace is added for you automatically; pass plain keys like
693
- "seen#owner/repo#42" or "lastRun".`,resolve(){let s=La();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/kvMemory.js","kvMemorySkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"kv_recall":{let e=typeof t?.key=="string"?t.key.trim():"";if(!e)return JSON.stringify({error:"key is required"});let r=await gt("recall",{scope:yt(e)});return JSON.stringify(r)}case"kv_recall_prefix":{let e=typeof t?.keyPrefix=="string"?t.keyPrefix.trim():"";if(!e)return JSON.stringify({error:"keyPrefix is required"});let r=await gt("recall-prefix",{scopePrefix:yt(e)});return JSON.stringify(r)}case"kv_store":{let e=typeof t?.key=="string"?t.key.trim():"";if(!e)return JSON.stringify({error:"key is required"});if(typeof t?.content!="string"||t.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let r={scope:yt(e),content:t.content};t.metadata!=null&&(r.metadata=t.metadata);let i=await gt("store",r);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"kv_recall",description:'Recall the value you stored under a plain key (exact match). Your per-agent namespace is added automatically \u2014 pass a plain key like "seen#owner/repo#42".',input_schema:{type:"object",properties:{key:{type:"string",description:'Plain storage key (no namespace prefix needed) \u2014 e.g. "seen#owner/repo#42" or "lastRun".'}},required:["key"]}},{name:"kv_recall_prefix",description:'List your entries whose plain key STARTS WITH a prefix (e.g. "seen#"). Your per-agent namespace is added automatically. Capped at 25.',input_schema:{type:"object",properties:{keyPrefix:{type:"string",description:'Plain key prefix to match (no namespace prefix needed) \u2014 e.g. "seen#".'}},required:["keyPrefix"]}},{name:"kv_store",description:"Store (overwrite) a value under a plain key so a later run of yours can recall it. Your per-agent namespace is added automatically.",input_schema:{type:"object",properties:{key:{type:"string",description:"Plain storage key (no namespace prefix needed). Same key you recall by."},content:{type:"string",description:"The value to persist. Free-form markdown/text."},metadata:{type:"object",description:"Optional structured metadata."}},required:["key","content"]}}]};import{existsSync as is,readFileSync as Pa}from"node:fs";import{homedir as Ua}from"node:os";import{join as qa,dirname as Da,resolve as Ja}from"node:path";import{fileURLToPath as Ma}from"node:url";function Ba(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Da(Ma(import.meta.url)),t=Ja(s,"..","bin","mcp-skill.mjs");return is(t)?t:null}function ns(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let s=qa(Ua(),".zibby","config.json");return is(s)&&JSON.parse(Pa(s,"utf-8")).sessionToken||null}catch{return null}}function os(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function ss(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Ka(){let s={};for(let[t,e]of Object.entries(process.env)){let r=/^ZIBBY_STORE__(.+)$/.exec(t);if(!r)continue;let i=typeof e=="string"?e.trim():"";i&&(s[r[1]]=i)}return s}var as={};function _t(s){let t={...Ka(),...as},e=Object.keys(t),r=typeof s=="string"?s.trim():"";return r?Object.prototype.hasOwnProperty.call(t,r)?{storeId:t[r],name:r}:{error:`unknown store '${r}'; available: ${e.join(", ")}`}:e.length===1?{storeId:t[e[0]],name:e[0]}:e.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${e.join(", ")})`}}async function Ga(s){let t=ns();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let e=await fetch(`${os()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`ensure_store failed (${e.status}): ${r.slice(0,300)}`)}return e.json()}async function bt(s,t,e){let r=ns();if(!r)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${os()}/datasets/stores/${encodeURIComponent(s)}/${t}`,n=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Store ${t} failed (${n.status}): ${o.slice(0,300)}`)}return n.json()}var cs={id:"dataset-store",serverName:"dataset_store",allowedTools:["mcp__dataset_store__*"],description:"Dataset store \u2014 a durable, queryable store for structured JSON records; append rows now, run SQL-style aggregations/reports later",promptFragment:`## Dataset Store (durable, queryable structured-record store)
705
+ "seen#owner/repo#42" or "lastRun".`,resolve(){let s=ic();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/kvMemory.js","kvMemorySkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"kv_recall":{let e=typeof t?.key=="string"?t.key.trim():"";if(!e)return JSON.stringify({error:"key is required"});let r=await Nt("recall",{scope:vt(e)});return JSON.stringify(r)}case"kv_recall_prefix":{let e=typeof t?.keyPrefix=="string"?t.keyPrefix.trim():"";if(!e)return JSON.stringify({error:"keyPrefix is required"});let r=await Nt("recall-prefix",{scopePrefix:vt(e)});return JSON.stringify(r)}case"kv_store":{let e=typeof t?.key=="string"?t.key.trim():"";if(!e)return JSON.stringify({error:"key is required"});if(typeof t?.content!="string"||t.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let r={scope:vt(e),content:t.content};t.metadata!=null&&(r.metadata=t.metadata);let n=await Nt("store",r);return JSON.stringify(n)}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"kv_recall",description:'Recall the value you stored under a plain key (exact match). Your per-agent namespace is added automatically \u2014 pass a plain key like "seen#owner/repo#42".',input_schema:{type:"object",properties:{key:{type:"string",description:'Plain storage key (no namespace prefix needed) \u2014 e.g. "seen#owner/repo#42" or "lastRun".'}},required:["key"]}},{name:"kv_recall_prefix",description:'List your entries whose plain key STARTS WITH a prefix (e.g. "seen#"). Your per-agent namespace is added automatically. Capped at 25.',input_schema:{type:"object",properties:{keyPrefix:{type:"string",description:'Plain key prefix to match (no namespace prefix needed) \u2014 e.g. "seen#".'}},required:["keyPrefix"]}},{name:"kv_store",description:"Store (overwrite) a value under a plain key so a later run of yours can recall it. Your per-agent namespace is added automatically.",input_schema:{type:"object",properties:{key:{type:"string",description:"Plain storage key (no namespace prefix needed). Same key you recall by."},content:{type:"string",description:"The value to persist. Free-form markdown/text."},metadata:{type:"object",description:"Optional structured metadata."}},required:["key","content"]}}]};import{existsSync as _s,readFileSync as lc}from"node:fs";import{homedir as dc}from"node:os";import{join as uc,dirname as pc,resolve as mc}from"node:path";import{fileURLToPath as fc}from"node:url";function hc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=pc(fc(import.meta.url)),t=mc(s,"..","bin","mcp-skill.mjs");return _s(t)?t:null}function bs(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let s=uc(dc(),".zibby","config.json");return _s(s)&&JSON.parse(lc(s,"utf-8")).sessionToken||null}catch{return null}}function ks(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function gs(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function yc(){let s={};for(let[t,e]of Object.entries(process.env)){let r=/^ZIBBY_STORE__(.+)$/.exec(t);if(!r)continue;let n=typeof e=="string"?e.trim():"";n&&(s[r[1]]=n)}return s}var ws={};function Ot(s){let t={...yc(),...ws},e=Object.keys(t),r=typeof s=="string"?s.trim():"";return r?Object.prototype.hasOwnProperty.call(t,r)?{storeId:t[r],name:r}:{error:`unknown store '${r}'; available: ${e.join(", ")}`}:e.length===1?{storeId:t[e[0]],name:e[0]}:e.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${e.join(", ")})`}}async function gc(s){let t=bs();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let e=await fetch(`${ks()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`ensure_store failed (${e.status}): ${r.slice(0,300)}`)}return e.json()}async function Rt(s,t,e){let r=bs();if(!r)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let n=`${ks()}/datasets/stores/${encodeURIComponent(s)}/${t}`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Store ${t} failed (${i.status}): ${o.slice(0,300)}`)}return i.json()}var Ss={id:"dataset-store",serverName:"dataset_store",allowedTools:["mcp__dataset_store__*"],description:"Dataset store \u2014 a durable, queryable store for structured JSON records; append rows now, run SQL-style aggregations/reports later",promptFragment:`## Dataset Store (durable, queryable structured-record store)
694
706
  You have one or more durable stores for STRUCTURED records that survive across
695
707
  your stateless runs. Unlike key-value memory (for picking up where you left
696
708
  off), this is for accumulating DATA you want to QUERY and AGGREGATE later \u2014 e.g.
@@ -726,7 +738,7 @@ Tools:
726
738
  - sqlite_query: (sqlite stores) Run a SELECT (optionally with \`params\` for safe
727
739
  binding). Returns { columns, rows }. Read-only \u2014 never changes data.
728
740
  Pick the tool that matches the store's TYPE; using a dataset tool on a sqlite
729
- store (or vice-versa) is rejected.`,resolve(){let s=Ba();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/datasetStore.js","datasetStoreSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(s,t){try{switch(s){case"dataset_append":{if(t?.record==null||typeof t.record!="object"||Array.isArray(t.record))return JSON.stringify({error:"record is required (a JSON object)"});let e=_t(t?.store);if(e.error)return JSON.stringify({error:e.error});let r=typeof t?.agent=="string"&&t.agent.trim()?t.agent.trim():ss(),i={record:t.record,agent:r};typeof t?.description=="string"&&t.description.trim()&&(i.description=t.description.trim());let n=await bt(e.storeId,"append",i);return JSON.stringify({...n,store:e.name,storeId:e.storeId})}case"dataset_query":{let e=_t(t?.store);if(e.error)return JSON.stringify({error:e.error});let r={};for(let n of["select","where","groupBy","orderBy","limit","since","until","agent"])t?.[n]!=null&&(r[n]=t[n]);let i=await bt(e.storeId,"query",r);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}case"ensure_store":{let e=typeof t?.name=="string"?t.name.trim():"";if(!e)return JSON.stringify({error:"name is required"});let r=typeof t?.type=="string"&&t.type.trim()?t.type.trim().toLowerCase():"sqlite",i=typeof t?.description=="string"?t.description.trim():"",n=await Ga({name:e,type:r,description:i,namespace:ss()});return n?.storeId&&(as[e]=n.storeId),JSON.stringify({...n,store:e})}case"sqlite_exec":case"sqlite_query":{let e=_t(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.sql!="string"||!t.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let r={sql:t.sql};Array.isArray(t?.params)&&(r.params=t.params);let i=await bt(e.storeId,"sql",r);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics.'},description:{type:"string",description:"What this store is for (shown in the Storage UI)."}},required:["name"]}},{name:"sqlite_exec",description:"For SQLITE-type stores: run SQL that CHANGES data \u2014 CREATE TABLE (use IF NOT EXISTS), INSERT, UPDATE, DELETE (one or more statements in one call). The store is a real, mutable SQLite database that persists across your stateless runs. Returns { rowsModified, wrote }. Use this to build schema on the fly and to update rows / track changing state (e.g. a queue with a status column).",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:'The SQL to run. May contain multiple statements separated by ";". Prefer CREATE TABLE IF NOT EXISTS for idempotent schema.'},params:{type:"array",description:'Optional positional bind params for a SINGLE parameterized statement (safe binding of values), e.g. sql "UPDATE t SET s=? WHERE id=?" with params ["done", 1].'}},required:["sql"]}},{name:"sqlite_query",description:"For SQLITE-type stores: run a read-only SELECT (optionally with `params` for safe binding) against the store's SQLite database. Returns { columns, rows }. Never changes data. Use to read back rows/state you stored earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:"A single SELECT statement. Use ? placeholders + `params` for any values."},params:{type:"array",description:'Optional positional bind params for the SELECT, e.g. ["linkedin_personal"].'}},required:["sql"]}}]};import{dirname as Fa,resolve as Ha}from"path";import{fileURLToPath as za}from"url";import{existsSync as Ya}from"fs";function Wa(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Fa(za(import.meta.url)),t=Ha(s,"..","bin","mcp-skill.mjs");return Ya(t)?t:null}function Za(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function Va(){return((process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,"")||process.env.ZIBBY_ACCOUNT_API_URL||process.env.ZIBBY_PROD_ACCOUNT_API_URL||(process.env.ZIBBY_ENV==="local"?"http://localhost:3001":"https://api-prod.zibby.app")).replace(/\/+$/,"")}var Qa={name:"trigger_agent",description:"Trigger another Zibby workflow/agent run in THIS project (fire-and-forget). Call it once per run you want to start \u2014 the agent decides which and how many. Omit workflowType to re-run THIS same agent (self-dispatch, e.g. with a different trigger input). Returns the started run's executionId; does NOT wait for it to finish.",input_schema:{type:"object",properties:{workflowType:{type:"string",description:"Which workflow to trigger (its type/slug in this project). Omit to trigger THIS same agent (self-dispatch)."},input:{type:"object",description:"The trigger payload passed to the target workflow (validated against its state schema)."}},required:[]}},ls={id:"trigger-agent",serverName:"trigger",allowedTools:["mcp__trigger__*"],envKeys:[],description:"Trigger another Zibby workflow/agent run in this project (agent-driven, fire-and-forget; cloud + self-hosted).",promptFragment:"## Trigger another agent (agent-driven)\nYou can start another Zibby agent run yourself with the `trigger_agent`\ntool \u2014 and YOU decide when and how many times to call it. Each call starts ONE\nindependent run (fire-and-forget) and returns its executionId; it does NOT wait for\nthat run to finish.\n- To re-run THIS same agent (self-dispatch) \u2014 e.g. to hand an item to another of\n this agent's scenarios \u2014 OMIT `workflowType` and pass the `input` for that run.\n- To trigger a DIFFERENT agent in the project, pass its `workflowType` + `input`.\nCall it once per run you want to start (loop over your items and call it for each).\nIt never throws \u2014 a failure comes back as { ok:false, error }; log it and move on.",resolve(){let s=Wa();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","PROJECT_ID","WORKFLOW_TYPE","PROGRESS_API_URL","ZIBBY_ACCOUNT_API_URL","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_USER_TOKEN"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/triggerAgent.js","triggerAgentSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(s,t={}){if(s!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${s}`});try{let e=process.env.PROJECT_ID,r=Za(),i=typeof t.workflowType=="string"&&t.workflowType.trim()?t.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!e)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!r)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!i)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let n=`${Va()}/projects/${encodeURIComponent(e)}/workflows/${encodeURIComponent(i)}/trigger`,o=new AbortController,c=setTimeout(()=>o.abort(),2e4),a;try{a=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify({input:t.input&&typeof t.input=="object"?t.input:{}}),signal:o.signal})}finally{clearTimeout(c)}let d=await a.text().catch(()=>""),l;try{l=d?JSON.parse(d):{}}catch{l={raw:d}}if(!a.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${a.status})`,detail:l&&(l.error||l.message)||d.slice(0,300)});let u=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:u,note:"run started (fire-and-forget)"})}catch(e){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${e?.message||String(e)}`})}},tools:[Qa]};import{spawnSync as Xa}from"node:child_process";import{existsSync as He,mkdirSync as ds,readdirSync as ec,writeFileSync as tc}from"node:fs";import{createHash as rc}from"node:crypto";import{join as ze}from"node:path";function us(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function ps(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let s=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return s?ze(s,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function sc(){let s=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",t=ze(s,".zibby","repos");try{if(He(t)){let e=ec(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>ze(t,r.name));if(e.length===1)return e[0];if(e.length>1)return t}}catch{}return He(s)?s:null}function ic(s){return rc("sha256").update(s).digest("hex").slice(0,16)}var ms={id:"codebase-memory",serverName:"codebase_memory",allowedTools:["mcp__codebase_memory__*"],description:"Codebase memory \u2014 code-graph + semantic index over the checked-out repo (architecture, graph search, dependency trace, change detection)",promptFragment:`## Codebase Memory (code-graph + semantic index over THIS repo)
741
+ store (or vice-versa) is rejected.`,resolve(){let s=hc();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/datasetStore.js","datasetStoreSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(s,t){try{switch(s){case"dataset_append":{if(t?.record==null||typeof t.record!="object"||Array.isArray(t.record))return JSON.stringify({error:"record is required (a JSON object)"});let e=Ot(t?.store);if(e.error)return JSON.stringify({error:e.error});let r=typeof t?.agent=="string"&&t.agent.trim()?t.agent.trim():gs(),n={record:t.record,agent:r};typeof t?.description=="string"&&t.description.trim()&&(n.description=t.description.trim());let i=await Rt(e.storeId,"append",n);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}case"dataset_query":{let e=Ot(t?.store);if(e.error)return JSON.stringify({error:e.error});let r={};for(let i of["select","where","groupBy","orderBy","limit","since","until","agent"])t?.[i]!=null&&(r[i]=t[i]);let n=await Rt(e.storeId,"query",r);return JSON.stringify({...n,store:e.name,storeId:e.storeId})}case"ensure_store":{let e=typeof t?.name=="string"?t.name.trim():"";if(!e)return JSON.stringify({error:"name is required"});let r=typeof t?.type=="string"&&t.type.trim()?t.type.trim().toLowerCase():"sqlite",n=typeof t?.description=="string"?t.description.trim():"",i=await gc({name:e,type:r,description:n,namespace:gs()});return i?.storeId&&(ws[e]=i.storeId),JSON.stringify({...i,store:e})}case"sqlite_exec":case"sqlite_query":{let e=Ot(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.sql!="string"||!t.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let r={sql:t.sql};Array.isArray(t?.params)&&(r.params=t.params);let n=await Rt(e.storeId,"sql",r);return JSON.stringify({...n,store:e.name,storeId:e.storeId})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics.'},description:{type:"string",description:"What this store is for (shown in the Storage UI)."}},required:["name"]}},{name:"sqlite_exec",description:"For SQLITE-type stores: run SQL that CHANGES data \u2014 CREATE TABLE (use IF NOT EXISTS), INSERT, UPDATE, DELETE (one or more statements in one call). The store is a real, mutable SQLite database that persists across your stateless runs. Returns { rowsModified, wrote }. Use this to build schema on the fly and to update rows / track changing state (e.g. a queue with a status column).",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:'The SQL to run. May contain multiple statements separated by ";". Prefer CREATE TABLE IF NOT EXISTS for idempotent schema.'},params:{type:"array",description:'Optional positional bind params for a SINGLE parameterized statement (safe binding of values), e.g. sql "UPDATE t SET s=? WHERE id=?" with params ["done", 1].'}},required:["sql"]}},{name:"sqlite_query",description:"For SQLITE-type stores: run a read-only SELECT (optionally with `params` for safe binding) against the store's SQLite database. Returns { columns, rows }. Never changes data. Use to read back rows/state you stored earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:"A single SELECT statement. Use ? placeholders + `params` for any values."},params:{type:"array",description:'Optional positional bind params for the SELECT, e.g. ["linkedin_personal"].'}},required:["sql"]}}]};import{dirname as _c,resolve as bc}from"path";import{fileURLToPath as kc}from"url";import{existsSync as wc}from"fs";function Sc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=_c(kc(import.meta.url)),t=bc(s,"..","bin","mcp-skill.mjs");return wc(t)?t:null}function Ic(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function vc(){return((process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,"")||process.env.ZIBBY_ACCOUNT_API_URL||process.env.ZIBBY_PROD_ACCOUNT_API_URL||(process.env.ZIBBY_ENV==="local"?"http://localhost:3001":"https://api-prod.zibby.app")).replace(/\/+$/,"")}var Nc={name:"trigger_agent",description:"Trigger another Zibby workflow/agent run in THIS project (fire-and-forget). Call it once per run you want to start \u2014 the agent decides which and how many. Omit workflowType to re-run THIS same agent (self-dispatch, e.g. with a different trigger input). Returns the started run's executionId; does NOT wait for it to finish.",input_schema:{type:"object",properties:{workflowType:{type:"string",description:"Which workflow to trigger (its type/slug in this project). Omit to trigger THIS same agent (self-dispatch)."},input:{type:"object",description:"The trigger payload passed to the target workflow (validated against its state schema)."}},required:[]}},Is={id:"trigger-agent",serverName:"trigger",allowedTools:["mcp__trigger__*"],envKeys:[],description:"Trigger another Zibby workflow/agent run in this project (agent-driven, fire-and-forget; cloud + self-hosted).",promptFragment:"## Trigger another agent (agent-driven)\nYou can start another Zibby agent run yourself with the `trigger_agent`\ntool \u2014 and YOU decide when and how many times to call it. Each call starts ONE\nindependent run (fire-and-forget) and returns its executionId; it does NOT wait for\nthat run to finish.\n- To re-run THIS same agent (self-dispatch) \u2014 e.g. to hand an item to another of\n this agent's scenarios \u2014 OMIT `workflowType` and pass the `input` for that run.\n- To trigger a DIFFERENT agent in the project, pass its `workflowType` + `input`.\nCall it once per run you want to start (loop over your items and call it for each).\nIt never throws \u2014 a failure comes back as { ok:false, error }; log it and move on.",resolve(){let s=Sc();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","PROJECT_ID","WORKFLOW_TYPE","PROGRESS_API_URL","ZIBBY_ACCOUNT_API_URL","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_USER_TOKEN"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/triggerAgent.js","triggerAgentSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(s,t={}){if(s!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${s}`});try{let e=process.env.PROJECT_ID,r=Ic(),n=typeof t.workflowType=="string"&&t.workflowType.trim()?t.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!e)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!r)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!n)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let i=`${vc()}/projects/${encodeURIComponent(e)}/workflows/${encodeURIComponent(n)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(i,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify({input:t.input&&typeof t.input=="object"?t.input:{}}),signal:o.signal})}finally{clearTimeout(a)}let d=await c.text().catch(()=>""),l;try{l=d?JSON.parse(d):{}}catch{l={raw:d}}if(!c.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${c.status})`,detail:l&&(l.error||l.message)||d.slice(0,300)});let u=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:n,executionId:u,note:"run started (fire-and-forget)"})}catch(e){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${e?.message||String(e)}`})}},tools:[Nc]};import{spawnSync as Oc}from"node:child_process";import{existsSync as Xe,mkdirSync as vs,readdirSync as Rc,writeFileSync as Tc}from"node:fs";import{createHash as Ac}from"node:crypto";import{join as et}from"node:path";function Ns(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function Os(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let s=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return s?et(s,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function Ec(){let s=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",t=et(s,".zibby","repos");try{if(Xe(t)){let e=Rc(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>et(t,r.name));if(e.length===1)return e[0];if(e.length>1)return t}}catch{}return Xe(s)?s:null}function Lc(s){return Ac("sha256").update(s).digest("hex").slice(0,16)}var Rs={id:"codebase-memory",serverName:"codebase_memory",allowedTools:["mcp__codebase_memory__*"],description:"Codebase memory \u2014 code-graph + semantic index over the checked-out repo (architecture, graph search, dependency trace, change detection)",promptFragment:`## Codebase Memory (code-graph + semantic index over THIS repo)
730
742
  The checked-out repository is indexed into a queryable code graph + semantic
731
743
  index. Reach for these instead of blindly grepping when you need structure,
732
744
  relationships, or "where does X live / what depends on Y":
@@ -738,8 +750,8 @@ relationships, or "where does X live / what depends on Y":
738
750
  - get_code_snippet / search_code: pull the exact code for a node / text match.
739
751
  - index_status / list_projects: confirm the index is present before querying.
740
752
  The repo is indexed for you at the start of the run; if a query comes back
741
- empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let s=ps();try{ds(s,{recursive:!0})}catch{}let t={CBM_CACHE_DIR:s};return process.env.WORKSPACE&&(t.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:us(),args:[],env:t,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let s=sc();if(!s)return{};let t=ps();try{ds(t,{recursive:!0})}catch{}let e=ze(t,`.cbm-indexed-${ic(s)}`);if(He(e))return{};let r=us();if(!He(r)&&!process.env.CBM_BIN)return{};let i=Xa(r,["cli","index_repository",JSON.stringify({repo_path:s})],{env:{...process.env,CBM_CACHE_DIR:t},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{tc(e,`${new Date().toISOString()} status=${i.status}
742
- `)}catch{}}catch{}return{}}};import{existsSync as Y,readFileSync as ve,readdirSync as wt,mkdirSync as nc,writeFileSync as me,statSync as ys}from"fs";import{join as R,resolve as kt,relative as gs,dirname as _s}from"path";import{fileURLToPath as oc}from"url";import{createRequire as ac}from"module";var cc=ac(import.meta.url),lc=`## Workflow Builder
753
+ empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let s=Os();try{vs(s,{recursive:!0})}catch{}let t={CBM_CACHE_DIR:s};return process.env.WORKSPACE&&(t.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:Ns(),args:[],env:t,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let s=Ec();if(!s)return{};let t=Os();try{vs(t,{recursive:!0})}catch{}let e=et(t,`.cbm-indexed-${Lc(s)}`);if(Xe(e))return{};let r=Ns();if(!Xe(r)&&!process.env.CBM_BIN)return{};let n=Oc(r,["cli","index_repository",JSON.stringify({repo_path:s})],{env:{...process.env,CBM_CACHE_DIR:t},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{Tc(e,`${new Date().toISOString()} status=${n.status}
754
+ `)}catch{}}catch{}return{}}};import{existsSync as Y,readFileSync as Te,readdirSync as Tt,mkdirSync as xc,writeFileSync as ye,statSync as Es}from"fs";import{join as R,resolve as At,relative as Ls,dirname as xs}from"path";import{fileURLToPath as jc}from"url";import{createRequire as $c}from"module";var Cc=$c(import.meta.url),Pc=`## Workflow Builder
743
755
 
744
756
  You can help users build custom AI workflows using the Zibby workflow framework.
745
757
 
@@ -849,9 +861,9 @@ Call with no arguments to see all available topics.
849
861
  - Workflow names must be kebab-case (e.g., ticket-triage, pr-review).
850
862
  - State flows through: each node's validated output is stored under its name in state (e.g., state.classify_ticket).
851
863
  - Downstream nodes reference upstream outputs in their prompt function (e.g., \\\`\\\${JSON.stringify(state.classify_ticket, null, 2)}\\\`).
852
- - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,bs=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function ws(s){return`${s.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}Workflow`}function Se(s){return`${s.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}Node`}function dc(s){let t=s?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function uc(s){let t=kt(s,".zibby.config.mjs");if(!Y(t))return{};try{return(await import(t)).default||{}}catch{return{}}}function pc(){try{let s=_s(cc.resolve("@zibby/core/package.json")),t=R(s,"templates","browser-test-automation"),e=ve(R(t,"nodes","preflight.mjs"),"utf-8"),r=ve(R(t,"graph.mjs"),"utf-8");return{preflight:e,graph:r}}catch{return null}}var fs=_s(oc(import.meta.url));function ks(){let s=kt(fs,"..","..","..","docsite","docs");if(Y(s))return s;let t=kt(fs,"..","docs");return Y(t)?t:null}function hs(){let s=ks();if(!s)return[];try{let t=(e,r="")=>{let i=[];for(let n of wt(e)){let o=R(e,n);try{if(ys(o).isDirectory())i=i.concat(t(o,`${r}${n}/`));else if(n.endsWith(".md")){let c=`${r}${n.replace(/\.md$/,"")}`;i.push(c)}}catch{}}return i};return t(s)}catch{return[]}}function Ss(s){let t=ks();if(!t)return null;let e=R(t,`${s}.md`);if(!Y(e))return null;try{return ve(e,"utf-8")}catch{return null}}function mc(s){let t=s.nodes.map(o=>{let c=o.inputFields?.length?`Input fields: ${o.inputFields.join(", ")}`:"Input: receives full state",a=o.outputFields?.length?`Output fields: ${o.outputFields.join(", ")}`:"Output: determined by task",d=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${c}. ${a}.${d?` ${d}`:""}`}).join(`
864
+ - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,js=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function $s(s){return`${s.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}Workflow`}function Re(s){return`${s.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}Node`}function Uc(s){let t=s?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function qc(s){let t=At(s,".zibby.config.mjs");if(!Y(t))return{};try{return(await import(t)).default||{}}catch{return{}}}function Dc(){try{let s=xs(Cc.resolve("@zibby/core/package.json")),t=R(s,"templates","browser-test-automation"),e=Te(R(t,"nodes","preflight.mjs"),"utf-8"),r=Te(R(t,"graph.mjs"),"utf-8");return{preflight:e,graph:r}}catch{return null}}var Ts=xs(jc(import.meta.url));function Cs(){let s=At(Ts,"..","..","..","docsite","docs");if(Y(s))return s;let t=At(Ts,"..","docs");return Y(t)?t:null}function As(){let s=Cs();if(!s)return[];try{let t=(e,r="")=>{let n=[];for(let i of Tt(e)){let o=R(e,i);try{if(Es(o).isDirectory())n=n.concat(t(o,`${r}${i}/`));else if(i.endsWith(".md")){let a=`${r}${i.replace(/\.md$/,"")}`;n.push(a)}}catch{}}return n};return t(s)}catch{return[]}}function Ps(s){let t=Cs();if(!t)return null;let e=R(t,`${s}.md`);if(!Y(e))return null;try{return Te(e,"utf-8")}catch{return null}}function Jc(s){let t=s.nodes.map(o=>{let a=o.inputFields?.length?`Input fields: ${o.inputFields.join(", ")}`:"Input: receives full state",c=o.outputFields?.length?`Output fields: ${o.outputFields.join(", ")}`:"Output: determined by task",d=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${a}. ${c}.${d?` ${d}`:""}`}).join(`
853
865
  `),e=s.edges.map(o=>o.condition?`- ${o.from} \u2192 ${o.to} (conditional: ${o.condition})`:`- ${o.from} \u2192 ${o.to}`).join(`
854
- `),r=pc(),i=Ss("custom-workflows"),n="";return r&&(n+=`
866
+ `),r=Dc(),n=Ps("custom-workflows"),i="";return r&&(i+=`
855
867
  ## Real working examples from the Zibby framework
856
868
 
857
869
  ### Example node (preflight.mjs) \u2014 a prompt-only node with Zod schema and onComplete hook:
@@ -865,9 +877,9 @@ ${r.graph}
865
877
  \`\`\`
866
878
 
867
879
  Study these examples carefully. Your generated code must follow the same patterns exactly.
868
- `),i&&(n+=`
880
+ `),n&&(i+=`
869
881
  ## Full framework documentation (Custom Workflows)
870
- ${i}
882
+ ${n}
871
883
  `),`Generate the code for a Zibby workflow called "${s.name}".
872
884
 
873
885
  ## Zibby Workflow Framework Reference
@@ -905,7 +917,7 @@ SKILLS.BROWSER, SKILLS.MEMORY, SKILLS.GITHUB, SKILLS.JIRA, SKILLS.SLACK, SKILLS.
905
917
  - Export name: camelCase + "Node" (e.g., \`classifyTicketNode\` for name \`classify_ticket\`)
906
918
  - Prompt function: template literal referencing \`state.input\` and upstream \`state.<node_name>\`
907
919
  - Prompts must be detailed \u2014 tell the agent exactly what to analyze/produce
908
- ${n}
920
+ ${i}
909
921
  ## Workflow to generate: "${s.name}"
910
922
 
911
923
  ### Description
@@ -928,10 +940,10 @@ Return a JSON object with this exact structure:
928
940
  }
929
941
  }
930
942
 
931
- IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function vs(s,t){let e=await uc(t),r=dc(e);try{let{invokeAgent:i}=await import("@zibby/core"),n=mc(s),o=await i(n,{state:{agentType:r,config:e,cwd:t,workspace:t}},{model:e?.agent?.[r]?.model||"auto",workspace:t,config:e,timeout:12e4}),a=(typeof o=="string"?o:o?.raw||JSON.stringify(o?.structured||o)).match(/\{[\s\S]*\}/);if(!a)throw new Error("Agent did not return valid JSON");return JSON.parse(a[0])}catch(i){return console.warn(`Agent code generation failed (${i.message}), using templates`),fc(s)}}function fc(s){let t={};for(let e of s.nodes){let r=Se(e.name),i=`${e.name.split("_").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}OutputSchema`,n=e.outputFields?.length?e.outputFields.map(a=>` ${a}: z.string().describe('${a}'),`).join(`
943
+ IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function Us(s,t){let e=await qc(t),r=Uc(e);try{let{invokeAgent:n}=await import("@zibby/core"),i=Jc(s),o=await n(i,{state:{agentType:r,config:e,cwd:t,workspace:t}},{model:e?.agent?.[r]?.model||"auto",workspace:t,config:e,timeout:12e4}),c=(typeof o=="string"?o:o?.raw||JSON.stringify(o?.structured||o)).match(/\{[\s\S]*\}/);if(!c)throw new Error("Agent did not return valid JSON");return JSON.parse(c[0])}catch(n){return console.warn(`Agent code generation failed (${n.message}), using templates`),Mc(s)}}function Mc(s){let t={};for(let e of s.nodes){let r=Re(e.name),n=`${e.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,i=e.outputFields?.length?e.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
932
944
  `):` summary: z.string().describe('Summary of the result'),
933
- status: z.enum(['ok', 'warn', 'error']).describe('Overall status'),`,o=s.edges.filter(a=>a.to===e.name&&a.from!=="START").map(a=>`Previous step (${a.from}): \${JSON.stringify(state.${a.from} || {}, null, 2)}`).join(`
934
- `),c=o?`${e.description}
945
+ status: z.enum(['ok', 'warn', 'error']).describe('Overall status'),`,o=s.edges.filter(c=>c.to===e.name&&c.from!=="START").map(c=>`Previous step (${c.from}): \${JSON.stringify(state.${c.from} || {}, null, 2)}`).join(`
946
+ `),a=o?`${e.description}
935
947
 
936
948
  Input:
937
949
  \${JSON.stringify(state.input || {}, null, 2)}
@@ -941,25 +953,25 @@ ${o}`:`${e.description}
941
953
  Input:
942
954
  \${JSON.stringify(state.input || {}, null, 2)}`;t[e.name]={code:`import { z } from '@zibby/core';
943
955
 
944
- const ${i} = z.object({
945
- ${n}
956
+ const ${n} = z.object({
957
+ ${i}
946
958
  });
947
959
 
948
960
  export const ${r} = {
949
961
  name: '${e.name}',
950
- prompt: (state) => \`${c}\`,
951
- outputSchema: ${i},
962
+ prompt: (state) => \`${a}\`,
963
+ outputSchema: ${n},
952
964
  };
953
- `}}return{nodes:t}}function hc(s,t,e,r){let i=t.toLowerCase(),n=ws(i),o=R(s,".zibby","workflows",i),c=R(o,"nodes");nc(c,{recursive:!0});let a=e.nodes.map(g=>g.name);for(let g of e.nodes){let b=r.nodes?.[g.name]?.code;b&&me(R(c,`${g.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let d=a.map(g=>{let b=Se(g),y=g.replace(/_/g,"-");return`export { ${b} } from './${y}.mjs';`});me(R(c,"index.mjs"),`${d.join(`
965
+ `}}return{nodes:t}}function Bc(s,t,e,r){let n=t.toLowerCase(),i=$s(n),o=R(s,".zibby","workflows",n),a=R(o,"nodes");xc(a,{recursive:!0});let c=e.nodes.map(g=>g.name);for(let g of e.nodes){let b=r.nodes?.[g.name]?.code;b&&ye(R(a,`${g.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let d=c.map(g=>{let b=Re(g),y=g.replace(/_/g,"-");return`export { ${b} } from './${y}.mjs';`});ye(R(a,"index.mjs"),`${d.join(`
954
966
  `)}
955
- `,"utf-8");let l=a[0],u=a.map(g=>Se(g)).join(", "),p=a.map(g=>` graph.addNode('${g}', ${Se(g)});`).join(`
967
+ `,"utf-8");let l=c[0],u=c.map(g=>Re(g)).join(", "),p=c.map(g=>` graph.addNode('${g}', ${Re(g)});`).join(`
956
968
  `),m=e.edges.map(g=>g.condition?` graph.addConditionalEdges('${g.from}', (state) => {
957
969
  ${g.condition}
958
970
  });`:` graph.addEdge('${g.from}', '${g.to}');`).join(`
959
971
  `),f=`import { WorkflowAgent, WorkflowGraph } from '@zibby/core';
960
972
  import { ${u} } from './nodes/index.mjs';
961
973
 
962
- export class ${n} extends WorkflowAgent {
974
+ export class ${i} extends WorkflowAgent {
963
975
  buildGraph() {
964
976
  const graph = new WorkflowGraph();
965
977
 
@@ -972,19 +984,19 @@ ${m}
972
984
  }
973
985
 
974
986
  async onComplete(result) {
975
- console.log(\`[${i}] workflow complete \u2014 success: \${result.success !== false}\`);
987
+ console.log(\`[${n}] workflow complete \u2014 success: \${result.success !== false}\`);
976
988
  }
977
989
  }
978
- `;me(R(o,"graph.mjs"),f,"utf-8");let h={name:i,description:e.description||`${n} workflow`,entryClass:n,triggers:{api:!0}};me(R(o,"workflow.json"),`${JSON.stringify(h,null,2)}
979
- `,"utf-8");let _=["graph.mjs","workflow.json","nodes/index.mjs",...a.map(g=>`nodes/${g.replace(/_/g,"-")}.mjs`)];return{workflowDir:gs(s,o),files:_,className:n,slug:i}}async function yc(s){let{name:t,description:e,nodes:r,edges:i}=s;if(!t||!bs.test(t.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${t}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!r||r.length===0)return JSON.stringify({error:"At least one node is required."});let n={name:t.toLowerCase(),description:e||`${ws(t.toLowerCase())} workflow`,nodes:r.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:i||[]};if(n.edges.length===0&&n.nodes.length>0){for(let o=0;o<n.nodes.length-1;o++)n.edges.push({from:n.nodes[o].name,to:n.nodes[o+1].name});n.edges.push({from:n.nodes[n.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:n,message:`Workflow "${n.name}" designed with ${n.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:n.nodes.map(o=>o.name),flow:n.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function gc(s,t){let{name:e,spec:r}=s,i=(e||r?.name||"").toLowerCase();if(!i||!bs.test(i))return JSON.stringify({error:`Invalid workflow name "${i}".`});if(!r||!r.nodes||r.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let n=R(t,".zibby","workflows",i);if(Y(n))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await vs(r,t),c=hc(t,i,r,o);return JSON.stringify({ok:!0,...c,message:`Workflow "${i}" created at ${c.workflowDir}/`,nextSteps:[`Test locally: zibby start ${i}`,`Deploy to cloud: zibby deploy ${i} --project <project-id>`,`Tail logs: zibby logs --workflow ${i} --project <project-id>`]})}async function _c(s,t){let{workflowName:e,nodeName:r,description:i,inputFields:n,outputFields:o}=s,c=(e||"").toLowerCase(),a=(r||"").replace(/-/g,"_"),d=R(t,".zibby","workflows",c);if(!Y(d))return JSON.stringify({error:`Workflow "${c}" not found. Create it first with build_workflow.`});let l={name:c,description:"",nodes:[{name:a,description:i||`Process ${a}`,inputFields:n||[],outputFields:o||[]}],edges:[]},p=(await vs(l,t)).nodes?.[a]?.code;if(!p)return JSON.stringify({error:"Failed to generate node code."});let m=R(d,"nodes"),f=`${a.replace(/_/g,"-")}.mjs`;me(R(m,f),p,"utf-8");let h=R(m,"index.mjs"),_=Se(a),g=`export { ${_} } from './${a.replace(/_/g,"-")}.mjs';
980
- `,b=Y(h)?ve(h,"utf-8"):"";return b.includes(_)||me(h,b+g,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:_,message:`Node "${a}" added. Update graph.mjs to wire it into the graph.`})}async function bc(s,t){let{name:e,projectId:r}=s,i=(e||"").toLowerCase();if(!i)return JSON.stringify({error:"Workflow name is required."});if(!r)return JSON.stringify({error:"projectId is required."});let n=R(t,".zibby","workflows",i);if(!Y(n))return JSON.stringify({error:`Workflow "${i}" not found at .zibby/workflows/${i}/`});try{let{execSync:o}=await import("child_process"),c=o(`node "${R(t,"packages/cli/bin/zibby.js")}" deploy ${i} --project ${r}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:c.trim()})}catch{try{let{execSync:c}=await import("child_process"),a=c(`npx zibby deploy ${i} --project ${r}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:a.trim()})}catch(c){return JSON.stringify({error:`Deploy failed: ${c.message}`})}}}function wc(s){let t=R(s,".zibby","workflows");if(!Y(t))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let r=wt(t).filter(i=>{try{return ys(R(t,i)).isDirectory()}catch{return!1}}).map(i=>{let n=R(t,i,"workflow.json"),o={};try{o=JSON.parse(ve(n,"utf-8"))}catch{}let c=R(t,i,"nodes"),a=0;try{a=wt(c).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:a,path:gs(s,R(t,i))}});return JSON.stringify({workflows:r})}var Is={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:lc,tools:[{name:"design_workflow",description:"Design a workflow spec (nodes, edges, descriptions) for the user to review before building. Call this after understanding requirements.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name in kebab-case (e.g., ticket-triage)"},description:{type:"string",description:"What the workflow does"},nodes:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Node name in snake_case (e.g., classify_ticket)"},description:{type:"string",description:"What this node does \u2014 be specific about input/output"},inputFields:{type:"array",items:{type:"string"},description:"Key fields this node reads from state"},outputFields:{type:"array",items:{type:"string"},description:"Key fields this node produces"}},required:["name","description"]},description:"Workflow nodes (processing steps)"},edges:{type:"array",items:{type:"object",properties:{from:{type:"string",description:"Source node name"},to:{type:"string",description:'Target node name (or "END")'},condition:{type:"string",description:"JS expression for conditional routing (optional)"}},required:["from","to"]},description:"Edges connecting nodes. If omitted, nodes are wired linearly."}},required:["name","description","nodes"]}},{name:"build_workflow",description:"Generate real workflow code on disk from a design spec. Uses the configured AI agent for high-quality code generation.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name (from design_workflow)"},spec:{type:"object",description:"The full spec object returned by design_workflow",properties:{name:{type:"string"},description:{type:"string"},nodes:{type:"array",items:{type:"object"}},edges:{type:"array",items:{type:"object"}}}}},required:["name","spec"]}},{name:"add_node",description:"Add a new node to an existing workflow. Generates the node file and updates the barrel export.",input_schema:{type:"object",properties:{workflowName:{type:"string",description:"Existing workflow name (kebab-case)"},nodeName:{type:"string",description:"New node name (snake_case)"},description:{type:"string",description:"What this node does"},inputFields:{type:"array",items:{type:"string"},description:"Fields read from state"},outputFields:{type:"array",items:{type:"string"},description:"Fields produced"}},required:["workflowName","nodeName","description"]}},{name:"deploy_workflow",description:"Deploy a workflow to Zibby Cloud. Returns the trigger URL.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name to deploy"},projectId:{type:"string",description:"Target project ID"}},required:["name","projectId"]}},{name:"list_workflows",description:"List all local workflows in .zibby/workflows/.",input_schema:{type:"object",properties:{}}},{name:"explore_framework_docs",description:"Read Zibby framework documentation on demand. Call this before building complex workflows or when you need details on advanced patterns (middleware, conditional routing, skills, deployment, CLI commands).",input_schema:{type:"object",properties:{topic:{type:"string",description:'Doc topic to read (e.g., "workflow", "custom-workflows", "cli-reference", "packages/core", "packages/skills", "integrations/jira"). Call with no topic to list all available docs.'}}}}],async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"design_workflow":return await yc(t);case"build_workflow":return await gc(t,r);case"add_node":return await _c(t,r);case"deploy_workflow":return await bc(t,r);case"list_workflows":return wc(r);case"explore_framework_docs":{let i=(t.topic||"").trim();if(!i){let o=hs();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let n=Ss(i);if(!n){let o=hs();return JSON.stringify({error:`Doc "${i}" not found.`,available:o})}return JSON.stringify({topic:i,content:n})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};import{resolveIntegrationToken as kc}from"@zibby/core/backend-client.js";var vt=Object.freeze({id:"openai_billing",requiresIntegration:I.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),It=Object.freeze({id:"anthropic_billing",requiresIntegration:I.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),Nt=Object.freeze({id:"cursor_admin",requiresIntegration:I.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Ns(s){return Math.floor(s/1e3)}function St(s){return new Date(s).toISOString().slice(0,10)}function Os(s){return new Date(s).toISOString()}async function Ie(s){let t=await kc(s);if(!t?.token)throw new Error(`${s} token resolver returned no token`);return t.token}async function Rs({startMs:s,endMs:t,groupBy:e=["project_id","line_item"]}){let r=await Ie("openai_billing"),i=[],n=0,o=e.map(a=>`group_by[]=${encodeURIComponent(a)}`).join("&"),c=null;for(let a=0;a<50;a++){let l=`https://api.openai.com/v1/organization/costs?${[`start_time=${Ns(s)}`,`end_time=${Ns(t)}`,"bucket_width=1d","limit=180",o,c?`page=${encodeURIComponent(c)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{Authorization:`Bearer ${r}`}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`OpenAI costs API ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){n+=1;let f=St((m.start_time||0)*1e3);for(let h of m.results||[])i.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!p.has_more||!p.next_page)break;c=p.next_page}return{ok:!0,items:i,rawBuckets:n}}async function Sc(){let s=await Ie("openai_billing"),e=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${s}`}});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`OpenAI projects API ${e.status}: ${n.slice(0,200)}`)}let r=await e.json(),i=new Map;for(let n of r.data||[])i.set(n.id,n.name);return i}async function Ts({startMs:s,endMs:t,groupBy:e=["workspace_id"]}){let r=await Ie("anthropic_billing"),i=[],n=0,o=e.map(a=>`group_by[]=${encodeURIComponent(a)}`).join("&"),c=null;for(let a=0;a<50;a++){let l=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(Os(s))}`,`ending_at=${encodeURIComponent(Os(t))}`,"bucket=1d","limit=100",o,c?`page=${encodeURIComponent(c)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Anthropic cost_report ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){n+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])i.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!p.has_more||!p.next_page)break;c=p.next_page}return{ok:!0,items:i,rawBuckets:n}}async function vc(){let s=await Ie("anthropic_billing"),e=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":s,"anthropic-version":"2023-06-01"}});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`Anthropic workspaces ${e.status}: ${n.slice(0,200)}`)}let r=await e.json(),i=new Map;for(let n of r.data||[])i.set(n.id,n.name);return i}async function As({startMs:s,endMs:t}){let e=await Ie("cursor_admin"),r=St(s),i=St(t),n=`https://api.cursor.com/teams/daily-usage-data?startDate=${r}&endDate=${i}`,o=await fetch(n,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${l.slice(0,200)}`)}let c=await o.json(),a=[],d=0;for(let l of c.data||[]){d+=1;let u=l.date;for(let p of l.userMetrics||[]){for(let m of p.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);a.push({provider:"cursor",day:u,costUsd:Number(m.totalCents??0)/100,userEmail:p.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!p.modelUsage||p.modelUsage.length===0)&&a.push({provider:"cursor",day:u,costUsd:Number(p.totalCents??0)/100,userEmail:p.email})}}return{ok:!0,items:a,rawBuckets:d}}async function Ic({startMs:s,endMs:t}){let[e,r,i]=await Promise.allSettled([Rs({startMs:s,endMs:t}),Ts({startMs:s,endMs:t}),As({startMs:s,endMs:t})]),n=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=n(e),c=n(r),a=n(i),d=[{provider:"openai",totalUsd:o.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"anthropic",totalUsd:c.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"cursor",totalUsd:a.items.reduce((l,u)=>l+(u.costUsd||0),0)}];return{openai:o,anthropic:c,cursor:a,totals:d}}function Nc(s,t){let e=new Map;for(let r of s){let i=t(r);if(!i)continue;let n=e.get(i)||{key:i,totalUsd:0,count:0};n.totalUsd+=r.costUsd||0,n.count+=1,e.set(i,n)}return[...e.values()].sort((r,i)=>i.totalUsd-r.totalUsd)}function Oc(s){if(!s.length)return{mean:0,stddev:0};let t=s.reduce((r,i)=>r+i,0)/s.length,e=s.reduce((r,i)=>r+(i-t)**2,0)/s.length;return{mean:t,stddev:Math.sqrt(e)}}import{z as w}from"zod";var Ne=["ok","info","warn","critical"],Rc=w.object({primary:w.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:w.object({value:w.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:w.enum(["up","down","flat"]).optional(),severity:w.enum(Ne).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:w.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),Tc=w.object({kind:w.literal("trend"),title:w.string().max(120).optional(),labels:w.array(w.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:w.array(w.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:w.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:w.enum(Ne).optional()}),Ac=w.object({kind:w.literal("table"),title:w.string().max(120).optional(),headers:w.array(w.string().max(40)).min(1).max(8),rows:w.array(w.array(w.union([w.string().max(200),w.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),Ec=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(Ne).default("info").optional(),items:w.array(w.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),jc=w.object({kind:w.literal("breakdown"),title:w.string().max(120).optional(),rows:w.array(w.object({label:w.string().min(1).max(80),value:w.string().min(1).max(80),sub:w.string().max(120).optional(),severity:w.enum(Ne).optional()})).min(1).max(20)}),Lc=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),$c=w.discriminatedUnion("kind",[Tc,Ac,Ec,jc,Lc]),Ot=w.object({title:w.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:w.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:Rc,sections:w.array($c).max(20).default([]).superRefine((s,t)=>{s.forEach((e,r)=>{e.kind==="trend"&&e.labels.length!==e.values.length&&t.addIssue({code:w.ZodIssueCode.custom,path:[r,"values"],message:"labels.length must equal values.length"}),e.kind==="table"&&!e.rows.every(i=>i.length===e.headers.length)&&t.addIssue({code:w.ZodIssueCode.custom,path:[r,"rows"],message:"every row must have headers.length entries"})})}),footer:w.object({viewUrl:w.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:w.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),te=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),Es=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),xc=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function js(s,t,e=12){if(!Number.isFinite(s)||!Number.isFinite(t)||t<=0)return"";let r=Math.max(0,Math.min(1,s/t)),i=Math.round(r*e);return"\u2593".repeat(i)+"\u2591".repeat(e-i)}function Rt(s,t){let e=String(s);return e.length>=t?e:e+" ".repeat(t-e.length)}function Ls(s,t){let e=String(s);return e.length>=t?e:" ".repeat(t-e.length)+e}function $s({headers:s,rows:t}){let e=s.map((o,c)=>{let a=Math.max(String(o).length,...t.map(d=>String(d[c]??"").length));return Math.min(a,32)}),r=o=>o.map((c,a)=>Rt(c,e[a])).join(" "),i=e.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[r(s),i,...t.map(o=>r(o))].join(`
981
- `)+"\n```"}function Cc(s){let t=Ot.parse(s),e=[];e.push({type:"header",text:{type:"plain_text",text:t.title.slice(0,150),emoji:!0}}),t.subtitle&&e.push({type:"context",elements:[{type:"mrkdwn",text:t.subtitle}]});let r=[`*${t.headline.primary}*`];if(t.headline.delta){let n=Es[t.headline.delta.direction]||"",o=t.headline.delta.severity?te[t.headline.delta.severity]:"";r.push(`${n} ${t.headline.delta.value} ${o}`.trim())}let i=r.join(" ");t.headline.summary&&(i+=`
982
- `+t.headline.summary),e.push({type:"section",text:{type:"mrkdwn",text:i}});for(let n of t.sections)switch(e.push({type:"divider"}),n.title&&e.push({type:"section",text:{type:"mrkdwn",text:`*${n.title}*`}}),n.kind){case"trend":{let o=Math.max(...n.values),c=n.labels.map((a,d)=>{let l=n.values[d],u=js(l,o),m=(n.highlight==="last"&&d===n.labels.length-1||n.highlight==="max"&&l===o||n.highlight==="min"&&l===Math.min(...n.values))&&n.severity?` ${te[n.severity]}`:"";return`${Rt(a,10)} ${Ls(l.toLocaleString(),8)} ${u}${m}`});e.push({type:"section",text:{type:"mrkdwn",text:"```\n"+c.join(`
983
- `)+"\n```"}});break}case"table":{e.push({type:"section",text:{type:"mrkdwn",text:$s(n)}});break}case"callouts":{let o=te[n.tone||"info"];e.push({type:"section",text:{type:"mrkdwn",text:n.items.map(c=>`${o} ${c}`).join(`
984
- `)}});break}case"breakdown":{let o=n.rows.map(c=>({type:"mrkdwn",text:`*${c.label}*
985
- ${c.value}${c.sub?`
986
- _${c.sub}_`:""}${c.severity?` ${te[c.severity]}`:""}`}));for(let c=0;c<o.length;c+=10)e.push({type:"section",fields:o.slice(c,c+10)});break}case"paragraph":{e.push({type:"section",text:{type:"mrkdwn",text:n.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let n=[];t.footer.viewUrl&&n.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:t.footer.viewUrl,style:"primary"}),t.footer.rerunUrl&&n.push({type:"button",text:{type:"plain_text",text:"Run again"},url:t.footer.rerunUrl}),e.push({type:"divider"}),e.push({type:"actions",elements:n})}return e}function Pc(s){let t=Ot.parse(s),e=[],r=[`**${t.headline.primary}**`];if(t.headline.delta){let o=Es[t.headline.delta.direction]||"",c=t.headline.delta.severity?te[t.headline.delta.severity]:"";r.push(`${o} ${t.headline.delta.value} ${c}`.trim())}let i=r.join(" ");t.headline.summary&&(i+=`
987
- `+t.headline.summary),e.push({tag:"div",text:{tag:"lark_md",content:i}});for(let o of t.sections)switch(e.push({tag:"hr"}),o.title&&e.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let c=Math.max(...o.values),a=o.labels.map((d,l)=>{let u=o.values[l],p=js(u,c),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&u===c||o.highlight==="min"&&u===Math.min(...o.values))&&o.severity?` ${te[o.severity]}`:"";return`${Rt(d,10)} ${Ls(u.toLocaleString(),8)} ${p}${f}`});e.push({tag:"div",text:{tag:"lark_md",content:"```\n"+a.join(`
988
- `)+"\n```"}});break}case"table":{e.push({tag:"div",text:{tag:"lark_md",content:$s(o)}});break}case"callouts":{let c=te[o.tone||"info"];e.push({tag:"div",text:{tag:"lark_md",content:o.items.map(a=>`${c} ${a}`).join(`
989
- `)}});break}case"breakdown":{let c=o.rows.map(a=>{let d=a.severity?` ${te[a.severity]}`:"",l=a.sub?` *${a.sub}*`:"";return`**${a.label}** ${a.value}${l}${d}`});e.push({tag:"div",text:{tag:"lark_md",content:c.join(`
990
- `)}});break}case"paragraph":{e.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let o=[];t.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:t.footer.viewUrl,type:"primary"}),t.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:t.footer.rerunUrl,type:"default"}),e.push({tag:"hr"}),e.push({tag:"action",actions:o})}let n="blue";return t.headline.delta?.severity&&(n=xc[t.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:t.title.slice(0,200)},subtitle:t.subtitle?{tag:"plain_text",content:t.subtitle.slice(0,200)}:void 0,template:n},elements:e}}var Lu=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),$u=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});import{createRequire as Uc}from"module";import{fileURLToPath as qc}from"url";import{registerHandlers as Dc}from"@zibby/core/function-skill-registry.js";import{registerSkill as Jc}from"@zibby/agent-workflow";var Mc=Uc(import.meta.url);function Bc(){try{return Mc.resolve("@zibby/core/function-bridge.js")}catch{return null}}var Kc=import.meta.url;function Gc(){let s=Error.prepareStackTrace;try{Error.prepareStackTrace=(r,i)=>i;let e=new Error().stack;for(let r=2;r<e.length;r++){let i=e[r].getFileName();if(i&&i!==Kc&&!i.startsWith("node:"))return i.startsWith("file://")?qc(i):i}return null}finally{Error.prepareStackTrace=s}}function Fc(s){if(!s||typeof s!="object")return{type:"object",properties:{},required:[]};let t={},e=[];for(let[r,i]of Object.entries(s))if(typeof i=="string")t[r]={type:i},e.push(r);else{let{required:n,...o}=i;t[r]=o,n!==!1&&e.push(r)}return{type:"object",properties:t,required:e}}function Hc(s,t,e){if(typeof e.handler!="function")throw new Error(`Skill "${s}" must have a handler function`);let r={[s]:e.handler},i=[{name:s,description:e.description||"",input_schema:Fc(e.input)}];return Dc(s,r,i),{id:s,type:"function",serverName:s,allowedTools:[`mcp__${s}__*`],description:e.description||`Function skill: ${s}`,envKeys:[],tools:i,resolve(){let n=Bc();return n?{command:"node",args:[n,t,s]}:null}}}function zc(s,t){return{id:s,type:"mcp",serverName:t.serverName||s,allowedTools:t.allowedTools||[`mcp__${t.serverName||s}__*`],description:t.description||`MCP skill: ${s}`,envKeys:t.envKeys||[],tools:t.tools||[],resolve:t.resolve,...t.cursorKey&&{cursorKey:t.cursorKey},...t.sessionEnvKey&&{sessionEnvKey:t.sessionEnvKey}}}function xs(s,t){let e;if("handler"in t){if(typeof t.handler!="function")throw new Error(`Skill "${s}" must have a handler function`);let r=Gc();if(!r)throw new Error(`Could not resolve caller file for skill "${s}".`);e=Hc(s,r,t)}else if(typeof t.resolve=="function")e=zc(s,t);else throw new Error(`Skill "${s}" must have either a handler (function skill) or resolve (MCP skill).`);return Jc(e),e}var Yc=xs;import{registerSkill as Sp,getSkill as vp,hasSkill as Ip,getAllSkills as Np,listSkillIds as Op}from"@zibby/agent-workflow";N(Tt);N(jt);N(ae);N(ce);N(xt);N(Pt);N(Ut);N(Jt);N(x);N(K);N(Kt);N(Yt);N(Xt);N(sr);N(ir);N(Le);N(or);N(Ar);N(X);N(Cr);N(cr);N(mr);N(Wr);N(rs);N(cs);N(ls);N(ms);N(Is);N(vt);N(It);N(Nt);N({...x,id:"slack_notify"});var yp={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",LINEAR:"linear",PLANE:"plane",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",NOTION:"notion",GOOGLE_DOCS:"google-docs",LINKEDIN:"linkedin",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",DATASET_STORE:"dataset-store",CODEBASE_MEMORY:"codebase-memory",WORKFLOW_BUILDER:"workflow-builder",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"};export{I as INTEGRATIONS,Ks as INTEGRATION_REGISTRY,Ne as REPORT_SEVERITIES,yp as SKILLS,It as anthropicBillingSkill,Tt as browserSkill,Wr as chatMemorySkill,ir as chatNotifySkill,ms as codebaseMemorySkill,mr as coreToolsSkill,Nt as cursorAdminSkill,cs as datasetStoreSkill,Kt as discordSkill,Ic as fetchAllProviders,Ts as fetchAnthropicCosts,vc as fetchAnthropicWorkspaces,As as fetchCursorSpend,Rs as fetchOpenAICosts,Sc as fetchOpenAIProjects,xt as figmaSkill,Yc as functionSkill,Np as getAllSkills,vp as getSkill,X as gitSkill,Cr as gitWriteSkill,ae as githubSkill,ce as gitlabSkill,sr as googleDocsSkill,Nc as groupByKey,Ip as hasSkill,jt as jiraSkill,rs as kvMemorySkill,K as larkSkill,Pt as linearSkill,Xt as linkedinSkill,Op as listSkillIds,Oc as meanStddev,or as memorySkill,Yt as notionSkill,vt as openaiBillingSkill,Jt as opendesignSkill,Ut as planeSkill,Sp as registerSkill,Ot as reportObjectSchema,Cc as reportToBlockKit,Pc as reportToLarkCard,Ar as runnerSkill,Le as sentrySkill,xs as skill,cr as skillInstallerSkill,x as slackSkill,Ar as testRunnerSkill,Is as workflowBuilderSkill};
990
+ `;ye(R(o,"graph.mjs"),f,"utf-8");let h={name:n,description:e.description||`${i} workflow`,entryClass:i,triggers:{api:!0}};ye(R(o,"workflow.json"),`${JSON.stringify(h,null,2)}
991
+ `,"utf-8");let _=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(g=>`nodes/${g.replace(/_/g,"-")}.mjs`)];return{workflowDir:Ls(s,o),files:_,className:i,slug:n}}async function Kc(s){let{name:t,description:e,nodes:r,edges:n}=s;if(!t||!js.test(t.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${t}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!r||r.length===0)return JSON.stringify({error:"At least one node is required."});let i={name:t.toLowerCase(),description:e||`${$s(t.toLowerCase())} workflow`,nodes:r.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:n||[]};if(i.edges.length===0&&i.nodes.length>0){for(let o=0;o<i.nodes.length-1;o++)i.edges.push({from:i.nodes[o].name,to:i.nodes[o+1].name});i.edges.push({from:i.nodes[i.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:i,message:`Workflow "${i.name}" designed with ${i.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:i.nodes.map(o=>o.name),flow:i.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function Gc(s,t){let{name:e,spec:r}=s,n=(e||r?.name||"").toLowerCase();if(!n||!js.test(n))return JSON.stringify({error:`Invalid workflow name "${n}".`});if(!r||!r.nodes||r.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let i=R(t,".zibby","workflows",n);if(Y(i))return JSON.stringify({error:`Workflow "${n}" already exists at .zibby/workflows/${n}/. Delete it first or choose a different name.`});let o=await Us(r,t),a=Bc(t,n,r,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${n}" created at ${a.workflowDir}/`,nextSteps:[`Test locally: zibby start ${n}`,`Deploy to cloud: zibby deploy ${n} --project <project-id>`,`Tail logs: zibby logs --workflow ${n} --project <project-id>`]})}async function Fc(s,t){let{workflowName:e,nodeName:r,description:n,inputFields:i,outputFields:o}=s,a=(e||"").toLowerCase(),c=(r||"").replace(/-/g,"_"),d=R(t,".zibby","workflows",a);if(!Y(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:n||`Process ${c}`,inputFields:i||[],outputFields:o||[]}],edges:[]},p=(await Us(l,t)).nodes?.[c]?.code;if(!p)return JSON.stringify({error:"Failed to generate node code."});let m=R(d,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;ye(R(m,f),p,"utf-8");let h=R(m,"index.mjs"),_=Re(c),g=`export { ${_} } from './${c.replace(/_/g,"-")}.mjs';
992
+ `,b=Y(h)?Te(h,"utf-8"):"";return b.includes(_)||ye(h,b+g,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:_,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Hc(s,t){let{name:e,projectId:r}=s,n=(e||"").toLowerCase();if(!n)return JSON.stringify({error:"Workflow name is required."});if(!r)return JSON.stringify({error:"projectId is required."});let i=R(t,".zibby","workflows",n);if(!Y(i))return JSON.stringify({error:`Workflow "${n}" not found at .zibby/workflows/${n}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${R(t,"packages/cli/bin/zibby.js")}" deploy ${n} --project ${r}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:a.trim()})}catch{try{let{execSync:a}=await import("child_process"),c=a(`npx zibby deploy ${n} --project ${r}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:c.trim()})}catch(a){return JSON.stringify({error:`Deploy failed: ${a.message}`})}}}function zc(s){let t=R(s,".zibby","workflows");if(!Y(t))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let r=Tt(t).filter(n=>{try{return Es(R(t,n)).isDirectory()}catch{return!1}}).map(n=>{let i=R(t,n,"workflow.json"),o={};try{o=JSON.parse(Te(i,"utf-8"))}catch{}let a=R(t,n,"nodes"),c=0;try{c=Tt(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:n,description:o.description||"",nodeCount:c,path:Ls(s,R(t,n))}});return JSON.stringify({workflows:r})}var qs={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:Pc,tools:[{name:"design_workflow",description:"Design a workflow spec (nodes, edges, descriptions) for the user to review before building. Call this after understanding requirements.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name in kebab-case (e.g., ticket-triage)"},description:{type:"string",description:"What the workflow does"},nodes:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Node name in snake_case (e.g., classify_ticket)"},description:{type:"string",description:"What this node does \u2014 be specific about input/output"},inputFields:{type:"array",items:{type:"string"},description:"Key fields this node reads from state"},outputFields:{type:"array",items:{type:"string"},description:"Key fields this node produces"}},required:["name","description"]},description:"Workflow nodes (processing steps)"},edges:{type:"array",items:{type:"object",properties:{from:{type:"string",description:"Source node name"},to:{type:"string",description:'Target node name (or "END")'},condition:{type:"string",description:"JS expression for conditional routing (optional)"}},required:["from","to"]},description:"Edges connecting nodes. If omitted, nodes are wired linearly."}},required:["name","description","nodes"]}},{name:"build_workflow",description:"Generate real workflow code on disk from a design spec. Uses the configured AI agent for high-quality code generation.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name (from design_workflow)"},spec:{type:"object",description:"The full spec object returned by design_workflow",properties:{name:{type:"string"},description:{type:"string"},nodes:{type:"array",items:{type:"object"}},edges:{type:"array",items:{type:"object"}}}}},required:["name","spec"]}},{name:"add_node",description:"Add a new node to an existing workflow. Generates the node file and updates the barrel export.",input_schema:{type:"object",properties:{workflowName:{type:"string",description:"Existing workflow name (kebab-case)"},nodeName:{type:"string",description:"New node name (snake_case)"},description:{type:"string",description:"What this node does"},inputFields:{type:"array",items:{type:"string"},description:"Fields read from state"},outputFields:{type:"array",items:{type:"string"},description:"Fields produced"}},required:["workflowName","nodeName","description"]}},{name:"deploy_workflow",description:"Deploy a workflow to Zibby Cloud. Returns the trigger URL.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name to deploy"},projectId:{type:"string",description:"Target project ID"}},required:["name","projectId"]}},{name:"list_workflows",description:"List all local workflows in .zibby/workflows/.",input_schema:{type:"object",properties:{}}},{name:"explore_framework_docs",description:"Read Zibby framework documentation on demand. Call this before building complex workflows or when you need details on advanced patterns (middleware, conditional routing, skills, deployment, CLI commands).",input_schema:{type:"object",properties:{topic:{type:"string",description:'Doc topic to read (e.g., "workflow", "custom-workflows", "cli-reference", "packages/core", "packages/skills", "integrations/jira"). Call with no topic to list all available docs.'}}}}],async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"design_workflow":return await Kc(t);case"build_workflow":return await Gc(t,r);case"add_node":return await Fc(t,r);case"deploy_workflow":return await Hc(t,r);case"list_workflows":return zc(r);case"explore_framework_docs":{let n=(t.topic||"").trim();if(!n){let o=As();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let i=Ps(n);if(!i){let o=As();return JSON.stringify({error:`Doc "${n}" not found.`,available:o})}return JSON.stringify({topic:n,content:i})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(n){return JSON.stringify({error:n.message})}},resolve(){return null}};import{resolveIntegrationToken as Yc}from"@zibby/core/backend-client.js";var Lt=Object.freeze({id:"openai_billing",requiresIntegration:v.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),xt=Object.freeze({id:"anthropic_billing",requiresIntegration:v.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),jt=Object.freeze({id:"cursor_admin",requiresIntegration:v.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Ds(s){return Math.floor(s/1e3)}function Et(s){return new Date(s).toISOString().slice(0,10)}function Js(s){return new Date(s).toISOString()}async function Ae(s){let t=await Yc(s);if(!t?.token)throw new Error(`${s} token resolver returned no token`);return t.token}async function Ms({startMs:s,endMs:t,groupBy:e=["project_id","line_item"]}){let r=await Ae("openai_billing"),n=[],i=0,o=e.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.openai.com/v1/organization/costs?${[`start_time=${Ds(s)}`,`end_time=${Ds(t)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{Authorization:`Bearer ${r}`}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`OpenAI costs API ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){i+=1;let f=Et((m.start_time||0)*1e3);for(let h of m.results||[])n.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:n,rawBuckets:i}}async function Wc(){let s=await Ae("openai_billing"),e=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${s}`}});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`OpenAI projects API ${e.status}: ${i.slice(0,200)}`)}let r=await e.json(),n=new Map;for(let i of r.data||[])n.set(i.id,i.name);return n}async function Bs({startMs:s,endMs:t,groupBy:e=["workspace_id"]}){let r=await Ae("anthropic_billing"),n=[],i=0,o=e.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(Js(s))}`,`ending_at=${encodeURIComponent(Js(t))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Anthropic cost_report ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){i+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])n.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:n,rawBuckets:i}}async function Zc(){let s=await Ae("anthropic_billing"),e=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":s,"anthropic-version":"2023-06-01"}});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`Anthropic workspaces ${e.status}: ${i.slice(0,200)}`)}let r=await e.json(),n=new Map;for(let i of r.data||[])n.set(i.id,i.name);return n}async function Ks({startMs:s,endMs:t}){let e=await Ae("cursor_admin"),r=Et(s),n=Et(t),i=`https://api.cursor.com/teams/daily-usage-data?startDate=${r}&endDate=${n}`,o=await fetch(i,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${l.slice(0,200)}`)}let a=await o.json(),c=[],d=0;for(let l of a.data||[]){d+=1;let u=l.date;for(let p of l.userMetrics||[]){for(let m of p.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:u,costUsd:Number(m.totalCents??0)/100,userEmail:p.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!p.modelUsage||p.modelUsage.length===0)&&c.push({provider:"cursor",day:u,costUsd:Number(p.totalCents??0)/100,userEmail:p.email})}}return{ok:!0,items:c,rawBuckets:d}}async function Vc({startMs:s,endMs:t}){let[e,r,n]=await Promise.allSettled([Ms({startMs:s,endMs:t}),Bs({startMs:s,endMs:t}),Ks({startMs:s,endMs:t})]),i=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=i(e),a=i(r),c=i(n),d=[{provider:"openai",totalUsd:o.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,u)=>l+(u.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function Qc(s,t){let e=new Map;for(let r of s){let n=t(r);if(!n)continue;let i=e.get(n)||{key:n,totalUsd:0,count:0};i.totalUsd+=r.costUsd||0,i.count+=1,e.set(n,i)}return[...e.values()].sort((r,n)=>n.totalUsd-r.totalUsd)}function Xc(s){if(!s.length)return{mean:0,stddev:0};let t=s.reduce((r,n)=>r+n,0)/s.length,e=s.reduce((r,n)=>r+(n-t)**2,0)/s.length;return{mean:t,stddev:Math.sqrt(e)}}import{z as k}from"zod";var Ee=["ok","info","warn","critical"],el=k.object({primary:k.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:k.object({value:k.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:k.enum(["up","down","flat"]).optional(),severity:k.enum(Ee).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:k.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),tl=k.object({kind:k.literal("trend"),title:k.string().max(120).optional(),labels:k.array(k.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:k.array(k.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:k.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:k.enum(Ee).optional()}),rl=k.object({kind:k.literal("table"),title:k.string().max(120).optional(),headers:k.array(k.string().max(40)).min(1).max(8),rows:k.array(k.array(k.union([k.string().max(200),k.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),sl=k.object({kind:k.literal("callouts"),title:k.string().max(120).optional(),tone:k.enum(Ee).default("info").optional(),items:k.array(k.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),nl=k.object({kind:k.literal("breakdown"),title:k.string().max(120).optional(),rows:k.array(k.object({label:k.string().min(1).max(80),value:k.string().min(1).max(80),sub:k.string().max(120).optional(),severity:k.enum(Ee).optional()})).min(1).max(20)}),il=k.object({kind:k.literal("paragraph"),title:k.string().max(120).optional(),text:k.string().min(1).max(3e3)}),ol=k.discriminatedUnion("kind",[tl,rl,sl,nl,il]),$t=k.object({title:k.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:k.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:el,sections:k.array(ol).max(20).default([]).superRefine((s,t)=>{s.forEach((e,r)=>{e.kind==="trend"&&e.labels.length!==e.values.length&&t.addIssue({code:k.ZodIssueCode.custom,path:[r,"values"],message:"labels.length must equal values.length"}),e.kind==="table"&&!e.rows.every(n=>n.length===e.headers.length)&&t.addIssue({code:k.ZodIssueCode.custom,path:[r,"rows"],message:"every row must have headers.length entries"})})}),footer:k.object({viewUrl:k.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:k.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),re=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),Gs=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),al=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Fs(s,t,e=12){if(!Number.isFinite(s)||!Number.isFinite(t)||t<=0)return"";let r=Math.max(0,Math.min(1,s/t)),n=Math.round(r*e);return"\u2593".repeat(n)+"\u2591".repeat(e-n)}function Ct(s,t){let e=String(s);return e.length>=t?e:e+" ".repeat(t-e.length)}function Hs(s,t){let e=String(s);return e.length>=t?e:" ".repeat(t-e.length)+e}function zs({headers:s,rows:t}){let e=s.map((o,a)=>{let c=Math.max(String(o).length,...t.map(d=>String(d[a]??"").length));return Math.min(c,32)}),r=o=>o.map((a,c)=>Ct(a,e[c])).join(" "),n=e.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[r(s),n,...t.map(o=>r(o))].join(`
993
+ `)+"\n```"}function cl(s){let t=$t.parse(s),e=[];e.push({type:"header",text:{type:"plain_text",text:t.title.slice(0,150),emoji:!0}}),t.subtitle&&e.push({type:"context",elements:[{type:"mrkdwn",text:t.subtitle}]});let r=[`*${t.headline.primary}*`];if(t.headline.delta){let i=Gs[t.headline.delta.direction]||"",o=t.headline.delta.severity?re[t.headline.delta.severity]:"";r.push(`${i} ${t.headline.delta.value} ${o}`.trim())}let n=r.join(" ");t.headline.summary&&(n+=`
994
+ `+t.headline.summary),e.push({type:"section",text:{type:"mrkdwn",text:n}});for(let i of t.sections)switch(e.push({type:"divider"}),i.title&&e.push({type:"section",text:{type:"mrkdwn",text:`*${i.title}*`}}),i.kind){case"trend":{let o=Math.max(...i.values),a=i.labels.map((c,d)=>{let l=i.values[d],u=Fs(l,o),m=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&l===o||i.highlight==="min"&&l===Math.min(...i.values))&&i.severity?` ${re[i.severity]}`:"";return`${Ct(c,10)} ${Hs(l.toLocaleString(),8)} ${u}${m}`});e.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
995
+ `)+"\n```"}});break}case"table":{e.push({type:"section",text:{type:"mrkdwn",text:zs(i)}});break}case"callouts":{let o=re[i.tone||"info"];e.push({type:"section",text:{type:"mrkdwn",text:i.items.map(a=>`${o} ${a}`).join(`
996
+ `)}});break}case"breakdown":{let o=i.rows.map(a=>({type:"mrkdwn",text:`*${a.label}*
997
+ ${a.value}${a.sub?`
998
+ _${a.sub}_`:""}${a.severity?` ${re[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)e.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{e.push({type:"section",text:{type:"mrkdwn",text:i.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let i=[];t.footer.viewUrl&&i.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:t.footer.viewUrl,style:"primary"}),t.footer.rerunUrl&&i.push({type:"button",text:{type:"plain_text",text:"Run again"},url:t.footer.rerunUrl}),e.push({type:"divider"}),e.push({type:"actions",elements:i})}return e}function ll(s){let t=$t.parse(s),e=[],r=[`**${t.headline.primary}**`];if(t.headline.delta){let o=Gs[t.headline.delta.direction]||"",a=t.headline.delta.severity?re[t.headline.delta.severity]:"";r.push(`${o} ${t.headline.delta.value} ${a}`.trim())}let n=r.join(" ");t.headline.summary&&(n+=`
999
+ `+t.headline.summary),e.push({tag:"div",text:{tag:"lark_md",content:n}});for(let o of t.sections)switch(e.push({tag:"hr"}),o.title&&e.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let a=Math.max(...o.values),c=o.labels.map((d,l)=>{let u=o.values[l],p=Fs(u,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&u===a||o.highlight==="min"&&u===Math.min(...o.values))&&o.severity?` ${re[o.severity]}`:"";return`${Ct(d,10)} ${Hs(u.toLocaleString(),8)} ${p}${f}`});e.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1000
+ `)+"\n```"}});break}case"table":{e.push({tag:"div",text:{tag:"lark_md",content:zs(o)}});break}case"callouts":{let a=re[o.tone||"info"];e.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
1001
+ `)}});break}case"breakdown":{let a=o.rows.map(c=>{let d=c.severity?` ${re[c.severity]}`:"",l=c.sub?` *${c.sub}*`:"";return`**${c.label}** ${c.value}${l}${d}`});e.push({tag:"div",text:{tag:"lark_md",content:a.join(`
1002
+ `)}});break}case"paragraph":{e.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let o=[];t.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:t.footer.viewUrl,type:"primary"}),t.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:t.footer.rerunUrl,type:"default"}),e.push({tag:"hr"}),e.push({tag:"action",actions:o})}let i="blue";return t.headline.delta?.severity&&(i=al[t.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:t.title.slice(0,200)},subtitle:t.subtitle?{tag:"plain_text",content:t.subtitle.slice(0,200)}:void 0,template:i},elements:e}}var up=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),pp=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});import{createRequire as dl}from"module";import{fileURLToPath as ul}from"url";import{registerHandlers as pl}from"@zibby/core/function-skill-registry.js";import{registerSkill as ml}from"@zibby/agent-workflow";var fl=dl(import.meta.url);function hl(){try{return fl.resolve("@zibby/core/function-bridge.js")}catch{return null}}var yl=import.meta.url;function gl(){let s=Error.prepareStackTrace;try{Error.prepareStackTrace=(r,n)=>n;let e=new Error().stack;for(let r=2;r<e.length;r++){let n=e[r].getFileName();if(n&&n!==yl&&!n.startsWith("node:"))return n.startsWith("file://")?ul(n):n}return null}finally{Error.prepareStackTrace=s}}function _l(s){if(!s||typeof s!="object")return{type:"object",properties:{},required:[]};let t={},e=[];for(let[r,n]of Object.entries(s))if(typeof n=="string")t[r]={type:n},e.push(r);else{let{required:i,...o}=n;t[r]=o,i!==!1&&e.push(r)}return{type:"object",properties:t,required:e}}function bl(s,t,e){if(typeof e.handler!="function")throw new Error(`Skill "${s}" must have a handler function`);let r={[s]:e.handler},n=[{name:s,description:e.description||"",input_schema:_l(e.input)}];return pl(s,r,n),{id:s,type:"function",serverName:s,allowedTools:[`mcp__${s}__*`],description:e.description||`Function skill: ${s}`,envKeys:[],tools:n,resolve(){let i=hl();return i?{command:"node",args:[i,t,s]}:null}}}function kl(s,t){return{id:s,type:"mcp",serverName:t.serverName||s,allowedTools:t.allowedTools||[`mcp__${t.serverName||s}__*`],description:t.description||`MCP skill: ${s}`,envKeys:t.envKeys||[],tools:t.tools||[],resolve:t.resolve,...t.cursorKey&&{cursorKey:t.cursorKey},...t.sessionEnvKey&&{sessionEnvKey:t.sessionEnvKey}}}function Ys(s,t){let e;if("handler"in t){if(typeof t.handler!="function")throw new Error(`Skill "${s}" must have a handler function`);let r=gl();if(!r)throw new Error(`Could not resolve caller file for skill "${s}".`);e=bl(s,r,t)}else if(typeof t.resolve=="function")e=kl(s,t);else throw new Error(`Skill "${s}" must have either a handler (function skill) or resolve (MCP skill).`);return ml(e),e}var wl=Ys;import{registerSkill as rm,getSkill as sm,hasSkill as nm,getAllSkills as im,listSkillIds as om}from"@zibby/agent-workflow";N(Pt);N(Dt);N(ce);N(le);N(Bt);N(Gt);N(Ft);N(Yt);N($);N(K);N(Vt);N(rr);N(ar);N(ur);N(gr);N(_r);N(De);N(kr);N(Kr);N(ee);N(Wr);N(Sr);N(Rr);N(ls);N(ys);N(Ss);N(Is);N(Rs);N(qs);N(Lt);N(xt);N(jt);N({...$,id:"slack_notify"});var Zp={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",LINEAR:"linear",PLANE:"plane",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINKEDIN:"linkedin",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",DATASET_STORE:"dataset-store",CODEBASE_MEMORY:"codebase-memory",WORKFLOW_BUILDER:"workflow-builder",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"};export{v as INTEGRATIONS,sn as INTEGRATION_REGISTRY,Ee as REPORT_SEVERITIES,Zp as SKILLS,xt as anthropicBillingSkill,Pt as browserSkill,ls as chatMemorySkill,_r as chatNotifySkill,Rs as codebaseMemorySkill,Rr as coreToolsSkill,jt as cursorAdminSkill,Ss as datasetStoreSkill,Vt as discordSkill,Vc as fetchAllProviders,Bs as fetchAnthropicCosts,Zc as fetchAnthropicWorkspaces,Ks as fetchCursorSpend,Ms as fetchOpenAICosts,Wc as fetchOpenAIProjects,Bt as figmaSkill,wl as functionSkill,im as getAllSkills,sm as getSkill,ee as gitSkill,Wr as gitWriteSkill,ce as githubSkill,le as gitlabSkill,ur as googleDocsSkill,Qc as groupByKey,nm as hasSkill,Dt as jiraSkill,ys as kvMemorySkill,gr as larkDocsSkill,K as larkSkill,Gt as linearSkill,ar as linkedinSkill,om as listSkillIds,Xc as meanStddev,kr as memorySkill,rr as notionSkill,Lt as openaiBillingSkill,Yt as opendesignSkill,Ft as planeSkill,rm as registerSkill,$t as reportObjectSchema,cl as reportToBlockKit,ll as reportToLarkCard,Kr as runnerSkill,De as sentrySkill,Ys as skill,Sr as skillInstallerSkill,$ as slackSkill,Kr as testRunnerSkill,qs as workflowBuilderSkill};