@zibby/skills 0.1.85 → 0.1.87

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,9 +1,9 @@
1
- import{registerSkill as I}from"@zibby/agent-workflow";import{createRequire as qs}from"module";import{join as Js}from"path";var Ds=qs(import.meta.url);function Bs(){if(process.env.MCP_BROWSER_PATH)return process.env.MCP_BROWSER_PATH;try{return Ds.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js")}catch{return null}}var Ms="1280x720",Fs="1280x720";function Gs({headless:r}={}){if(r===!0)return!0;if(r===!1)return!1;let e=process.env.ZIBBY_HEADLESS;return e==="1"||String(e).toLowerCase()==="true"}function Ks(r,e){let t=(r||[]).filter(n=>n!=="--headless");return e?[...t,"--headless"]:t}var Cr={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 v}from"@zibby/agent-workflow";import{createRequire as Hs}from"module";import{join as zs}from"path";var Ys=Hs(import.meta.url);function Ws(){if(process.env.MCP_BROWSER_PATH)return process.env.MCP_BROWSER_PATH;try{return Ys.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js")}catch{return null}}var Zs="1280x720",Vs="1280x720";function Qs({headless:r}={}){if(r===!0)return!0;if(r===!1)return!1;let e=process.env.ZIBBY_HEADLESS;return e==="1"||String(e).toLowerCase()==="true"}function Xs(r,e){let t=(r||[]).filter(n=>n!=="--headless");return e?[...t,"--headless"]:t}var Jr={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:r,workspace:e,nodeName:t,headless:n}={}){let i=Bs(),s=r&&t?Js(r,t):null,o=s||r||e||"test-results",a=Gs({headless:n}),c={};if(s&&(c.ZIBBY_NODE_SESSION_PATH=s),r&&(c.ZIBBY_SESSION_PATH=r),!i)throw new Error(`@zibby/mcp-browser is not installed.
3
+ DO NOT return success: true unless you ACTUALLY called browser tools.`,resolve({sessionPath:r,workspace:e,nodeName:t,headless:n}={}){let i=Ws(),s=r&&t?zs(r,t):null,o=s||r||e||"test-results",a=Qs({headless:n}),c={};if(s&&(c.ZIBBY_NODE_SESSION_PATH=s),r&&(c.ZIBBY_SESSION_PATH=r),!i)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:Ks([i,"--isolated",`--save-video=${Ms}`,`--viewport-size=${Fs}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as zs}from"module";import{resolveIntegrationToken as Ws,clearTokenCache as Ys}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",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Hs=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var Zs=zs(import.meta.url);function Vs(){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 Qs=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Xs(r,e){if(!e||!e.length)return r;let t=r;for(let n of e)n.type==="strong"?t=`**${t}**`:n.type==="em"?t=`_${t}_`:n.type==="code"?t=`\`${t}\``:n.type==="strike"?t=`~~${t}~~`:n.type==="link"&&n.attrs?.href&&(t=`[${t}](${n.attrs.href})`);return t}function ot(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(Xs(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
6
+ Override: set MCP_BROWSER_PATH to the path of mcp-browser-zibby.js.`);return{command:"node",args:Xs([i,"--isolated",`--save-video=${Zs}`,`--viewport-size=${Vs}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as to}from"module";import{resolveIntegrationToken as ro,clearTokenCache as no}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",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),eo=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var io=to(import.meta.url);function so(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return io.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var oo=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function ao(r,e){if(!e||!e.length)return r;let t=r;for(let n of e)n.type==="strong"?t=`**${t}**`:n.type==="em"?t=`_${t}_`:n.type==="code"?t=`\`${t}\``:n.type==="strike"?t=`~~${t}~~`:n.type==="link"&&n.attrs?.href&&(t=`[${t}](${n.attrs.href})`);return t}function ot(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(ao(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
7
7
  `);continue}if(n.type==="rule"){t.push(`
8
8
  ---
9
9
  `);continue}let i=n.content?ot(n.content,e+1):"";if(n.type==="listItem")t.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${ot(o.content||[],e+1).trim()}`);t.push(`
@@ -16,12 +16,12 @@ ${s.join(`
16
16
 
17
17
  ${"#".repeat(s)} ${i.trim()}
18
18
 
19
- `)}else Qs.has(n.type)?t.push(`
19
+ `)}else oo.has(n.type)?t.push(`
20
20
 
21
21
  ${i}
22
22
  `):t.push(i)}return t.join("").replace(/\n{3,}/g,`
23
23
 
24
- `)}function xe(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Jt(r){return xe(r).replace(/[a-z0-9]+/g,"")}function at(r,e){let t=xe(r),n=xe(e);if(!t||!n)return 0;if(t===n)return 1;if(t.length===1||n.length===1)return t===n?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=i(t),o=i(n),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of s.entries()){let u=o.get(l)||0;a+=Math.min(p,u)}return 2*a/Math.max(1,c+d)}function pe(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function eo(r,e=[]){let t=Array.isArray(e)?e:[];if(t.length===0)return{requested:r||null,resolved:null,strategy:"none"};let n=t.filter(a=>!a.subtask),i=n.length>0?n:t,s=pe(r);if(s){let a=i.find(l=>pe(l.name)===s);if(a)return{requested:r,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(u=>pe(u)===s))continue;let p=i.find(u=>l.some(m=>pe(m)===pe(u.name)));if(p)return{requested:r,resolved:p,strategy:"alias"}}let d=i.map(l=>({t:l,score:at(r,l.name)})).sort((l,p)=>p.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:r,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(d=>pe(d.name)===a);if(c)return{requested:r||null,resolved:c,strategy:"default-preferred"}}return{requested:r||null,resolved:i[0],strategy:"default-first"}}async function Ur(r){let e=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,t=await E(`/rest/api/3/issue/createmeta?${e}`),n=Array.isArray(t?.projects)?t.projects:[],s=n.find(a=>String(a?.key||"").toUpperCase()===String(r||"").toUpperCase())||n[0]||null;return(Array.isArray(s?.issuetypes)?s.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function qr(r,e){if(!r)throw new Error("projectKey is required");let t="sprint is not EMPTY";e==="active"?t="sprint in openSprints()":e==="closed"?t="sprint in closedSprints()":e==="future"&&(t="sprint in futureSprints()");let n=`project = ${r} AND ${t} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(n)}&maxResults=100&fields=customfield_10020`,s=await E(`/rest/api/3/search/jql?${i}`),o=new Map;for(let a of s.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let 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 to(r,{sprintId:e,sprintName:t,target:n}={}){let i=Array.isArray(r)?r:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(e!=null&&String(e).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(e))||null,selectedBy:"id"};if(t&&String(t).trim()){let o=String(t).trim(),a=i.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(d=>({s:d,score:at(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 s=String(n||"current").trim().toLowerCase();return s==="active"||s==="current"||s==="latest"?{sprint:i[0],selectedBy:s}:{sprint:i[0],selectedBy:"default"}}function ro(r,e){let t=r?.fields?.customfield_10020;return Array.isArray(t)?t.some(n=>String(n?.id)===String(e)):!1}async function no({issueKey:r,projectKey:e,sprintId:t,attempts:n=3,delayMs:i=450}){let s=[];for(let o=0;o<n;o++){try{let a=`project = ${e} AND key = ${r} AND sprint = ${t}`,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 s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let p=await E(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),u=ro(p,t);if(s.push({attempt:o+1,jql:!1,issueField:u}),u)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<n-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:s}}async function Dt({issueKey:r,projectKey:e,sprintId:t,sprintName:n,target:i}){if(!r)return{ok:!1,error:"issueKey is required"};let s=e;if(!s&&(s=(await E(`/rest/api/3/issue/${r}?fields=project`))?.fields?.project?.key||null,!s))return{ok:!1,error:`Could not resolve project for ${r}`};let o=await qr(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=to(o,{sprintId:t,sprintName:n,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:t??null,sprintName:n??null,target:i??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await E(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await no({issueKey:r,projectKey:s,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:r,projectKey:s,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 ${r} in sprint ${a.id}`}}async function E(r,e={}){let t=async()=>{let{token:n,cloudId:i}=await Ws("jira");if(typeof n!="string"||!n)throw new Error(`Invalid jira token type: ${typeof n}`);if(!i)throw new Error("Invalid jira cloudId: missing");let s=`https://api.atlassian.com/ex/jira/${i}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.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 t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw n;return Ys("jira"),t()}}var Jr={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)
24
+ `)}function xe(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Bt(r){return xe(r).replace(/[a-z0-9]+/g,"")}function at(r,e){let t=xe(r),n=xe(e);if(!t||!n)return 0;if(t===n)return 1;if(t.length===1||n.length===1)return t===n?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=i(t),o=i(n),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of s.entries()){let u=o.get(l)||0;a+=Math.min(p,u)}return 2*a/Math.max(1,c+d)}function pe(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function co(r,e=[]){let t=Array.isArray(e)?e:[];if(t.length===0)return{requested:r||null,resolved:null,strategy:"none"};let n=t.filter(a=>!a.subtask),i=n.length>0?n:t,s=pe(r);if(s){let a=i.find(l=>pe(l.name)===s);if(a)return{requested:r,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(u=>pe(u)===s))continue;let p=i.find(u=>l.some(m=>pe(m)===pe(u.name)));if(p)return{requested:r,resolved:p,strategy:"alias"}}let d=i.map(l=>({t:l,score:at(r,l.name)})).sort((l,p)=>p.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:r,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(d=>pe(d.name)===a);if(c)return{requested:r||null,resolved:c,strategy:"default-preferred"}}return{requested:r||null,resolved:i[0],strategy:"default-first"}}async function qr(r){let e=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,t=await E(`/rest/api/3/issue/createmeta?${e}`),n=Array.isArray(t?.projects)?t.projects:[],s=n.find(a=>String(a?.key||"").toUpperCase()===String(r||"").toUpperCase())||n[0]||null;return(Array.isArray(s?.issuetypes)?s.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function Dr(r,e){if(!r)throw new Error("projectKey is required");let t="sprint is not EMPTY";e==="active"?t="sprint in openSprints()":e==="closed"?t="sprint in closedSprints()":e==="future"&&(t="sprint in futureSprints()");let n=`project = ${r} AND ${t} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(n)}&maxResults=100&fields=customfield_10020`,s=await E(`/rest/api/3/search/jql?${i}`),o=new Map;for(let a of s.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let 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 lo(r,{sprintId:e,sprintName:t,target:n}={}){let i=Array.isArray(r)?r:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(e!=null&&String(e).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(e))||null,selectedBy:"id"};if(t&&String(t).trim()){let o=String(t).trim(),a=i.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(d=>({s:d,score:at(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 s=String(n||"current").trim().toLowerCase();return s==="active"||s==="current"||s==="latest"?{sprint:i[0],selectedBy:s}:{sprint:i[0],selectedBy:"default"}}function po(r,e){let t=r?.fields?.customfield_10020;return Array.isArray(t)?t.some(n=>String(n?.id)===String(e)):!1}async function uo({issueKey:r,projectKey:e,sprintId:t,attempts:n=3,delayMs:i=450}){let s=[];for(let o=0;o<n;o++){try{let a=`project = ${e} AND key = ${r} AND sprint = ${t}`,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 s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let p=await E(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),u=po(p,t);if(s.push({attempt:o+1,jql:!1,issueField:u}),u)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<n-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:s}}async function Mt({issueKey:r,projectKey:e,sprintId:t,sprintName:n,target:i}){if(!r)return{ok:!1,error:"issueKey is required"};let s=e;if(!s&&(s=(await E(`/rest/api/3/issue/${r}?fields=project`))?.fields?.project?.key||null,!s))return{ok:!1,error:`Could not resolve project for ${r}`};let o=await Dr(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=lo(o,{sprintId:t,sprintName:n,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:t??null,sprintName:n??null,target:i??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await E(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await uo({issueKey:r,projectKey:s,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:r,projectKey:s,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 ${r} in sprint ${a.id}`}}async function E(r,e={}){let t=async()=>{let{token:n,cloudId:i}=await ro("jira");if(typeof n!="string"||!n)throw new Error(`Invalid jira token type: ${typeof n}`);if(!i)throw new Error("Invalid jira cloudId: missing");let s=`https://api.atlassian.com/ex/jira/${i}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.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 t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw n;return no("jira"),t()}}var Br={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)
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 r=Vs();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);process.env.ATLASSIAN_INSTANCE_URL&&(e.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let t of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[t]&&(e[t]=process.env[t]);return{command:"node",args:[r],env:e,description:this.description}},async handleToolCall(r,e){try{switch(r){case"jira_list_projects":{let t=await E("/rest/api/3/project"),n=(Array.isArray(t)?t:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await E(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],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:t,count:c.length,statuses:c})}let n=await E("/rest/api/3/status"),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let n=await Ur(t);return JSON.stringify({projectKey:t,count:n.length,issueTypes:n})}case"jira_search":{let t=e.jql||"",n=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await E(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let n=await E(`/rest/api/3/issue/${t}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name,labels:n.fields?.labels,created:n.fields?.created,updated:n.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=e;if(!t||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await Ur(t),f=eo(i,h)}catch{}let y={project:{key:t},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(y.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(y.priority={name:o}),a?.length&&(y.labels=a),c&&(y.assignee={id:c});let _=await E("/rest/api/3/issue",{method:"POST",body:{fields:y}}),b={ok:!0,key:_.key,id:_.id,self:_.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&pe(f.requested)!==pe(f.resolved.name)&&(b.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(b.availableIssueTypes=h.map(g=>g.name)),(d||l)&&(b.sprintMove=await Dt({issueKey:_.key,projectKey:t,sprintId:p,sprintName:u,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,i=await qr(t,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await Dt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await Dt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:n,projectKey:i,status:s,maxResults:o}=e;if(!t&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${t}"`,d=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",p=`${d}${c}${l} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await E(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(y=>({key:y.key,project:y.fields?.project?.key,summary:y.fields?.summary,status:y.fields?.status?.name,assignee:y.fields?.assignee?.displayName||"Unassigned",priority:y.fields?.priority?.name,type:y.fields?.issuetype?.name})),h={};for(let y of f)h[y.status]=(h[y.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:t,maxResults:n}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await E(`/rest/api/3/issue/${t}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=ot(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:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:n}=e;return!t||!n?JSON.stringify({error:"issueKey and body are required"}):(await E(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:n}=e;return!t||!n?JSON.stringify({error:"issueKey and fields are required"}):(await E(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:n,toStatus:i,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let p=((await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:p})}let c=n;if(!c){let p=(await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[],u=xe(a),m=p.find(f=>xe(f?.name||"")===u||xe(f?.to?.name||"")===u);if(!m){let f=Jt(a);f.length>=2&&(m=p.find(h=>{let y=Jt(h?.name||""),_=Jt(h?.to?.name||""),b=y.length>=2&&(y.includes(f)||f.includes(y)),g=_.length>=2&&(_.includes(f)||f.includes(_));return b||g}))}if(!m){let f=p.map(b=>{let g=at(a,b?.name||""),k=at(a,b?.to?.name||"");return{t:b,score:Math.max(g,k)}}).sort((b,g)=>g.score-b.score),h=f[0],y=f[1];h&&h.score>=.45&&(!y||h.score-y.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await E(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await E(`/rest/api/3/issue/${t}?fields=status`);return JSON.stringify({ok:!0,issueKey:t,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 ho}from"fs";import{fileURLToPath as go}from"url";import{dirname as yo,resolve as _o}from"path";import{resolveIntegrationToken as Br}from"@zibby/core/backend-client.js";import{spawn as io,execSync as so}from"child_process";import{existsSync as Z,mkdirSync as oo,readdirSync as Dr,statSync as ao,readFileSync as co}from"fs";import{resolve as Bt,join as V,basename as lo}from"path";var Mt=".zibby/repos";function po(r){let e=String(r??"");for(let t of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])t&&(e=e.split(t).join("***"));return e.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,t=>t.replace(/:[^@\s]+@/,":***@"))}function Fe(r,e,t,n,i="clone"){try{r(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);n&&(o=o.split(n).join("***")),console.error(`[${i}] WARNING: failed to strip token from .git/config: ${o}`)}}function ct(r,e,t={}){return new Promise((n,i)=>{let s=io(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),s.on("error",c=>i(c))})}var ue={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
74
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=so();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);process.env.ATLASSIAN_INSTANCE_URL&&(e.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let t of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[t]&&(e[t]=process.env[t]);return{command:"node",args:[r],env:e,description:this.description}},async handleToolCall(r,e){try{switch(r){case"jira_list_projects":{let t=await E("/rest/api/3/project"),n=(Array.isArray(t)?t:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await E(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],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:t,count:c.length,statuses:c})}let n=await E("/rest/api/3/status"),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let n=await qr(t);return JSON.stringify({projectKey:t,count:n.length,issueTypes:n})}case"jira_search":{let t=e.jql||"",n=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await E(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let n=await E(`/rest/api/3/issue/${t}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name,labels:n.fields?.labels,created:n.fields?.created,updated:n.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=e;if(!t||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await qr(t),f=co(i,h)}catch{}let g={project:{key:t},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(g.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(g.priority={name:o}),a?.length&&(g.labels=a),c&&(g.assignee={id:c});let _=await E("/rest/api/3/issue",{method:"POST",body:{fields:g}}),b={ok:!0,key:_.key,id:_.id,self:_.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&pe(f.requested)!==pe(f.resolved.name)&&(b.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(b.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(b.sprintMove=await Mt({issueKey:_.key,projectKey:t,sprintId:p,sprintName:u,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,i=await Dr(t,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await Mt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await Mt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:n,projectKey:i,status:s,maxResults:o}=e;if(!t&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${t}"`,d=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",p=`${d}${c}${l} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await E(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(g=>({key:g.key,project:g.fields?.project?.key,summary:g.fields?.summary,status:g.fields?.status?.name,assignee:g.fields?.assignee?.displayName||"Unassigned",priority:g.fields?.priority?.name,type:g.fields?.issuetype?.name})),h={};for(let g of f)h[g.status]=(h[g.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:t,maxResults:n}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await E(`/rest/api/3/issue/${t}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=ot(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:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:n}=e;return!t||!n?JSON.stringify({error:"issueKey and body are required"}):(await E(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:n}=e;return!t||!n?JSON.stringify({error:"issueKey and fields are required"}):(await E(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:n,toStatus:i,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let p=((await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:p})}let c=n;if(!c){let p=(await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[],u=xe(a),m=p.find(f=>xe(f?.name||"")===u||xe(f?.to?.name||"")===u);if(!m){let f=Bt(a);f.length>=2&&(m=p.find(h=>{let g=Bt(h?.name||""),_=Bt(h?.to?.name||""),b=g.length>=2&&(g.includes(f)||f.includes(g)),y=_.length>=2&&(_.includes(f)||f.includes(_));return b||y}))}if(!m){let f=p.map(b=>{let y=at(a,b?.name||""),k=at(a,b?.to?.name||"");return{t:b,score:Math.max(y,k)}}).sort((b,y)=>y.score-b.score),h=f[0],g=f[1];h&&h.score>=.45&&(!g||h.score-g.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await E(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await E(`/rest/api/3/issue/${t}?fields=status`);return JSON.stringify({ok:!0,issueKey:t,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 vo}from"fs";import{fileURLToPath as Io}from"url";import{dirname as No,resolve as Oo}from"path";import{resolveIntegrationToken as Fr}from"@zibby/core/backend-client.js";import{spawn as mo,execSync as fo}from"child_process";import{existsSync as Z,mkdirSync as ho,readdirSync as Mr,statSync as yo,readFileSync as go}from"fs";import{resolve as Ft,join as V,basename as _o}from"path";var Gt=".zibby/repos";function bo(r){let e=String(r??"");for(let t of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])t&&(e=e.split(t).join("***"));return e.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,t=>t.replace(/:[^@\s]+@/,":***@"))}function Fe(r,e,t,n,i="clone"){try{r(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);n&&(o=o.split(n).join("***")),console.error(`[${i}] WARNING: failed to strip token from .git/config: ${o}`)}}function ct(r,e,t={}){return new Promise((n,i)=>{let s=mo(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),s.on("error",c=>i(c))})}var ue={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
75
75
  You can clone and explore git repositories locally for codebase analysis:
76
76
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
77
77
  - git_list_repos: List locally cloned repos
@@ -82,7 +82,7 @@ When a test ticket lacks context, use this workflow:
82
82
  2. Use git_explore to understand the project structure
83
83
  3. Use shell commands (grep, cat) to read specific files for deeper understanding
84
84
  4. Use GitHub/GitLab skills to read related PRs and commits
85
- 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await uo(e,n);case"git_list_repos":return mo(e,n);case"git_explore":return fo(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:po(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 uo(r,e){let{url:t,branch:n,shallow:i=!0,name:s}=r;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=s||lo(t.replace(/\.git$/,"")),a=Bt(e,Mt);oo(a,{recursive:!0});let c=V(a,o),d=t,l=process.env.GITHUB_TOKEN,p=process.env.GITLAB_TOKEN,u=process.env.GITLAB_URL;if(t.includes("github.com")&&l)d=t.replace("https://github.com",`https://x-access-token:${l}@github.com`);else if(p&&u)try{let h=new URL(u).host;t.includes(h)&&(d=t.replace(`https://${h}`,`https://oauth2:${p}@${h}`))}catch{}if(Z(V(c,".git"))){let h=n?`git -C "${c}" fetch "${d}" ${n} && git -C "${c}" checkout ${n} && git -C "${c}" merge --ff-only FETCH_HEAD`:`git -C "${c}" pull "${d}"`;await ct(h,e);let y=await ct(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:n||"default",head:y})}let m=["git","clone"];i&&m.push("--depth","1"),n&&m.push("--branch",n),m.push(`"${d}"`,`"${c}"`),await ct(m.join(" "),e),Fe(so,c,t,l||p,"git_checkout");let f=await ct(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:n||"default",shallow:i,head:f})}function mo(r,e){let t=Bt(e,Mt);if(!Z(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let i of Dr(t,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=V(t,i.name);if(!Z(V(s,".git")))continue;let o=ao(s);n.push({name:i.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:t})}function fo(r,e){let{repo:t,depth:n=2}=r,i=Bt(e,Mt,t);if(!Z(i))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let s={repo:t,path:i},o=V(i,"package.json");if(Z(o))try{let m=JSON.parse(co(o,"utf-8"));s.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?s.framework="React":m.dependencies?.next?s.framework="Next.js":m.dependencies?.vue?s.framework="Vue":m.dependencies?.angular?s.framework="Angular":m.dependencies?.express?s.framework="Express":m.dependencies?.fastify&&(s.framework="Fastify")}catch{}let a=V(i,"pyproject.toml");Z(a)&&(s.language="Python");let c=V(i,"go.mod");Z(c)&&(s.language="Go");let d=V(i,"Cargo.toml");Z(d)&&(s.language="Rust"),Z(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function p(m,f,h){if(h>n)return;let y;try{y=Dr(m,{withFileTypes:!0})}catch{return}let _=y.filter(b=>!b.name.startsWith(".")&&b.name!=="node_modules"&&b.name!=="__pycache__"&&b.name!=="dist"&&b.name!=="build"&&b.name!==".git").sort((b,g)=>b.isDirectory()!==g.isDirectory()?b.isDirectory()?-1:1:b.name.localeCompare(g.name));for(let b of _){let g=b.isDirectory();l.push(`${f}${g?"\u{1F4C1}":"\u{1F4C4}"} ${b.name}`),g&&h<n&&p(V(m,b.name),`${f} `,h+1)}}p(i,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let u=["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 s.keyFilesFound=u.filter(m=>Z(V(i,m))),JSON.stringify(s)}function bo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=yo(go(import.meta.url)),e=_o(r,"..","bin","mcp-skill.mjs");return ho(e)?e:null}async function N(r,e={}){let{token:t}=await Br("github"),n=r.startsWith("https://")?r:`https://api.github.com${r}`,i={Authorization:`Bearer ${t}`,Accept:e.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`)}return e.raw?s.text():s.json()}var Ee={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)
85
+ 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await ko(e,n);case"git_list_repos":return wo(e,n);case"git_explore":return So(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:bo(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 ko(r,e){let{url:t,branch:n,shallow:i=!0,name:s}=r;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=s||_o(t.replace(/\.git$/,"")),a=Ft(e,Gt);ho(a,{recursive:!0});let c=V(a,o),d=t,l=process.env.GITHUB_TOKEN,p=process.env.GITLAB_TOKEN,u=process.env.GITLAB_URL;if(t.includes("github.com")&&l)d=t.replace("https://github.com",`https://x-access-token:${l}@github.com`);else if(p&&u)try{let h=new URL(u).host;t.includes(h)&&(d=t.replace(`https://${h}`,`https://oauth2:${p}@${h}`))}catch{}if(Z(V(c,".git"))){let h=n?`git -C "${c}" fetch "${d}" ${n} && git -C "${c}" checkout ${n} && git -C "${c}" merge --ff-only FETCH_HEAD`:`git -C "${c}" pull "${d}"`;await ct(h,e);let g=await ct(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:n||"default",head:g})}let m=["git","clone"];i&&m.push("--depth","1"),n&&m.push("--branch",n),m.push(`"${d}"`,`"${c}"`),await ct(m.join(" "),e),Fe(fo,c,t,l||p,"git_checkout");let f=await ct(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:n||"default",shallow:i,head:f})}function wo(r,e){let t=Ft(e,Gt);if(!Z(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let i of Mr(t,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=V(t,i.name);if(!Z(V(s,".git")))continue;let o=yo(s);n.push({name:i.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:t})}function So(r,e){let{repo:t,depth:n=2}=r,i=Ft(e,Gt,t);if(!Z(i))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let s={repo:t,path:i},o=V(i,"package.json");if(Z(o))try{let m=JSON.parse(go(o,"utf-8"));s.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?s.framework="React":m.dependencies?.next?s.framework="Next.js":m.dependencies?.vue?s.framework="Vue":m.dependencies?.angular?s.framework="Angular":m.dependencies?.express?s.framework="Express":m.dependencies?.fastify&&(s.framework="Fastify")}catch{}let a=V(i,"pyproject.toml");Z(a)&&(s.language="Python");let c=V(i,"go.mod");Z(c)&&(s.language="Go");let d=V(i,"Cargo.toml");Z(d)&&(s.language="Rust"),Z(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function p(m,f,h){if(h>n)return;let g;try{g=Mr(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 _){let y=b.isDirectory();l.push(`${f}${y?"\u{1F4C1}":"\u{1F4C4}"} ${b.name}`),y&&h<n&&p(V(m,b.name),`${f} `,h+1)}}p(i,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let u=["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 s.keyFilesFound=u.filter(m=>Z(V(i,m))),JSON.stringify(s)}function To(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=No(Io(import.meta.url)),e=Oo(r,"..","bin","mcp-skill.mjs");return vo(e)?e:null}async function N(r,e={}){let{token:t}=await Fr("github"),n=r.startsWith("https://")?r:`https://api.github.com${r}`,i={Authorization:`Bearer ${t}`,Accept:e.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`)}return e.raw?s.text():s.json()}var Ee={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)
86
86
  You have access to the user's GitHub repositories. Available tools:
87
87
 
88
88
  ### Discovery
@@ -125,9 +125,9 @@ When user says "check out repo-name" or "clone repo-name":
125
125
  3. STOP. Do not offer to inspect files or ask what to do next.
126
126
 
127
127
  When user just wants to "look at" or "read" files (not clone):
128
- - Use github_get_file to read individual files via API`,resolve(){let r=bo();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/github.js","githubSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"github_search_issues":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let n=await N(`/search/issues?q=${encodeURIComponent(t)}&per_page=${e.limit||20}`),i=(n.items||[]).map(s=>({number:s.number,title:s.title,state:s.state,repo:s.repository_url?.split("/").slice(-2).join("/"),url:s.html_url,user:s.user?.login,isPR:!!s.pull_request,labels:(s.labels||[]).map(o=>o.name),createdAt:s.created_at}));return JSON.stringify({total:n.total_count,items:i})}case"github_search_code":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let n=e.repo?`+repo:${e.repo}`:"",i=e.language?`+language:${e.language}`:"",s=await N(`/search/code?q=${encodeURIComponent(t)}${n}${i}&per_page=${e.limit||15}`),o=(s.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:s.total_count,items:o})}case"github_get_pr":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/pulls/${i}`);return JSON.stringify({number:s.number,title:s.title,state:s.state,merged:s.merged,body:s.body?.slice(0,5e3),user:s.user?.login,branch:s.head?.ref,headSha:s.head?.sha,base:s.base?.ref,changedFiles:s.changed_files,additions:s.additions,deletions:s.deletions,createdAt:s.created_at,mergedAt:s.merged_at,url:s.html_url,labels:(s.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=s.length>15e3;return JSON.stringify({number:i,diff:o?s.slice(0,15e3):s,truncated:o,totalLength:s.length})}case"github_list_pr_files":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:s.length,files:s.map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/pulls/${i}/comments?per_page=50`),o=await N(`/repos/${t}/${n}/issues/${i}/comments?per_page=50`),a=[...s.map(c=>({type:"review",user:c.user?.login,body:c.body?.slice(0,1e3),path:c.path,line:c.line,createdAt:c.created_at})),...o.map(c=>({type:"issue",user:c.user?.login,body:c.body?.slice(0,1e3),createdAt:c.created_at}))].sort((c,d)=>new Date(c.createdAt)-new Date(d.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:t,repo:n,number:i,commentId:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await N(`/repos/${t}/${n}/pulls/comments/${s}`),a=o.in_reply_to_id||o.id,c=[];try{c=await N(`/repos/${t}/${n}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let d=c.filter(u=>u.id===a||u.in_reply_to_id===a).sort((u,m)=>new Date(u.created_at)-new Date(m.created_at)),l=d.length?d:[o],p=l.find(u=>u.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:l.map(u=>({id:u.id,user:u.user?.login,body:(u.body||"").slice(0,4e3),createdAt:u.created_at,isRoot:u.id===a,url:u.html_url}))})}case"github_reply_review_thread":{let{owner:t,repo:n,number:i,commentId:s,body:o}=e||{};if(!t||!n||!i||!s||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await N(`/repos/${t}/${n}/pulls/${i}/comments/${s}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:t,repo:n,number:i,body:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${t}/${n}/issues/${i}/comments`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:t,repo:n,number:i,body:s,event:o,comments:a}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let c=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(c))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let d=Array.isArray(a)?a.filter(u=>u&&u.path&&u.body&&(u.line!=null||u.position!=null)).map(u=>{let m={path:u.path,body:String(u.body)};return u.line!=null?(m.line=Number(u.line),m.side=u.side==="LEFT"?"LEFT":"RIGHT"):m.position=Number(u.position),m}):[];if(c!=="APPROVE"&&!s&&d.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l={event:c};s&&(l.body=String(s)),d.length>0&&(l.comments=d);let p=await N(`/repos/${t}/${n}/pulls/${i}/reviews`,{method:"POST",body:l});return JSON.stringify({ok:!0,id:p.id,state:p.state,event:c,commentsPosted:d.length,url:p.html_url})}case"github_list_commits":{let{owner:t,repo:n,branch:i,path:s,limit:o}=e;if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let a=`/repos/${t}/${n}/commits?per_page=${o||20}`;i&&(a+=`&sha=${encodeURIComponent(i)}`),s&&(a+=`&path=${encodeURIComponent(s)}`);let c=await N(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:t,repo:n,sha:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let s=await N(`/repos/${t}/${n}/commits/${i}`);return JSON.stringify({sha:s.sha?.slice(0,8),message:s.commit?.message,author:s.commit?.author?.name,date:s.commit?.author?.date,stats:s.stats,files:(s.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:t,repo:n,path:i,ref:s}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${t}/${n}/contents/${encodeURIComponent(i)}`;s&&(o+=`?ref=${encodeURIComponent(s)}`);let a=await N(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:i,entries:a.map(l=>({name:l.name,type:l.type,size:l.size,path:l.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),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 t=await N("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let n=t.repositories[0],i=n.owner.login,s=n.owner.type,o=s==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await N(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:s,isOrg:s==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(t){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${t.message})`})}case"github_list_orgs":try{let n=(await N("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of n)o.owner.type==="Organization"&&(i.has(o.owner.login)||i.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let s=Array.from(i.values());return JSON.stringify({count:s.length,orgs:s,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(t){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${t.message}`})}case"github_clone":{let f=function(b){let g=b.replace(/^~(?=$|\/|\\)/,m);return a(g)},{owner:t,repo:n,destination:i}=e;if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let{execSync:s}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:d}=await import("fs"),{homedir:l,platform:p}=await import("os"),{token:u}=await Br("github"),m=l(),h=i?f(i):o(m,"zibby-repos"),y=o(h,n);if(d(h,{recursive:!0}),c(y))return JSON.stringify({error:`Directory ${y} already exists. Remove it first or use a different destination.`,existingPath:y});let _=`https://x-access-token:${u}@github.com/${t}/${n}.git`;try{s(`git clone ${_} "${y}"`,{stdio:"pipe"});let b=`https://github.com/${t}/${n}.git`;Fe(s,y,b,u,"github_clone");let g=p()==="win32",k;return g?k=s(`dir "${y}"`,{encoding:"utf-8",shell:"cmd.exe"}):k=s(`ls -la "${y}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:y,message:`Cloned ${t}/${n} to ${y}`,contents:k.split(`
128
+ - Use github_get_file to read individual files via API`,resolve(){let r=To();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/github.js","githubSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"github_search_issues":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let n=await N(`/search/issues?q=${encodeURIComponent(t)}&per_page=${e.limit||20}`),i=(n.items||[]).map(s=>({number:s.number,title:s.title,state:s.state,repo:s.repository_url?.split("/").slice(-2).join("/"),url:s.html_url,user:s.user?.login,isPR:!!s.pull_request,labels:(s.labels||[]).map(o=>o.name),createdAt:s.created_at}));return JSON.stringify({total:n.total_count,items:i})}case"github_search_code":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let n=e.repo?`+repo:${e.repo}`:"",i=e.language?`+language:${e.language}`:"",s=await N(`/search/code?q=${encodeURIComponent(t)}${n}${i}&per_page=${e.limit||15}`),o=(s.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:s.total_count,items:o})}case"github_get_pr":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/pulls/${i}`);return JSON.stringify({number:s.number,title:s.title,state:s.state,merged:s.merged,body:s.body?.slice(0,5e3),user:s.user?.login,branch:s.head?.ref,headSha:s.head?.sha,base:s.base?.ref,changedFiles:s.changed_files,additions:s.additions,deletions:s.deletions,createdAt:s.created_at,mergedAt:s.merged_at,url:s.html_url,labels:(s.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=s.length>15e3;return JSON.stringify({number:i,diff:o?s.slice(0,15e3):s,truncated:o,totalLength:s.length})}case"github_list_pr_files":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:s.length,files:s.map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/pulls/${i}/comments?per_page=50`),o=await N(`/repos/${t}/${n}/issues/${i}/comments?per_page=50`),a=[...s.map(c=>({type:"review",user:c.user?.login,body:c.body?.slice(0,1e3),path:c.path,line:c.line,createdAt:c.created_at})),...o.map(c=>({type:"issue",user:c.user?.login,body:c.body?.slice(0,1e3),createdAt:c.created_at}))].sort((c,d)=>new Date(c.createdAt)-new Date(d.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:t,repo:n,number:i,commentId:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await N(`/repos/${t}/${n}/pulls/comments/${s}`),a=o.in_reply_to_id||o.id,c=[];try{c=await N(`/repos/${t}/${n}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let d=c.filter(u=>u.id===a||u.in_reply_to_id===a).sort((u,m)=>new Date(u.created_at)-new Date(m.created_at)),l=d.length?d:[o],p=l.find(u=>u.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:l.map(u=>({id:u.id,user:u.user?.login,body:(u.body||"").slice(0,4e3),createdAt:u.created_at,isRoot:u.id===a,url:u.html_url}))})}case"github_reply_review_thread":{let{owner:t,repo:n,number:i,commentId:s,body:o}=e||{};if(!t||!n||!i||!s||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await N(`/repos/${t}/${n}/pulls/${i}/comments/${s}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:t,repo:n,number:i,body:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${t}/${n}/issues/${i}/comments`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:t,repo:n,number:i,body:s,event:o,comments:a}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let c=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(c))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let d=Array.isArray(a)?a.filter(u=>u&&u.path&&u.body&&(u.line!=null||u.position!=null)).map(u=>{let m={path:u.path,body:String(u.body)};return u.line!=null?(m.line=Number(u.line),m.side=u.side==="LEFT"?"LEFT":"RIGHT"):m.position=Number(u.position),m}):[];if(c!=="APPROVE"&&!s&&d.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l={event:c};s&&(l.body=String(s)),d.length>0&&(l.comments=d);let p=await N(`/repos/${t}/${n}/pulls/${i}/reviews`,{method:"POST",body:l});return JSON.stringify({ok:!0,id:p.id,state:p.state,event:c,commentsPosted:d.length,url:p.html_url})}case"github_list_commits":{let{owner:t,repo:n,branch:i,path:s,limit:o}=e;if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let a=`/repos/${t}/${n}/commits?per_page=${o||20}`;i&&(a+=`&sha=${encodeURIComponent(i)}`),s&&(a+=`&path=${encodeURIComponent(s)}`);let c=await N(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:t,repo:n,sha:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let s=await N(`/repos/${t}/${n}/commits/${i}`);return JSON.stringify({sha:s.sha?.slice(0,8),message:s.commit?.message,author:s.commit?.author?.name,date:s.commit?.author?.date,stats:s.stats,files:(s.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:t,repo:n,path:i,ref:s}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${t}/${n}/contents/${encodeURIComponent(i)}`;s&&(o+=`?ref=${encodeURIComponent(s)}`);let a=await N(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:i,entries:a.map(l=>({name:l.name,type:l.type,size:l.size,path:l.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),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 t=await N("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let n=t.repositories[0],i=n.owner.login,s=n.owner.type,o=s==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await N(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:s,isOrg:s==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(t){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${t.message})`})}case"github_list_orgs":try{let n=(await N("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of n)o.owner.type==="Organization"&&(i.has(o.owner.login)||i.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let s=Array.from(i.values());return JSON.stringify({count:s.length,orgs:s,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(t){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${t.message}`})}case"github_clone":{let f=function(b){let y=b.replace(/^~(?=$|\/|\\)/,m);return a(y)},{owner:t,repo:n,destination:i}=e;if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let{execSync:s}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:d}=await import("fs"),{homedir:l,platform:p}=await import("os"),{token:u}=await Fr("github"),m=l(),h=i?f(i):o(m,"zibby-repos"),g=o(h,n);if(d(h,{recursive:!0}),c(g))return JSON.stringify({error:`Directory ${g} already exists. Remove it first or use a different destination.`,existingPath:g});let _=`https://x-access-token:${u}@github.com/${t}/${n}.git`;try{s(`git clone ${_} "${g}"`,{stdio:"pipe"});let b=`https://github.com/${t}/${n}.git`;Fe(s,g,b,u,"github_clone");let y=p()==="win32",k;return y?k=s(`dir "${g}"`,{encoding:"utf-8",shell:"cmd.exe"}):k=s(`ls -la "${g}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:g,message:`Cloned ${t}/${n} to ${g}`,contents:k.split(`
129
129
  `).slice(0,30).join(`
130
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(b){let k=String(b.message||b).split(u).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${k}`})}}case"github_search_repos":{let{query:t,limit:n}=e;if(!t)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),s=JSON.parse(i);if(s.error)return JSON.stringify(s);let o=t.toLowerCase(),a=s.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:t,count:a.length,repos:a.slice(0,n||20)})}case"github_list_repos":{let{owner:t,type:n,sort:i,direction:s,limit:o,query:a}=e,c=100,d=o||200,l=[],p=g=>({name:g.name,fullName:g.full_name,private:g.private,description:g.description,language:g.language,defaultBranch:g.default_branch,updatedAt:g.updated_at,stars:g.stargazers_count,url:g.html_url,fullPath:g.full_name,webUrl:g.html_url,visibility:g.visibility||(g.private?"private":"public")}),u=g=>{if(!a)return!0;let k=String(a).toLowerCase();return g.name&&g.name.toLowerCase().includes(k)||g.fullName&&g.fullName.toLowerCase().includes(k)||g.description&&g.description.toLowerCase().includes(k)};if(!t){let g=1,k=!0;for(;k&&l.length<d;){let D=`/installation/repositories?per_page=${c}&page=${g}`,ye=(await N(D)).repositories||[];if(ye.length===0)break;l=l.concat(ye),k=ye.length===c,g++}let R=l.map(p).filter(u),K=R.slice(0,d),Te=R.length>K.length,T=K.filter(D=>D.private).length,O=K.filter(D=>!D.private).length;return JSON.stringify({count:K.length,repos:K,truncated:Te,privateCount:T,publicCount:O,message:`Found ${T} private and ${O} public repos`})}let m=await N(`/orgs/${t}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&l.length<d;){let g;m?g=`/orgs/${t}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:g=`/users/${t}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let k=await N(g),R=Array.isArray(k)?k:[];if(R.length===0)break;l=l.concat(R),h=R.length===c,f++}let y=l.map(p).filter(u),_=y.slice(0,d),b=y.length>_.length;return JSON.stringify({count:_.length,repos:_,truncated:b})}case"github_create_pr":{let{owner:t,repo:n,head:i,title:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=e.base;if(!o)try{o=(await N(`/repos/${t}/${n}`)).default_branch||"main"}catch{o="main"}let a={title:String(s),head:String(i),base:String(o),body:e.body?String(e.body):"",draft:!!e.draft};try{let c=await N(`/repos/${t}/${n}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${t}/${n}`,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:i,base:o,repo:`${t}/${n}`,provider:"github",skippedReason:d});throw c}}case"github_merge_pr":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=e.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(s))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${s})`});let o={merge_method:s};e.commitTitle&&(o.commit_title=String(e.commitTitle)),e.commitMessage&&(o.commit_message=String(e.commitMessage));try{let a=await N(`/repos/${t}/${n}/pulls/${i}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:i,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:t,repo:n,title:i,body:s}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await N(`/repos/${t}/${n}/issues`,{method:"POST",body:{title:i,body:s||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:t,repo:n,state:i,labels:s,since:o,assignee:a,sort:c,direction:d,limit:l}=e||{};if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",i||"open"),p.set("per_page",String(l||30)),p.set("sort",c||"updated"),p.set("direction",d||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),o&&p.set("since",o),a&&p.set("assignee",a);let u=await N(`/repos/${t}/${n}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).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:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/issues/${i}`);return s.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:s.number,title:s.title,body:s.body||"",state:s.state,stateReason:s.state_reason||null,labels:(s.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:s.assignee?.login||null,assignees:(s.assignees||[]).map(o=>o.login),user:s.user?.login,milestone:s.milestone?.title||null,comments:s.comments,url:s.html_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:n,number:i,limit:s}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await N(`/repos/${t}/${n}/issues/${i}/comments?per_page=${s||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:t,repo:n,number:i,body:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${t}/${n}/issues/${i}/comments`,{method:"POST",body:{body:s}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:t,repo:n,number:i,stateReason:s}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};s&&(o.state_reason=s);let a=await N(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:s.number,state:s.state,url:s.html_url})}case"github_label_issue":{let{owner:t,repo:n,number:i,labels:s,mode:o}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(s)?s:s?[s]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await N(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await N(`/repos/${t}/${n}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await N(`/repos/${t}/${n}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let d=await N(`/repos/${t}/${n}/issues/${i}/labels`,{method:"POST",body:{labels:a}});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: ${r}`})}}catch(t){return JSON.stringify({error:t.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 ko}from"fs";import{fileURLToPath as wo}from"url";import{dirname as So,resolve as Io}from"path";function vo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=So(wo(import.meta.url)),e=Io(r,"..","bin","mcp-skill.mjs");return ko(e)?e:null}function No(){let r=process.env.GITLAB_API_URL;if(r)return r.replace(/\/+$/,"");let e=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(e)?e:`${e}/api/v4`}function Oo(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let r=process.env.GITLAB_TOKEN;if(!r)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":r}}async function j(r,e={}){let t=/^https?:\/\//.test(r)?r:`${No()}${r}`,n={Accept:"application/json","User-Agent":"Zibby-App",...Oo(),...e.body?{"Content-Type":"application/json"}:{}},i=await fetch(t,{method:e.method||"GET",headers:n,body:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`GitLab API ${i.status}: ${s.slice(0,300)}`)}return e.raw?i.text():i.json()}function Mr(){let r=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(r?r.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Ro(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function P(r){let e=String(r);return/^\d+$/.test(e)?e:encodeURIComponent(e)}var je={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)
130
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(b){let k=String(b.message||b).split(u).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${k}`})}}case"github_search_repos":{let{query:t,limit:n}=e;if(!t)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),s=JSON.parse(i);if(s.error)return JSON.stringify(s);let o=t.toLowerCase(),a=s.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:t,count:a.length,repos:a.slice(0,n||20)})}case"github_list_repos":{let{owner:t,type:n,sort:i,direction:s,limit:o,query:a}=e,c=100,d=o||200,l=[],p=y=>({name:y.name,fullName:y.full_name,private:y.private,description:y.description,language:y.language,defaultBranch:y.default_branch,updatedAt:y.updated_at,stars:y.stargazers_count,url:y.html_url,fullPath:y.full_name,webUrl:y.html_url,visibility:y.visibility||(y.private?"private":"public")}),u=y=>{if(!a)return!0;let k=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(k)||y.fullName&&y.fullName.toLowerCase().includes(k)||y.description&&y.description.toLowerCase().includes(k)};if(!t){let y=1,k=!0;for(;k&&l.length<d;){let D=`/installation/repositories?per_page=${c}&page=${y}`,ge=(await N(D)).repositories||[];if(ge.length===0)break;l=l.concat(ge),k=ge.length===c,y++}let T=l.map(p).filter(u),K=T.slice(0,d),Re=T.length>K.length,R=K.filter(D=>D.private).length,O=K.filter(D=>!D.private).length;return JSON.stringify({count:K.length,repos:K,truncated:Re,privateCount:R,publicCount:O,message:`Found ${R} private and ${O} public repos`})}let m=await N(`/orgs/${t}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&l.length<d;){let y;m?y=`/orgs/${t}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:y=`/users/${t}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let k=await N(y),T=Array.isArray(k)?k:[];if(T.length===0)break;l=l.concat(T),h=T.length===c,f++}let g=l.map(p).filter(u),_=g.slice(0,d),b=g.length>_.length;return JSON.stringify({count:_.length,repos:_,truncated:b})}case"github_create_pr":{let{owner:t,repo:n,head:i,title:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=e.base;if(!o)try{o=(await N(`/repos/${t}/${n}`)).default_branch||"main"}catch{o="main"}let a={title:String(s),head:String(i),base:String(o),body:e.body?String(e.body):"",draft:!!e.draft};try{let c=await N(`/repos/${t}/${n}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${t}/${n}`,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:i,base:o,repo:`${t}/${n}`,provider:"github",skippedReason:d});throw c}}case"github_merge_pr":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=e.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(s))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${s})`});let o={merge_method:s};e.commitTitle&&(o.commit_title=String(e.commitTitle)),e.commitMessage&&(o.commit_message=String(e.commitMessage));try{let a=await N(`/repos/${t}/${n}/pulls/${i}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:i,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:t,repo:n,title:i,body:s}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await N(`/repos/${t}/${n}/issues`,{method:"POST",body:{title:i,body:s||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:t,repo:n,state:i,labels:s,since:o,assignee:a,sort:c,direction:d,limit:l}=e||{};if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",i||"open"),p.set("per_page",String(l||30)),p.set("sort",c||"updated"),p.set("direction",d||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),o&&p.set("since",o),a&&p.set("assignee",a);let u=await N(`/repos/${t}/${n}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).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:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/issues/${i}`);return s.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:s.number,title:s.title,body:s.body||"",state:s.state,stateReason:s.state_reason||null,labels:(s.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:s.assignee?.login||null,assignees:(s.assignees||[]).map(o=>o.login),user:s.user?.login,milestone:s.milestone?.title||null,comments:s.comments,url:s.html_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:n,number:i,limit:s}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await N(`/repos/${t}/${n}/issues/${i}/comments?per_page=${s||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:t,repo:n,number:i,body:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${t}/${n}/issues/${i}/comments`,{method:"POST",body:{body:s}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:t,repo:n,number:i,stateReason:s}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};s&&(o.state_reason=s);let a=await N(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:s.number,state:s.state,url:s.html_url})}case"github_label_issue":{let{owner:t,repo:n,number:i,labels:s,mode:o}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(s)?s:s?[s]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await N(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await N(`/repos/${t}/${n}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await N(`/repos/${t}/${n}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let d=await N(`/repos/${t}/${n}/issues/${i}/labels`,{method:"POST",body:{labels:a}});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: ${r}`})}}catch(t){return JSON.stringify({error:t.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 Ro}from"fs";import{fileURLToPath as Ao}from"url";import{dirname as xo,resolve as Eo}from"path";function jo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=xo(Ao(import.meta.url)),e=Eo(r,"..","bin","mcp-skill.mjs");return Ro(e)?e:null}function Lo(){let r=process.env.GITLAB_API_URL;if(r)return r.replace(/\/+$/,"");let e=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(e)?e:`${e}/api/v4`}function $o(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let r=process.env.GITLAB_TOKEN;if(!r)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":r}}async function j(r,e={}){let t=/^https?:\/\//.test(r)?r:`${Lo()}${r}`,n={Accept:"application/json","User-Agent":"Zibby-App",...$o(),...e.body?{"Content-Type":"application/json"}:{}},i=await fetch(t,{method:e.method||"GET",headers:n,body:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`GitLab API ${i.status}: ${s.slice(0,300)}`)}return e.raw?i.text():i.json()}function Gr(){let r=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(r?r.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Po(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function P(r){let e=String(r);return/^\d+$/.test(e)?e:encodeURIComponent(e)}var je={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)
131
131
  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:
132
132
 
133
133
  ### Discovery
@@ -153,9 +153,9 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
153
153
 
154
154
  ### Notes
155
155
  - 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.
156
- - 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 r=vo();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/gitlab.js","gitlabSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gitlab_clone":{let{projectPath:t,projectId:n,destination:i,branch:s}=e||{},o=t&&String(t).trim();if(!o&&n!=null&&(/^\d+$/.test(String(n))?o=(await j(`/projects/${P(n)}`))?.path_with_namespace:o=String(n).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=Ro();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:p,mkdirSync:u}=await import("fs"),m=i?l(i):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(u(m,{recursive:!0}),p(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let y=Mr().replace(/^https?:\/\//,""),_=Mr().startsWith("http://")?"http":"https",b=`${_}://oauth2:${a}@${y}/${o}.git`,g=s?`--branch "${String(s).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${g}${b} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let k=`${_}://${y}/${o}.git`;Fe(c,h,k,a,"gitlab_clone");let R=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:R.split(`
156
+ - 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 r=jo();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/gitlab.js","gitlabSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gitlab_clone":{let{projectPath:t,projectId:n,destination:i,branch:s}=e||{},o=t&&String(t).trim();if(!o&&n!=null&&(/^\d+$/.test(String(n))?o=(await j(`/projects/${P(n)}`))?.path_with_namespace:o=String(n).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=Po();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:p,mkdirSync:u}=await import("fs"),m=i?l(i):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(u(m,{recursive:!0}),p(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let g=Gr().replace(/^https?:\/\//,""),_=Gr().startsWith("http://")?"http":"https",b=`${_}://oauth2:${a}@${g}/${o}.git`,y=s?`--branch "${String(s).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${y}${b} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let k=`${_}://${g}/${o}.git`;Fe(c,h,k,a,"gitlab_clone");let T=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:T.split(`
157
157
  `).slice(0,30).join(`
158
- `)})}catch(k){let R=String(k.message||k).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${R}`})}}case"gitlab_create_mr":{let t=e?.project??e?.projectId,n=e?.source_branch??e?.sourceBranch,{title:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let s=P(t),o=e?.target_branch??e?.targetBranch;if(!o)try{o=(await j(`/projects/${s}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(n),target_branch:String(o),title:String(i),description:e?.description?String(e.description):""};try{let c=await j(`/projects/${s}/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(t),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(t),provider:"gitlab",skippedReason:d});throw c}}case"gitlab_accept_mr":{let t=e?.project??e?.projectId,{iid:n}=e||{};if(!t||!n)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let i=P(t),s={};e.squash!=null&&(s.squash=!!e.squash),e.mergeCommitMessage&&(s.merge_commit_message=String(e.mergeCommitMessage)),e.mergeWhenPipelineSucceeds!=null&&(s.merge_when_pipeline_succeeds=!!e.mergeWhenPipelineSucceeds);try{let o=await j(`/projects/${i}/merge_requests/${n}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??n,project:String(t),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:n,project:String(t),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await j(`/projects/${P(t)}/merge_requests/${n}`);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:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await j(`/projects/${P(t)}/merge_requests/${n}/changes`),s=Array.isArray(i.changes)?i.changes:[];return JSON.stringify({iid:i.iid,total:s.length,diffRefs:i.diff_refs||null,files:s.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:t,state:n,targetBranch:i,sourceBranch:s,authorUsername:o,labels:a,search:c,sort:d,orderBy:l,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||20)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("target_branch",i),s&&u.set("source_branch",s),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await j(`/projects/${P(t)}/merge_requests?${u.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:t,iid:n,limit:i}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await j(`/projects/${P(t)}/merge_requests/${n}/notes?per_page=${i||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(s)?s.length:0,notes:(Array.isArray(s)?s:[]).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:t,iid:n,body:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await j(`/projects/${P(t)}/merge_requests/${n}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:n,path:i,oldPath:s,newLine:o,oldLine:a,body:c}=e||{};if(!t||!n||!i||!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=P(t),l=e.diffRefs||null;if(l||(l=(await j(`/projects/${d}/merge_requests/${n}`)).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 p={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:i,old_path:s||i};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await j(`/projects/${d}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(c),position:p}});return JSON.stringify({ok:!0,discussionId:u.id})}catch(u){return JSON.stringify({ok:!1,error:`inline anchor rejected (${u.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:t,iid:n,body:i,comments:s}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let o=P(t),a=Array.isArray(s)?s.filter(u=>u&&u.path&&u.body&&(u.newLine!=null||u.oldLine!=null)):[];if(!i&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=e.diffRefs||null;a.length>0&&!c&&(c=(await j(`/projects/${o}/merge_requests/${n}`)).diff_refs||null);let d=!1;i&&(await j(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:String(i)}}),d=!0);let l=0,p=[];if(a.length>0&&c)for(let u of a){let m={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:u.path,old_path:u.oldPath||u.path};u.newLine!=null&&(m.new_line=Number(u.newLine)),u.oldLine!=null&&(m.old_line=Number(u.oldLine));try{await j(`/projects/${o}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(u.body),position:m}}),l+=1}catch(f){p.push(`${u.path}:${u.newLine??u.oldLine} \u2014 ${f.message}`)}}else a.length>0&&!c&&p.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:p.length?p:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:n,discussionId:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let s=await j(`/projects/${P(t)}/merge_requests/${n}/discussions/${encodeURIComponent(i)}`),o=Array.isArray(s.notes)?s.notes:[],a=o.find(d=>d.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:s.id,individualNote:!!s.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:t,iid:n,discussionId:i,body:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await j(`/projects/${P(t)}/merge_requests/${n}/discussions/${encodeURIComponent(i)}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:t,limit:n}=e||{},i=Math.min(Number(n)>0?Number(n):50,200),s=new URLSearchParams;s.set("membership","true"),s.set("simple","true"),s.set("order_by","last_activity_at"),s.set("sort","desc"),s.set("per_page",String(Math.min(i+1,100))),t&&s.set("search",String(t));let o=await j(`/projects?${s.toString()}`),a=Array.isArray(o)?o:[],c=a.length>i,d=a.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:c,projects:d})}case"gitlab_list_issues":{let{projectId:t,state:n,labels:i,assigneeUsername:s,authorUsername:o,updatedAfter:a,search:c,sort:d,orderBy:l,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||30)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("labels",Array.isArray(i)?i.join(","):i),s&&u.set("assignee_username",s),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await j(`/projects/${P(t)}/issues?${u.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(y=>y.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:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await j(`/projects/${P(t)}/issues/${n}`);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(s=>s.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:t,iid:n,body:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await j(`/projects/${P(t)}/issues/${n}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 To}from"fs";import{fileURLToPath as Ao}from"url";import{dirname as xo,resolve as Eo}from"path";import{resolveIntegrationToken as jo}from"@zibby/core/backend-client.js";function Lo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=xo(Ao(import.meta.url)),e=Eo(r,"..","bin","mcp-skill.mjs");return To(e)?e:null}async function z(r,e={}){let{token:t}=await jo("figma"),n=r.startsWith("https://")?r:`https://api.figma.com${r}`,i={"X-Figma-Token":t,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Figma API ${s.status}: ${o.slice(0,300)}`)}return s.json()}function oe(r){let e=String(r||"").trim(),t=e.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return t?t[1]:e}function lt(r){return r==null?void 0:(Array.isArray(r)?r:String(r).split(",")).map(t=>String(t).trim().replace(/-/g,":")).filter(Boolean).join(",")}function $o(r){let e=String(r||"").match(/[?&]node-id=([^&]+)/i);return e?decodeURIComponent(e[1]).replace(/-/g,":"):void 0}var Q=r=>typeof r=="number"?Math.round(r*100)/100:r;function Ft(r){if(!r)return null;let e=n=>Math.round((n??0)*255).toString(16).padStart(2,"0"),t={hex:`#${e(r.r)}${e(r.g)}${e(r.b)}`.toUpperCase()};return r.a!=null&&r.a<1&&(t.opacity=Q(r.a)),t}function Fr(r){return!r||r.visible===!1?null:r.type==="SOLID"?{type:"SOLID",...Ft(r.color),...r.opacity!=null?{opacity:r.opacity}:{}}:{type:r.type,...r.opacity!=null?{opacity:r.opacity}:{},...r.gradientStops?{stops:r.gradientStops.map(e=>({position:Q(e.position),...Ft(e.color)}))}:{}}}function Gr(r,e){let t=r.absoluteBoundingBox,n={id:r.id,name:r.name,type:r.type};t&&(n.size={w:Q(t.width),h:Q(t.height)},n.position={x:Q(t.x),y:Q(t.y)}),r.opacity!=null&&r.opacity!==1&&(n.opacity=r.opacity),r.cornerRadius!=null&&(n.cornerRadius=r.cornerRadius),Array.isArray(r.rectangleCornerRadii)&&(n.cornerRadii=r.rectangleCornerRadii);let i=(r.fills||[]).map(Fr).filter(Boolean);i.length&&(n.fills=i);let s=(r.strokes||[]).map(Fr).filter(Boolean);s.length&&(n.strokes=s,r.strokeWeight!=null&&(n.strokeWeight=r.strokeWeight));let o=(r.effects||[]).filter(a=>a.visible!==!1).map(a=>({type:a.type,...a.radius!=null?{radius:a.radius}:{},...a.offset?{offset:{x:Q(a.offset.x),y:Q(a.offset.y)}}:{},...a.spread?{spread:a.spread}:{},...a.color?Ft(a.color):{}}));if(o.length&&(n.effects=o),r.layoutMode&&r.layoutMode!=="NONE"&&(n.autoLayout={direction:r.layoutMode,padding:{l:r.paddingLeft??0,r:r.paddingRight??0,t:r.paddingTop??0,b:r.paddingBottom??0},gap:r.itemSpacing??0,align:{primary:r.primaryAxisAlignItems,counter:r.counterAxisAlignItems}}),r.type==="TEXT"){let a=r.style||{};n.text=r.characters,n.textStyle={fontFamily:a.fontFamily,fontWeight:a.fontWeight,fontSize:a.fontSize,lineHeightPx:a.lineHeightPx!=null?Q(a.lineHeightPx):void 0,letterSpacing:a.letterSpacing!=null?Q(a.letterSpacing):void 0,align:a.textAlignHorizontal,case:a.textCase}}return e>0&&Array.isArray(r.children)&&r.children.length&&(n.children=r.children.map(a=>Gr(a,e-1))),n}var Kr={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:v.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma (connected)
158
+ `)})}catch(k){let T=String(k.message||k).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${T}`})}}case"gitlab_create_mr":{let t=e?.project??e?.projectId,n=e?.source_branch??e?.sourceBranch,{title:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let s=P(t),o=e?.target_branch??e?.targetBranch;if(!o)try{o=(await j(`/projects/${s}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(n),target_branch:String(o),title:String(i),description:e?.description?String(e.description):""};try{let c=await j(`/projects/${s}/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(t),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(t),provider:"gitlab",skippedReason:d});throw c}}case"gitlab_accept_mr":{let t=e?.project??e?.projectId,{iid:n}=e||{};if(!t||!n)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let i=P(t),s={};e.squash!=null&&(s.squash=!!e.squash),e.mergeCommitMessage&&(s.merge_commit_message=String(e.mergeCommitMessage)),e.mergeWhenPipelineSucceeds!=null&&(s.merge_when_pipeline_succeeds=!!e.mergeWhenPipelineSucceeds);try{let o=await j(`/projects/${i}/merge_requests/${n}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??n,project:String(t),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:n,project:String(t),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await j(`/projects/${P(t)}/merge_requests/${n}`);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:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await j(`/projects/${P(t)}/merge_requests/${n}/changes`),s=Array.isArray(i.changes)?i.changes:[];return JSON.stringify({iid:i.iid,total:s.length,diffRefs:i.diff_refs||null,files:s.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:t,state:n,targetBranch:i,sourceBranch:s,authorUsername:o,labels:a,search:c,sort:d,orderBy:l,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||20)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("target_branch",i),s&&u.set("source_branch",s),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await j(`/projects/${P(t)}/merge_requests?${u.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:t,iid:n,limit:i}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await j(`/projects/${P(t)}/merge_requests/${n}/notes?per_page=${i||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(s)?s.length:0,notes:(Array.isArray(s)?s:[]).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:t,iid:n,body:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await j(`/projects/${P(t)}/merge_requests/${n}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:n,path:i,oldPath:s,newLine:o,oldLine:a,body:c}=e||{};if(!t||!n||!i||!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=P(t),l=e.diffRefs||null;if(l||(l=(await j(`/projects/${d}/merge_requests/${n}`)).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 p={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:i,old_path:s||i};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await j(`/projects/${d}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(c),position:p}});return JSON.stringify({ok:!0,discussionId:u.id})}catch(u){return JSON.stringify({ok:!1,error:`inline anchor rejected (${u.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:t,iid:n,body:i,comments:s}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let o=P(t),a=Array.isArray(s)?s.filter(u=>u&&u.path&&u.body&&(u.newLine!=null||u.oldLine!=null)):[];if(!i&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=e.diffRefs||null;a.length>0&&!c&&(c=(await j(`/projects/${o}/merge_requests/${n}`)).diff_refs||null);let d=!1;i&&(await j(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:String(i)}}),d=!0);let l=0,p=[];if(a.length>0&&c)for(let u of a){let m={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:u.path,old_path:u.oldPath||u.path};u.newLine!=null&&(m.new_line=Number(u.newLine)),u.oldLine!=null&&(m.old_line=Number(u.oldLine));try{await j(`/projects/${o}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(u.body),position:m}}),l+=1}catch(f){p.push(`${u.path}:${u.newLine??u.oldLine} \u2014 ${f.message}`)}}else a.length>0&&!c&&p.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:p.length?p:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:n,discussionId:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let s=await j(`/projects/${P(t)}/merge_requests/${n}/discussions/${encodeURIComponent(i)}`),o=Array.isArray(s.notes)?s.notes:[],a=o.find(d=>d.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:s.id,individualNote:!!s.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:t,iid:n,discussionId:i,body:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await j(`/projects/${P(t)}/merge_requests/${n}/discussions/${encodeURIComponent(i)}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:t,limit:n}=e||{},i=Math.min(Number(n)>0?Number(n):50,200),s=new URLSearchParams;s.set("membership","true"),s.set("simple","true"),s.set("order_by","last_activity_at"),s.set("sort","desc"),s.set("per_page",String(Math.min(i+1,100))),t&&s.set("search",String(t));let o=await j(`/projects?${s.toString()}`),a=Array.isArray(o)?o:[],c=a.length>i,d=a.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:c,projects:d})}case"gitlab_list_issues":{let{projectId:t,state:n,labels:i,assigneeUsername:s,authorUsername:o,updatedAfter:a,search:c,sort:d,orderBy:l,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||30)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("labels",Array.isArray(i)?i.join(","):i),s&&u.set("assignee_username",s),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await j(`/projects/${P(t)}/issues?${u.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(g=>g.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:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await j(`/projects/${P(t)}/issues/${n}`);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(s=>s.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:t,iid:n,body:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await j(`/projects/${P(t)}/issues/${n}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 Co}from"fs";import{fileURLToPath as Uo}from"url";import{dirname as Jo,resolve as qo}from"path";import{resolveIntegrationToken as Do}from"@zibby/core/backend-client.js";function Bo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Jo(Uo(import.meta.url)),e=qo(r,"..","bin","mcp-skill.mjs");return Co(e)?e:null}async function z(r,e={}){let{token:t}=await Do("figma"),n=r.startsWith("https://")?r:`https://api.figma.com${r}`,i={"X-Figma-Token":t,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Figma API ${s.status}: ${o.slice(0,300)}`)}return s.json()}function oe(r){let e=String(r||"").trim(),t=e.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return t?t[1]:e}function lt(r){return r==null?void 0:(Array.isArray(r)?r:String(r).split(",")).map(t=>String(t).trim().replace(/-/g,":")).filter(Boolean).join(",")}function Mo(r){let e=String(r||"").match(/[?&]node-id=([^&]+)/i);return e?decodeURIComponent(e[1]).replace(/-/g,":"):void 0}var Q=r=>typeof r=="number"?Math.round(r*100)/100:r;function Kt(r){if(!r)return null;let e=n=>Math.round((n??0)*255).toString(16).padStart(2,"0"),t={hex:`#${e(r.r)}${e(r.g)}${e(r.b)}`.toUpperCase()};return r.a!=null&&r.a<1&&(t.opacity=Q(r.a)),t}function Kr(r){return!r||r.visible===!1?null:r.type==="SOLID"?{type:"SOLID",...Kt(r.color),...r.opacity!=null?{opacity:r.opacity}:{}}:{type:r.type,...r.opacity!=null?{opacity:r.opacity}:{},...r.gradientStops?{stops:r.gradientStops.map(e=>({position:Q(e.position),...Kt(e.color)}))}:{}}}function Hr(r,e){let t=r.absoluteBoundingBox,n={id:r.id,name:r.name,type:r.type};t&&(n.size={w:Q(t.width),h:Q(t.height)},n.position={x:Q(t.x),y:Q(t.y)}),r.opacity!=null&&r.opacity!==1&&(n.opacity=r.opacity),r.cornerRadius!=null&&(n.cornerRadius=r.cornerRadius),Array.isArray(r.rectangleCornerRadii)&&(n.cornerRadii=r.rectangleCornerRadii);let i=(r.fills||[]).map(Kr).filter(Boolean);i.length&&(n.fills=i);let s=(r.strokes||[]).map(Kr).filter(Boolean);s.length&&(n.strokes=s,r.strokeWeight!=null&&(n.strokeWeight=r.strokeWeight));let o=(r.effects||[]).filter(a=>a.visible!==!1).map(a=>({type:a.type,...a.radius!=null?{radius:a.radius}:{},...a.offset?{offset:{x:Q(a.offset.x),y:Q(a.offset.y)}}:{},...a.spread?{spread:a.spread}:{},...a.color?Kt(a.color):{}}));if(o.length&&(n.effects=o),r.layoutMode&&r.layoutMode!=="NONE"&&(n.autoLayout={direction:r.layoutMode,padding:{l:r.paddingLeft??0,r:r.paddingRight??0,t:r.paddingTop??0,b:r.paddingBottom??0},gap:r.itemSpacing??0,align:{primary:r.primaryAxisAlignItems,counter:r.counterAxisAlignItems}}),r.type==="TEXT"){let a=r.style||{};n.text=r.characters,n.textStyle={fontFamily:a.fontFamily,fontWeight:a.fontWeight,fontSize:a.fontSize,lineHeightPx:a.lineHeightPx!=null?Q(a.lineHeightPx):void 0,letterSpacing:a.letterSpacing!=null?Q(a.letterSpacing):void 0,align:a.textAlignHorizontal,case:a.textCase}}return e>0&&Array.isArray(r.children)&&r.children.length&&(n.children=r.children.map(a=>Hr(a,e-1))),n}var zr={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:I.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma (connected)
159
159
  You have access to the user's Figma files via the Figma REST API. Every tool that takes a file accepts EITHER the raw file key OR a full figma.com URL (figma.com/file|design/<key>/...). Node ids accept URL form \`1-23\` or API form \`1:23\` interchangeably. Tools:
160
160
 
161
161
  ### Identity
@@ -186,7 +186,7 @@ You have access to the user's Figma files via the Figma REST API. Every tool tha
186
186
 
187
187
  ### Notes
188
188
  - The file key is NOT the file name \u2014 it's the opaque id segment in the URL (or just paste the URL).
189
- - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes / figma_parse_url output.`,resolve(){let r=Lo();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/figma.js","figmaSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"figma_get_me":{let t=await z("/v1/me");return JSON.stringify({id:t.id,handle:t.handle,email:t.email,imgUrl:t.img_url})}case"figma_get_file":{let t=oe((e||{}).fileKey),{depth:n}=e||{};if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=`/v1/files/${encodeURIComponent(t)}`;if(n!=null){let a=Number(n);!Number.isNaN(a)&&a>0&&(i+=`?depth=${a}`)}let s=await z(i),o=(s.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:s.name,lastModified:s.lastModified,version:s.version,editorType:s.editorType,role:s.role,pages:o})}case"figma_get_nodes":{let t=oe((e||{}).fileKey),{ids:n,depth:i}=e||{};if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=lt(n);if(!s)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=new URLSearchParams;if(o.set("ids",s),i!=null){let d=Number(i);!Number.isNaN(d)&&d>0&&o.set("depth",String(d))}let a=await z(`/v1/files/${encodeURIComponent(t)}/nodes?${o.toString()}`),c={};for(let[d,l]of Object.entries(a.nodes||{}))c[d]=l?.document?{id:l.document.id,name:l.document.name,type:l.document.type,document:l.document}:l;return JSON.stringify({name:a.name,nodes:c})}case"figma_get_node_specs":{let t=oe((e||{}).file),{ids:n,depth:i}=e||{};if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let s=lt(n);if(!s)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=Number(i);Number.isNaN(o)&&(o=2),o=Math.min(6,Math.max(0,Math.trunc(o)));let a=new URLSearchParams;a.set("ids",s),a.set("depth",String(o));let c=await z(`/v1/files/${encodeURIComponent(t)}/nodes?${a.toString()}`),d={};for(let[l,p]of Object.entries(c.nodes||{}))d[l]=p&&p.document?Gr(p.document,o):null;return JSON.stringify(d)}case"figma_render_png":{let t=oe((e||{}).fileKey??(e||{}).file),{ids:n,scale:i,format:s,svg_include_id:o,version:a}=e||{};if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let c=lt(n);if(!c)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let d=["png","jpg","svg","pdf"].includes(String(s||"").toLowerCase())?String(s).toLowerCase():"png",l=new URLSearchParams;l.set("ids",c),l.set("format",d);let p;(d==="png"||d==="jpg")&&(p=Number(i),(Number.isNaN(p)||p<=0)&&(p=1),p=Math.min(4,Math.max(.01,p)),l.set("scale",String(p))),d==="svg"&&o!=null&&l.set("svg_include_id",String(!!o)),a&&l.set("version",String(a));let u=await z(`/v1/images/${encodeURIComponent(t)}?${l.toString()}`);return u.err?JSON.stringify({error:`Figma render error: ${u.err}`}):JSON.stringify({format:d,...p!=null?{scale:p}:{},images:u.images||{}})}case"figma_get_image_fills":{let t=oe((e||{}).file);if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let n=await z(`/v1/files/${encodeURIComponent(t)}/images`);return JSON.stringify({images:n.meta?.images??n.images??{}})}case"figma_get_file_versions":{let t=oe((e||{}).file);if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let i=((await z(`/v1/files/${encodeURIComponent(t)}/versions`)).versions||[]).map(s=>({id:s.id,label:s.label,description:s.description,createdAt:s.created_at,user:s.user?.handle}));return JSON.stringify({count:i.length,versions:i})}case"figma_get_comments":{let t=oe((e||{}).fileKey);if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=((await z(`/v1/files/${encodeURIComponent(t)}/comments`)).comments||[]).map(s=>({id:s.id,message:s.message,user:s.user?.handle,createdAt:s.created_at,resolvedAt:s.resolved_at||null,parentId:s.parent_id||null}));return JSON.stringify({count:i.length,comments:i})}case"figma_post_comment":{let t=oe((e||{}).file),{message:n,comment_id:i,node_id:s,x:o,y:a}=e||{};if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});if(!n)return JSON.stringify({error:"message is required"});let c={message:n};i&&(c.comment_id=i),s?c.client_meta={node_id:lt(s),node_offset:{x:o??0,y:a??0}}:(o!=null||a!=null)&&(c.client_meta={x:o??0,y:a??0});let d=await z(`/v1/files/${encodeURIComponent(t)}/comments`,{method:"POST",body:c});return JSON.stringify({id:d.id,message:d.message,fileKey:t,createdAt:d.created_at,parentId:d.parent_id||null})}case"figma_get_team_projects":{let{team_id:t}=e||{};if(!t)return JSON.stringify({error:"team_id is required"});let n=await z(`/v1/teams/${encodeURIComponent(t)}/projects`);return JSON.stringify({name:n.name,projects:n.projects||[]})}case"figma_get_project_files":{let{project_id:t,branch_data:n}=e||{};if(!t)return JSON.stringify({error:"project_id is required"});let i=new URLSearchParams;n&&i.set("branch_data","true");let s=i.toString(),o=await z(`/v1/projects/${encodeURIComponent(t)}/files${s?`?${s}`:""}`);return JSON.stringify({name:o.name,files:o.files||[]})}case"figma_parse_url":{let{url:t}=e||{};return JSON.stringify({file_key:oe(t),node_id:$o(t)??null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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. Accepts a file key OR a figma.com URL (figma.com/file|design/<key>/... \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes or figma_get_node_specs to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'A file key OR a figma.com URL (e.g. "aBcD1234" or 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:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch. Accepts URL form ["1-23"] or API form ["1:23"]. A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_get_node_specs",description:"Dev-Mode-style inspection computed from the REST tree: for the given nodes and their children returns size, position, colors (hex), fonts/text-style, spacing/auto-layout, corner radius, strokes and effects \u2014 a compact spec for reproducing a design in code. Prefer this over figma_get_nodes when your job is to build UI from a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to inspect (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},depth:{type:"number",description:"How many levels of children to walk (0-6, default 2)."}},required:["file","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to an image and return the URLs (a map of nodeId \u2192 URL). Despite the name it renders PNG/JPG/SVG/PDF (default png). Use to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},format:{type:"string",enum:["png","jpg","svg","pdf"],description:"Output format (default png)."},scale:{type:"number",description:"Render scale, 0.01\u20134 (raster formats only; default 1). 2 for retina/hi-dpi."},svg_include_id:{type:"boolean",description:"For SVG: include element ids as attributes."},version:{type:"string",description:"Render a specific file version id (from figma_get_file_versions)."}},required:["fileKey","ids"]}},{name:"figma_get_image_fills",description:"Get a map of imageRef \u2192 download URL for every image fill used in a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_file_versions",description:"List a Figma file's saved version history (version id, label, created_at, user). A version id can be passed to figma_render_png to render a past version.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"}},required:["fileKey"]}},{name:"figma_post_comment",description:"Post a comment on a Figma file (WRITE \u2014 needs a PAT with comment-write scope). Optionally reply to a comment (comment_id), pin it to a node (node_id, with optional x/y offset), or pin to a canvas point (x/y).",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},message:{type:"string",description:"The comment text."},comment_id:{type:"string",description:"Optional: reply to this parent comment id."},node_id:{type:"string",description:'Optional: pin the comment to this node ("1-23" or "1:23").'},x:{type:"number",description:"Optional: x position (node offset if node_id given, else canvas point)."},y:{type:"number",description:"Optional: y position (node offset if node_id given, else canvas point)."}},required:["file","message"]}},{name:"figma_get_team_projects",description:"List the projects in a Figma team. Get team_id from a Figma team URL (\u2026/files/team/<TEAM_ID>/\u2026).",input_schema:{type:"object",properties:{team_id:{type:"string",description:"The Figma team id."}},required:["team_id"]}},{name:"figma_get_project_files",description:"List the files in a Figma project (from figma_get_team_projects). Returns file key, name, thumbnail, last_modified.",input_schema:{type:"object",properties:{project_id:{type:"string",description:"The Figma project id."},branch_data:{type:"boolean",description:"Optional: include branch metadata for each file."}},required:["project_id"]}},{name:"figma_parse_url",description:"Local helper (no API call): extract the file key and node id (colon form) from a figma.com file/design URL. Returns { file_key, node_id }.",input_schema:{type:"object",properties:{url:{type:"string",description:"A full figma.com file/design URL."}},required:["url"]}}]};import{existsSync as Po}from"fs";import{fileURLToPath as Co}from"url";import{dirname as Uo,resolve as qo}from"path";import{resolveIntegrationToken as Jo}from"@zibby/core/backend-client.js";function Do(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Uo(Co(import.meta.url)),e=qo(r,"..","bin","mcp-skill.mjs");return Po(e)?e:null}async function X(r,e={}){let{token:t}=await Jo("hubspot");if(!t)throw new Error("HubSpot not connected \u2014 Connect HubSpot in Integrations.");let n=r.startsWith("https://")?r:`https://api.hubapi.com${r}`,i={Authorization:`Bearer ${t}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let a=await s.text().catch(()=>""),c=s.status===401||s.status===403?" \u2014 token invalid/expired or missing the required Private App scope for this object":"";throw new Error(`HubSpot API ${s.status}${c}: ${a.slice(0,300)}`)}let o=await s.text().catch(()=>"");if(!o)return{};try{return JSON.parse(o)}catch{return{raw:o}}}function me(r){return typeof r!="string"?null:r.trim()||null}function Hr(r,e={}){let t=new URLSearchParams;if(r!=null){let i=Array.isArray(r)?r.join(","):String(r);i&&t.set("properties",i)}for(let[i,s]of Object.entries(e))s!=null&&s!==""&&t.set(i,String(s));let n=t.toString();return n?`?${n}`:""}var Le="The CRM object type \u2014 one of the common values `contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions` (customer feedback: NPS/CSAT/CES), or any custom object name/id.",zr={id:"hubspot",serverName:"hubspot",allowedTools:["mcp__hubspot__*"],requiresIntegration:v.HUBSPOT,envKeys:[],description:"HubSpot CRM \u2014 search/read/create/update contacts, companies, deals, tickets, notes and feedback submissions via the HubSpot REST API.",promptFragment:"## HubSpot CRM\nYou have access to the user's HubSpot CRM via the HubSpot REST API (OAuth \u2014 the user connects HubSpot in Integrations; the token is resolved and auto-refreshed for you). The connected app grants the CRM scopes for the objects you touch.\n\nHubSpot's object model is **uniform** \u2014 nearly every tool takes an `objectType` (`contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions`, or a custom object). Records are `{ id, properties }`; you set/read named properties.\n\n**Before you create/update/search, call `hubspot_list_properties` to learn the valid property names for that object type** (they're not guessable). `feedback_submissions` is where NPS/CSAT/CES customer-feedback survey responses live.\n\n### Identity\n- hubspot_whoami: Confirm the token works \u2014 returns the portal (hub) id, account type, time zone, UI domain.\n\n### Schema\n- hubspot_list_properties: List the defined properties (name, label, type, fieldType) for an objectType. Do this first so you use real property names.\n\n### Read\n- hubspot_search: Search an objectType by full-text `query` OR structured `filters` (array of {propertyName, operator, value}). Returns { total, results:[{id, properties}] }.\n- hubspot_get_object: Fetch one record by id (optionally selecting specific properties).\n- hubspot_list_objects: Page through all records of an objectType (limit + after cursor).\n\n### Write\n- hubspot_create_object: Create a record from a `properties` object.\n- hubspot_update_object: Patch a record's `properties` by id.\n- hubspot_create_note: Convenience \u2014 log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket.\n- hubspot_associate: Associate two records (fromType/fromId \u2194 toType/toId) with the default association type.",resolve(){let r=Do();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/hubspot.js","hubspotSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{let t=e||{};switch(r){case"hubspot_whoami":{let n=await X("/account-info/v3/details");return JSON.stringify({portalId:n.portalId,accountType:n.accountType,timeZone:n.timeZone,uiDomain:n.uiDomain,companyCurrency:n.companyCurrency})}case"hubspot_list_properties":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required (e.g. contacts, companies, deals, tickets, feedback_submissions)"});let s=((await X(`/crm/v3/properties/${encodeURIComponent(n)}`)).results||[]).map(o=>({name:o.name,label:o.label,type:o.type,fieldType:o.fieldType}));return JSON.stringify({objectType:n,count:s.length,properties:s})}case"hubspot_search":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let s={limit:Number.isFinite(Number(t.limit))&&Number(t.limit)>0?Math.trunc(Number(t.limit)):20};t.query&&(s.query=String(t.query)),Array.isArray(t.filters)&&t.filters.length&&(s.filterGroups=[{filters:t.filters}]),t.properties!=null&&(s.properties=Array.isArray(t.properties)?t.properties:String(t.properties).split(",").map(a=>a.trim()).filter(Boolean));let o=await X(`/crm/v3/objects/${encodeURIComponent(n)}/search`,{method:"POST",body:s});return JSON.stringify({total:o.total??(o.results?o.results.length:0),results:(o.results||[]).map(a=>({id:a.id,properties:a.properties}))})}case"hubspot_get_object":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!t.id)return JSON.stringify({error:"id is required"});let i=Hr(t.properties,{associations:t.associations}),s=await X(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(t.id)}${i}`);return JSON.stringify({id:s.id,properties:s.properties,...s.associations?{associations:s.associations}:{}})}case"hubspot_list_objects":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let i=Number.isFinite(Number(t.limit))&&Number(t.limit)>0?Math.trunc(Number(t.limit)):20,s=Hr(t.properties,{limit:i,after:t.after}),o=await X(`/crm/v3/objects/${encodeURIComponent(n)}${s}`);return JSON.stringify({results:(o.results||[]).map(a=>({id:a.id,properties:a.properties})),paging:o.paging||null})}case"hubspot_create_object":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!t.properties||typeof t.properties!="object"||Array.isArray(t.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value } \u2014 call hubspot_list_properties first for valid names)"});let i=await X(`/crm/v3/objects/${encodeURIComponent(n)}`,{method:"POST",body:{properties:t.properties}});return JSON.stringify({id:i.id,properties:i.properties})}case"hubspot_update_object":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!t.id)return JSON.stringify({error:"id is required"});if(!t.properties||typeof t.properties!="object"||Array.isArray(t.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value })"});let i=await X(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(t.id)}`,{method:"PATCH",body:{properties:t.properties}});return JSON.stringify({id:i.id,properties:i.properties})}case"hubspot_create_note":{if(!t.body||typeof t.body!="string")return JSON.stringify({error:"body is required (the note text)"});let n=typeof t.timestamp=="string"&&t.timestamp?t.timestamp:null;if(!n)try{n=new Date().toISOString()}catch{n=null}if(!n)return JSON.stringify({error:"timestamp is required (pass an ISO 8601 string, e.g. 2026-01-01T00:00:00.000Z)"});let i=await X("/crm/v3/objects/notes",{method:"POST",body:{properties:{hs_note_body:t.body,hs_timestamp:n}}}),s=i.id,o=[["contacts",t.contactId],["companies",t.companyId],["deals",t.dealId],["tickets",t.ticketId]].filter(([,c])=>c!=null&&c!==""),a=[];for(let[c,d]of o)try{await X(`/crm/v4/objects/notes/${encodeURIComponent(s)}/associations/default/${c}/${encodeURIComponent(d)}`,{method:"PUT"}),a.push({toType:c,toId:String(d)})}catch(l){a.push({toType:c,toId:String(d),error:l.message})}return JSON.stringify({id:s,properties:i.properties,associatedTo:a})}case"hubspot_associate":{let n=me(t.fromType),i=me(t.toType);return!n||!t.fromId||!i||!t.toId?JSON.stringify({error:"fromType, fromId, toType and toId are all required"}):(await X(`/crm/v4/objects/${encodeURIComponent(n)}/${encodeURIComponent(t.fromId)}/associations/default/${encodeURIComponent(i)}/${encodeURIComponent(t.toId)}`,{method:"PUT"}),JSON.stringify({ok:!0}))}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"hubspot_whoami",description:"Confirm the HubSpot token works: returns the portal (hub) id, account type, time zone and UI domain.",input_schema:{type:"object",properties:{}}},{name:"hubspot_list_properties",description:"List the defined properties (name, label, type, fieldType) for a CRM object type. Call this FIRST so you use valid property names when creating/updating/searching.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le}},required:["objectType"]}},{name:"hubspot_search",description:"Search a CRM object type. Pass a full-text `query` OR structured `filters` (array of {propertyName, operator, value}, e.g. operator EQ/CONTAINS_TOKEN/GT/\u2026). Returns { total, results:[{id, properties}] }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},query:{type:"string",description:"Optional full-text search string."},filters:{type:"array",description:"Optional structured filters (ANDed). Each: { propertyName, operator, value }. Operators: EQ, NEQ, LT, LTE, GT, GTE, CONTAINS_TOKEN, HAS_PROPERTY, IN, \u2026",items:{type:"object",properties:{propertyName:{type:"string"},operator:{type:"string"},value:{type:"string"}}}},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each result."},limit:{type:"number",description:"Max results (default 20)."}},required:["objectType"]}},{name:"hubspot_get_object",description:"Fetch one CRM record by id. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},id:{type:"string",description:"The record id."},properties:{type:"array",items:{type:"string"},description:"Optional: specific property names to return."},associations:{type:"string",description:'Optional: comma-separated object types to also return associations for (e.g. "companies,deals").'}},required:["objectType","id"]}},{name:"hubspot_list_objects",description:"Page through records of a CRM object type. Returns { results, paging } \u2014 pass paging.next.after back as `after` for the next page.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each record."},limit:{type:"number",description:"Page size (default 20)."},after:{type:"string",description:"Optional paging cursor from a previous response (paging.next.after)."}},required:["objectType"]}},{name:"hubspot_create_object",description:"Create a CRM record. Pass `properties` as an object of { propertyName: value } (call hubspot_list_properties first for valid names). Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},properties:{type:"object",description:"Object of { propertyName: value } to set on the new record."}},required:["objectType","properties"]}},{name:"hubspot_update_object",description:"Update (PATCH) a CRM record by id. Pass `properties` as an object of { propertyName: value }. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},id:{type:"string",description:"The record id to update."},properties:{type:"object",description:"Object of { propertyName: value } to change."}},required:["objectType","id","properties"]}},{name:"hubspot_create_note",description:"Log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket. Returns { id, associatedTo }.",input_schema:{type:"object",properties:{body:{type:"string",description:"The note text (stored as hs_note_body)."},contactId:{type:"string",description:"Optional: associate the note to this contact id."},companyId:{type:"string",description:"Optional: associate the note to this company id."},dealId:{type:"string",description:"Optional: associate the note to this deal id."},ticketId:{type:"string",description:"Optional: associate the note to this ticket id."},timestamp:{type:"string",description:"Optional ISO 8601 timestamp for the note (defaults to now)."}},required:["body"]}},{name:"hubspot_associate",description:"Associate two CRM records with the default association type (e.g. a contact to a company). Returns { ok:true }.",input_schema:{type:"object",properties:{fromType:{type:"string",description:"Source object type (e.g. contacts)."},fromId:{type:"string",description:"Source record id."},toType:{type:"string",description:"Target object type (e.g. companies)."},toId:{type:"string",description:"Target record id."}},required:["fromType","fromId","toType","toId"]}}]};import{existsSync as Bo}from"fs";import{fileURLToPath as Mo}from"url";import{dirname as Fo,resolve as Go}from"path";function Ko(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Fo(Mo(import.meta.url)),e=Go(r,"..","bin","mcp-skill.mjs");return Bo(e)?e:null}var Ho=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function zo(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let r=process.env.LINEAR_API_KEY;if(!r)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return r}async function W(r,e={}){let t=await fetch(Ho,{method:"POST",headers:{Authorization:zo(),"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:e})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`Linear API ${t.status}: ${i.slice(0,300)}`)}let n=await t.json().catch(()=>null);if(!n)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(n.errors)&&n.errors.length){let i=n.errors.map(s=>s?.message||String(s)).join("; ");throw new Error(`Linear GraphQL error: ${i.slice(0,300)}`)}return n.data}function Ke(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Wo(r,e){let t=Ke(r),n=Ke(e);if(!t||!n)return 0;if(t===n)return 1;if(t.length===1||n.length===1)return t===n?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=i(t),o=i(n),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of s.entries())a+=Math.min(p,o.get(l)||0);return 2*a/Math.max(1,c+d)}function Yo(r,e){let t=Array.isArray(r)?r:[];if(!t.length)return{state:null,strategy:"no-states"};let n=Ke(e);if(!n)return{state:null,strategy:"no-target"};let i=t.find(a=>Ke(a.name)===n);if(i)return{state:i,strategy:"exact"};let s={backlog:["backlog"],unstarted:["todo","unstarted","open"],started:["inprogress","started","doing","wip"],completed:["done","completed","closed","resolved","fixed"],canceled:["canceled","cancelled","wontfix","won'tfix"],triage:["triage"]};for(let[a,c]of Object.entries(s)){if(!c.some(l=>Ke(l)===n))continue;let d=t.find(l=>l.type===a);if(d)return{state:d,strategy:"type-alias"}}let o=t.map(a=>({s:a,score:Wo(e,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 Zo=`
189
+ - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes / figma_parse_url output.`,resolve(){let r=Bo();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/figma.js","figmaSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"figma_get_me":{let t=await z("/v1/me");return JSON.stringify({id:t.id,handle:t.handle,email:t.email,imgUrl:t.img_url})}case"figma_get_file":{let t=oe((e||{}).fileKey),{depth:n}=e||{};if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=`/v1/files/${encodeURIComponent(t)}`;if(n!=null){let a=Number(n);!Number.isNaN(a)&&a>0&&(i+=`?depth=${a}`)}let s=await z(i),o=(s.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:s.name,lastModified:s.lastModified,version:s.version,editorType:s.editorType,role:s.role,pages:o})}case"figma_get_nodes":{let t=oe((e||{}).fileKey),{ids:n,depth:i}=e||{};if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=lt(n);if(!s)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=new URLSearchParams;if(o.set("ids",s),i!=null){let d=Number(i);!Number.isNaN(d)&&d>0&&o.set("depth",String(d))}let a=await z(`/v1/files/${encodeURIComponent(t)}/nodes?${o.toString()}`),c={};for(let[d,l]of Object.entries(a.nodes||{}))c[d]=l?.document?{id:l.document.id,name:l.document.name,type:l.document.type,document:l.document}:l;return JSON.stringify({name:a.name,nodes:c})}case"figma_get_node_specs":{let t=oe((e||{}).file),{ids:n,depth:i}=e||{};if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let s=lt(n);if(!s)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=Number(i);Number.isNaN(o)&&(o=2),o=Math.min(6,Math.max(0,Math.trunc(o)));let a=new URLSearchParams;a.set("ids",s),a.set("depth",String(o));let c=await z(`/v1/files/${encodeURIComponent(t)}/nodes?${a.toString()}`),d={};for(let[l,p]of Object.entries(c.nodes||{}))d[l]=p&&p.document?Hr(p.document,o):null;return JSON.stringify(d)}case"figma_render_png":{let t=oe((e||{}).fileKey??(e||{}).file),{ids:n,scale:i,format:s,svg_include_id:o,version:a}=e||{};if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let c=lt(n);if(!c)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let d=["png","jpg","svg","pdf"].includes(String(s||"").toLowerCase())?String(s).toLowerCase():"png",l=new URLSearchParams;l.set("ids",c),l.set("format",d);let p;(d==="png"||d==="jpg")&&(p=Number(i),(Number.isNaN(p)||p<=0)&&(p=1),p=Math.min(4,Math.max(.01,p)),l.set("scale",String(p))),d==="svg"&&o!=null&&l.set("svg_include_id",String(!!o)),a&&l.set("version",String(a));let u=await z(`/v1/images/${encodeURIComponent(t)}?${l.toString()}`);return u.err?JSON.stringify({error:`Figma render error: ${u.err}`}):JSON.stringify({format:d,...p!=null?{scale:p}:{},images:u.images||{}})}case"figma_get_image_fills":{let t=oe((e||{}).file);if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let n=await z(`/v1/files/${encodeURIComponent(t)}/images`);return JSON.stringify({images:n.meta?.images??n.images??{}})}case"figma_get_file_versions":{let t=oe((e||{}).file);if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let i=((await z(`/v1/files/${encodeURIComponent(t)}/versions`)).versions||[]).map(s=>({id:s.id,label:s.label,description:s.description,createdAt:s.created_at,user:s.user?.handle}));return JSON.stringify({count:i.length,versions:i})}case"figma_get_comments":{let t=oe((e||{}).fileKey);if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=((await z(`/v1/files/${encodeURIComponent(t)}/comments`)).comments||[]).map(s=>({id:s.id,message:s.message,user:s.user?.handle,createdAt:s.created_at,resolvedAt:s.resolved_at||null,parentId:s.parent_id||null}));return JSON.stringify({count:i.length,comments:i})}case"figma_post_comment":{let t=oe((e||{}).file),{message:n,comment_id:i,node_id:s,x:o,y:a}=e||{};if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});if(!n)return JSON.stringify({error:"message is required"});let c={message:n};i&&(c.comment_id=i),s?c.client_meta={node_id:lt(s),node_offset:{x:o??0,y:a??0}}:(o!=null||a!=null)&&(c.client_meta={x:o??0,y:a??0});let d=await z(`/v1/files/${encodeURIComponent(t)}/comments`,{method:"POST",body:c});return JSON.stringify({id:d.id,message:d.message,fileKey:t,createdAt:d.created_at,parentId:d.parent_id||null})}case"figma_get_team_projects":{let{team_id:t}=e||{};if(!t)return JSON.stringify({error:"team_id is required"});let n=await z(`/v1/teams/${encodeURIComponent(t)}/projects`);return JSON.stringify({name:n.name,projects:n.projects||[]})}case"figma_get_project_files":{let{project_id:t,branch_data:n}=e||{};if(!t)return JSON.stringify({error:"project_id is required"});let i=new URLSearchParams;n&&i.set("branch_data","true");let s=i.toString(),o=await z(`/v1/projects/${encodeURIComponent(t)}/files${s?`?${s}`:""}`);return JSON.stringify({name:o.name,files:o.files||[]})}case"figma_parse_url":{let{url:t}=e||{};return JSON.stringify({file_key:oe(t),node_id:Mo(t)??null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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. Accepts a file key OR a figma.com URL (figma.com/file|design/<key>/... \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes or figma_get_node_specs to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'A file key OR a figma.com URL (e.g. "aBcD1234" or 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:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch. Accepts URL form ["1-23"] or API form ["1:23"]. A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_get_node_specs",description:"Dev-Mode-style inspection computed from the REST tree: for the given nodes and their children returns size, position, colors (hex), fonts/text-style, spacing/auto-layout, corner radius, strokes and effects \u2014 a compact spec for reproducing a design in code. Prefer this over figma_get_nodes when your job is to build UI from a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to inspect (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},depth:{type:"number",description:"How many levels of children to walk (0-6, default 2)."}},required:["file","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to an image and return the URLs (a map of nodeId \u2192 URL). Despite the name it renders PNG/JPG/SVG/PDF (default png). Use to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},format:{type:"string",enum:["png","jpg","svg","pdf"],description:"Output format (default png)."},scale:{type:"number",description:"Render scale, 0.01\u20134 (raster formats only; default 1). 2 for retina/hi-dpi."},svg_include_id:{type:"boolean",description:"For SVG: include element ids as attributes."},version:{type:"string",description:"Render a specific file version id (from figma_get_file_versions)."}},required:["fileKey","ids"]}},{name:"figma_get_image_fills",description:"Get a map of imageRef \u2192 download URL for every image fill used in a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_file_versions",description:"List a Figma file's saved version history (version id, label, created_at, user). A version id can be passed to figma_render_png to render a past version.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"}},required:["fileKey"]}},{name:"figma_post_comment",description:"Post a comment on a Figma file (WRITE \u2014 needs a PAT with comment-write scope). Optionally reply to a comment (comment_id), pin it to a node (node_id, with optional x/y offset), or pin to a canvas point (x/y).",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},message:{type:"string",description:"The comment text."},comment_id:{type:"string",description:"Optional: reply to this parent comment id."},node_id:{type:"string",description:'Optional: pin the comment to this node ("1-23" or "1:23").'},x:{type:"number",description:"Optional: x position (node offset if node_id given, else canvas point)."},y:{type:"number",description:"Optional: y position (node offset if node_id given, else canvas point)."}},required:["file","message"]}},{name:"figma_get_team_projects",description:"List the projects in a Figma team. Get team_id from a Figma team URL (\u2026/files/team/<TEAM_ID>/\u2026).",input_schema:{type:"object",properties:{team_id:{type:"string",description:"The Figma team id."}},required:["team_id"]}},{name:"figma_get_project_files",description:"List the files in a Figma project (from figma_get_team_projects). Returns file key, name, thumbnail, last_modified.",input_schema:{type:"object",properties:{project_id:{type:"string",description:"The Figma project id."},branch_data:{type:"boolean",description:"Optional: include branch metadata for each file."}},required:["project_id"]}},{name:"figma_parse_url",description:"Local helper (no API call): extract the file key and node id (colon form) from a figma.com file/design URL. Returns { file_key, node_id }.",input_schema:{type:"object",properties:{url:{type:"string",description:"A full figma.com file/design URL."}},required:["url"]}}]};import{existsSync as Fo}from"fs";import{fileURLToPath as Go}from"url";import{dirname as Ko,resolve as Ho}from"path";import{resolveIntegrationToken as zo}from"@zibby/core/backend-client.js";function Yo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ko(Go(import.meta.url)),e=Ho(r,"..","bin","mcp-skill.mjs");return Fo(e)?e:null}async function X(r,e={}){let{token:t}=await zo("hubspot");if(!t)throw new Error("HubSpot not connected \u2014 Connect HubSpot in Integrations.");let n=r.startsWith("https://")?r:`https://api.hubapi.com${r}`,i={Authorization:`Bearer ${t}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let a=await s.text().catch(()=>""),c=s.status===401||s.status===403?" \u2014 token invalid/expired or missing the required Private App scope for this object":"";throw new Error(`HubSpot API ${s.status}${c}: ${a.slice(0,300)}`)}let o=await s.text().catch(()=>"");if(!o)return{};try{return JSON.parse(o)}catch{return{raw:o}}}function me(r){return typeof r!="string"?null:r.trim()||null}function Yr(r,e={}){let t=new URLSearchParams;if(r!=null){let i=Array.isArray(r)?r.join(","):String(r);i&&t.set("properties",i)}for(let[i,s]of Object.entries(e))s!=null&&s!==""&&t.set(i,String(s));let n=t.toString();return n?`?${n}`:""}var Le="The CRM object type \u2014 one of the common values `contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions` (customer feedback: NPS/CSAT/CES), or any custom object name/id.",Wr={id:"hubspot",serverName:"hubspot",allowedTools:["mcp__hubspot__*"],requiresIntegration:I.HUBSPOT,envKeys:[],description:"HubSpot CRM \u2014 search/read/create/update contacts, companies, deals, tickets, notes and feedback submissions via the HubSpot REST API.",promptFragment:"## HubSpot CRM\nYou have access to the user's HubSpot CRM via the HubSpot REST API (OAuth \u2014 the user connects HubSpot in Integrations; the token is resolved and auto-refreshed for you). The connected app grants the CRM scopes for the objects you touch.\n\nHubSpot's object model is **uniform** \u2014 nearly every tool takes an `objectType` (`contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions`, or a custom object). Records are `{ id, properties }`; you set/read named properties.\n\n**Before you create/update/search, call `hubspot_list_properties` to learn the valid property names for that object type** (they're not guessable). `feedback_submissions` is where NPS/CSAT/CES customer-feedback survey responses live.\n\n### Identity\n- hubspot_whoami: Confirm the token works \u2014 returns the portal (hub) id, account type, time zone, UI domain.\n\n### Schema\n- hubspot_list_properties: List the defined properties (name, label, type, fieldType) for an objectType. Do this first so you use real property names.\n\n### Read\n- hubspot_search: Search an objectType by full-text `query` OR structured `filters` (array of {propertyName, operator, value}). Returns { total, results:[{id, properties}] }.\n- hubspot_get_object: Fetch one record by id (optionally selecting specific properties).\n- hubspot_list_objects: Page through all records of an objectType (limit + after cursor).\n\n### Write\n- hubspot_create_object: Create a record from a `properties` object.\n- hubspot_update_object: Patch a record's `properties` by id.\n- hubspot_create_note: Convenience \u2014 log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket.\n- hubspot_associate: Associate two records (fromType/fromId \u2194 toType/toId) with the default association type.",resolve(){let r=Yo();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/hubspot.js","hubspotSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{let t=e||{};switch(r){case"hubspot_whoami":{let n=await X("/account-info/v3/details");return JSON.stringify({portalId:n.portalId,accountType:n.accountType,timeZone:n.timeZone,uiDomain:n.uiDomain,companyCurrency:n.companyCurrency})}case"hubspot_list_properties":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required (e.g. contacts, companies, deals, tickets, feedback_submissions)"});let s=((await X(`/crm/v3/properties/${encodeURIComponent(n)}`)).results||[]).map(o=>({name:o.name,label:o.label,type:o.type,fieldType:o.fieldType}));return JSON.stringify({objectType:n,count:s.length,properties:s})}case"hubspot_search":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let s={limit:Number.isFinite(Number(t.limit))&&Number(t.limit)>0?Math.trunc(Number(t.limit)):20};t.query&&(s.query=String(t.query)),Array.isArray(t.filters)&&t.filters.length&&(s.filterGroups=[{filters:t.filters}]),t.properties!=null&&(s.properties=Array.isArray(t.properties)?t.properties:String(t.properties).split(",").map(a=>a.trim()).filter(Boolean));let o=await X(`/crm/v3/objects/${encodeURIComponent(n)}/search`,{method:"POST",body:s});return JSON.stringify({total:o.total??(o.results?o.results.length:0),results:(o.results||[]).map(a=>({id:a.id,properties:a.properties}))})}case"hubspot_get_object":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!t.id)return JSON.stringify({error:"id is required"});let i=Yr(t.properties,{associations:t.associations}),s=await X(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(t.id)}${i}`);return JSON.stringify({id:s.id,properties:s.properties,...s.associations?{associations:s.associations}:{}})}case"hubspot_list_objects":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let i=Number.isFinite(Number(t.limit))&&Number(t.limit)>0?Math.trunc(Number(t.limit)):20,s=Yr(t.properties,{limit:i,after:t.after}),o=await X(`/crm/v3/objects/${encodeURIComponent(n)}${s}`);return JSON.stringify({results:(o.results||[]).map(a=>({id:a.id,properties:a.properties})),paging:o.paging||null})}case"hubspot_create_object":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!t.properties||typeof t.properties!="object"||Array.isArray(t.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value } \u2014 call hubspot_list_properties first for valid names)"});let i=await X(`/crm/v3/objects/${encodeURIComponent(n)}`,{method:"POST",body:{properties:t.properties}});return JSON.stringify({id:i.id,properties:i.properties})}case"hubspot_update_object":{let n=me(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!t.id)return JSON.stringify({error:"id is required"});if(!t.properties||typeof t.properties!="object"||Array.isArray(t.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value })"});let i=await X(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(t.id)}`,{method:"PATCH",body:{properties:t.properties}});return JSON.stringify({id:i.id,properties:i.properties})}case"hubspot_create_note":{if(!t.body||typeof t.body!="string")return JSON.stringify({error:"body is required (the note text)"});let n=typeof t.timestamp=="string"&&t.timestamp?t.timestamp:null;if(!n)try{n=new Date().toISOString()}catch{n=null}if(!n)return JSON.stringify({error:"timestamp is required (pass an ISO 8601 string, e.g. 2026-01-01T00:00:00.000Z)"});let i=await X("/crm/v3/objects/notes",{method:"POST",body:{properties:{hs_note_body:t.body,hs_timestamp:n}}}),s=i.id,o=[["contacts",t.contactId],["companies",t.companyId],["deals",t.dealId],["tickets",t.ticketId]].filter(([,c])=>c!=null&&c!==""),a=[];for(let[c,d]of o)try{await X(`/crm/v4/objects/notes/${encodeURIComponent(s)}/associations/default/${c}/${encodeURIComponent(d)}`,{method:"PUT"}),a.push({toType:c,toId:String(d)})}catch(l){a.push({toType:c,toId:String(d),error:l.message})}return JSON.stringify({id:s,properties:i.properties,associatedTo:a})}case"hubspot_associate":{let n=me(t.fromType),i=me(t.toType);return!n||!t.fromId||!i||!t.toId?JSON.stringify({error:"fromType, fromId, toType and toId are all required"}):(await X(`/crm/v4/objects/${encodeURIComponent(n)}/${encodeURIComponent(t.fromId)}/associations/default/${encodeURIComponent(i)}/${encodeURIComponent(t.toId)}`,{method:"PUT"}),JSON.stringify({ok:!0}))}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"hubspot_whoami",description:"Confirm the HubSpot token works: returns the portal (hub) id, account type, time zone and UI domain.",input_schema:{type:"object",properties:{}}},{name:"hubspot_list_properties",description:"List the defined properties (name, label, type, fieldType) for a CRM object type. Call this FIRST so you use valid property names when creating/updating/searching.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le}},required:["objectType"]}},{name:"hubspot_search",description:"Search a CRM object type. Pass a full-text `query` OR structured `filters` (array of {propertyName, operator, value}, e.g. operator EQ/CONTAINS_TOKEN/GT/\u2026). Returns { total, results:[{id, properties}] }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},query:{type:"string",description:"Optional full-text search string."},filters:{type:"array",description:"Optional structured filters (ANDed). Each: { propertyName, operator, value }. Operators: EQ, NEQ, LT, LTE, GT, GTE, CONTAINS_TOKEN, HAS_PROPERTY, IN, \u2026",items:{type:"object",properties:{propertyName:{type:"string"},operator:{type:"string"},value:{type:"string"}}}},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each result."},limit:{type:"number",description:"Max results (default 20)."}},required:["objectType"]}},{name:"hubspot_get_object",description:"Fetch one CRM record by id. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},id:{type:"string",description:"The record id."},properties:{type:"array",items:{type:"string"},description:"Optional: specific property names to return."},associations:{type:"string",description:'Optional: comma-separated object types to also return associations for (e.g. "companies,deals").'}},required:["objectType","id"]}},{name:"hubspot_list_objects",description:"Page through records of a CRM object type. Returns { results, paging } \u2014 pass paging.next.after back as `after` for the next page.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each record."},limit:{type:"number",description:"Page size (default 20)."},after:{type:"string",description:"Optional paging cursor from a previous response (paging.next.after)."}},required:["objectType"]}},{name:"hubspot_create_object",description:"Create a CRM record. Pass `properties` as an object of { propertyName: value } (call hubspot_list_properties first for valid names). Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},properties:{type:"object",description:"Object of { propertyName: value } to set on the new record."}},required:["objectType","properties"]}},{name:"hubspot_update_object",description:"Update (PATCH) a CRM record by id. Pass `properties` as an object of { propertyName: value }. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Le},id:{type:"string",description:"The record id to update."},properties:{type:"object",description:"Object of { propertyName: value } to change."}},required:["objectType","id","properties"]}},{name:"hubspot_create_note",description:"Log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket. Returns { id, associatedTo }.",input_schema:{type:"object",properties:{body:{type:"string",description:"The note text (stored as hs_note_body)."},contactId:{type:"string",description:"Optional: associate the note to this contact id."},companyId:{type:"string",description:"Optional: associate the note to this company id."},dealId:{type:"string",description:"Optional: associate the note to this deal id."},ticketId:{type:"string",description:"Optional: associate the note to this ticket id."},timestamp:{type:"string",description:"Optional ISO 8601 timestamp for the note (defaults to now)."}},required:["body"]}},{name:"hubspot_associate",description:"Associate two CRM records with the default association type (e.g. a contact to a company). Returns { ok:true }.",input_schema:{type:"object",properties:{fromType:{type:"string",description:"Source object type (e.g. contacts)."},fromId:{type:"string",description:"Source record id."},toType:{type:"string",description:"Target object type (e.g. companies)."},toId:{type:"string",description:"Target record id."}},required:["fromType","fromId","toType","toId"]}}]};import{existsSync as Wo}from"fs";import{fileURLToPath as Zo}from"url";import{dirname as Vo,resolve as Qo}from"path";function Xo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Vo(Zo(import.meta.url)),e=Qo(r,"..","bin","mcp-skill.mjs");return Wo(e)?e:null}var ea=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function ta(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let r=process.env.LINEAR_API_KEY;if(!r)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return r}async function Y(r,e={}){let t=await fetch(ea,{method:"POST",headers:{Authorization:ta(),"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:e})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`Linear API ${t.status}: ${i.slice(0,300)}`)}let n=await t.json().catch(()=>null);if(!n)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(n.errors)&&n.errors.length){let i=n.errors.map(s=>s?.message||String(s)).join("; ");throw new Error(`Linear GraphQL error: ${i.slice(0,300)}`)}return n.data}function Ke(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function ra(r,e){let t=Ke(r),n=Ke(e);if(!t||!n)return 0;if(t===n)return 1;if(t.length===1||n.length===1)return t===n?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=i(t),o=i(n),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of s.entries())a+=Math.min(p,o.get(l)||0);return 2*a/Math.max(1,c+d)}function na(r,e){let t=Array.isArray(r)?r:[];if(!t.length)return{state:null,strategy:"no-states"};let n=Ke(e);if(!n)return{state:null,strategy:"no-target"};let i=t.find(a=>Ke(a.name)===n);if(i)return{state:i,strategy:"exact"};let s={backlog:["backlog"],unstarted:["todo","unstarted","open"],started:["inprogress","started","doing","wip"],completed:["done","completed","closed","resolved","fixed"],canceled:["canceled","cancelled","wontfix","won'tfix"],triage:["triage"]};for(let[a,c]of Object.entries(s)){if(!c.some(l=>Ke(l)===n))continue;let d=t.find(l=>l.type===a);if(d)return{state:d,strategy:"type-alias"}}let o=t.map(a=>({s:a,score:ra(e,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 ia=`
190
190
  id
191
191
  identifier
192
192
  number
@@ -200,7 +200,7 @@ You have access to the user's Figma files via the Figma REST API. Every tool tha
200
200
  assignee { id name displayName email }
201
201
  labels { nodes { id name color } }
202
202
  team { id key name }
203
- `,Yr={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)
203
+ `,Vr={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)
204
204
  You have direct access to the user's Linear workspace (GraphQL API). Tools:
205
205
 
206
206
  ### Discovery
@@ -218,32 +218,32 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
218
218
 
219
219
  ### Notes
220
220
  - 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.
221
- - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let r={};for(let t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);process.env.LINEAR_API_URL&&(r.LINEAR_API_URL=process.env.LINEAR_API_URL);let e=Ko();return e?{type:"stdio",command:"node",args:[e,"../dist/linear.js","linearSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,e){try{switch(r){case"linear_list_teams":{let n=(await W(`
221
+ - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let r={};for(let t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);process.env.LINEAR_API_URL&&(r.LINEAR_API_URL=process.env.LINEAR_API_URL);let e=Xo();return e?{type:"stdio",command:"node",args:[e,"../dist/linear.js","linearSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,e){try{switch(r){case"linear_list_teams":{let n=(await Y(`
222
222
  query Teams($first: Int) {
223
223
  teams(first: $first) {
224
224
  nodes { id key name description }
225
225
  }
226
226
  }
227
- `,{first:e?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:n.length,teams:n})}case"linear_list_states":{let{teamId:t,teamKey:n}=e||{},i=t;if(!i&&n&&(i=await Wr(n)),i){let c=(await W(`
227
+ `,{first:e?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:n.length,teams:n})}case"linear_list_states":{let{teamId:t,teamKey:n}=e||{},i=t;if(!i&&n&&(i=await Zr(n)),i){let c=(await Y(`
228
228
  query States($teamId: String!) {
229
229
  team(id: $teamId) {
230
230
  id key name
231
231
  states { nodes { id name type color position } }
232
232
  }
233
233
  }
234
- `,{teamId:i}))?.team,d=(c?.states?.nodes||[]).slice().sort((l,p)=>(l.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:d.length,states:d})}let o=(await W(`
234
+ `,{teamId:i}))?.team,d=(c?.states?.nodes||[]).slice().sort((l,p)=>(l.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:d.length,states:d})}let o=(await Y(`
235
235
  query AllStates($first: Int) {
236
236
  workflowStates(first: $first) {
237
237
  nodes { id name type color team { id key name } }
238
238
  }
239
239
  }
240
- `,{first:e?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:t}=e||{},i=(await W(`
240
+ `,{first:e?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:t}=e||{},i=(await Y(`
241
241
  query Labels($first: Int, $filter: IssueLabelFilter) {
242
242
  issueLabels(first: $first, filter: $filter) {
243
243
  nodes { id name color team { id key } }
244
244
  }
245
245
  }
246
- `,{first:e?.limit||100,filter:t?{team:{id:{eq:t}}}:void 0}))?.issueLabels?.nodes||[];return JSON.stringify({count:i.length,labels:i})}case"linear_list_issues":{let{teamId:t,teamKey:n,stateId:i,stateName:s,label:o,assigneeId:a,updatedAfter:c,limit:d}=e||{},l={},p=t;!p&&n&&(p=await Wr(n)),p&&(l.team={id:{eq:p}}),i?l.state={id:{eq:i}}:s&&(l.state={name:{eqIgnoreCase:s}}),o&&(l.labels={name:{eqIgnoreCase:o}}),a&&(l.assignee={id:{eq:a}}),c&&(l.updatedAt={gt:c});let m=((await W(`
246
+ `,{first:e?.limit||100,filter:t?{team:{id:{eq:t}}}:void 0}))?.issueLabels?.nodes||[];return JSON.stringify({count:i.length,labels:i})}case"linear_list_issues":{let{teamId:t,teamKey:n,stateId:i,stateName:s,label:o,assigneeId:a,updatedAfter:c,limit:d}=e||{},l={},p=t;!p&&n&&(p=await Zr(n)),p&&(l.team={id:{eq:p}}),i?l.state={id:{eq:i}}:s&&(l.state={name:{eqIgnoreCase:s}}),o&&(l.labels={name:{eqIgnoreCase:o}}),a&&(l.assignee={id:{eq:a}}),c&&(l.updatedAt={gt:c});let m=((await Y(`
247
247
  query Issues($first: Int, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
248
248
  issues(first: $first, filter: $filter, orderBy: $orderBy) {
249
249
  nodes {
@@ -260,7 +260,7 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
260
260
  comments(first: ${Number(e?.limit)||50}) {
261
261
  nodes { id body createdAt updatedAt user { id name displayName } }
262
262
  }
263
- `);if(!n)return JSON.stringify({error:`Issue not found: ${t}`});let i=(n.comments?.nodes||[]).map(s=>({id:s.id,author:s.user?.displayName||s.user?.name||"Unknown",body:s.body||"",createdAt:s.createdAt,updatedAt:s.updatedAt})).sort((s,o)=>String(o.createdAt).localeCompare(String(s.createdAt)));return JSON.stringify({count:i.length,issue:n.identifier,comments:i})}case"linear_add_comment":{let t=e?.issueId||e?.identifier||e?.issueKey,n=e?.body;if(!t||!n)return JSON.stringify({error:"issueId/identifier and body are required"});let i=await Ge(t,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${t}`});let o=(await W(`
263
+ `);if(!n)return JSON.stringify({error:`Issue not found: ${t}`});let i=(n.comments?.nodes||[]).map(s=>({id:s.id,author:s.user?.displayName||s.user?.name||"Unknown",body:s.body||"",createdAt:s.createdAt,updatedAt:s.updatedAt})).sort((s,o)=>String(o.createdAt).localeCompare(String(s.createdAt)));return JSON.stringify({count:i.length,issue:n.identifier,comments:i})}case"linear_add_comment":{let t=e?.issueId||e?.identifier||e?.issueKey,n=e?.body;if(!t||!n)return JSON.stringify({error:"issueId/identifier and body are required"});let i=await Ge(t,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${t}`});let o=(await Y(`
264
264
  mutation AddComment($input: CommentCreateInput!) {
265
265
  commentCreate(input: $input) {
266
266
  success
@@ -271,41 +271,41 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
271
271
  id identifier
272
272
  state { id name type }
273
273
  team { id key states { nodes { id name type position } } }
274
- `);if(!a)return JSON.stringify({error:`Issue not found: ${t}`});let c=n,d=n?{strategy:"explicit-id"}:null;if(!c){let u=String(i||s||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((h,y)=>(h.position||0)-(y.position||0));if(!u)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=Yo(m,u);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${u}" 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 p=(await W(`
274
+ `);if(!a)return JSON.stringify({error:`Issue not found: ${t}`});let c=n,d=n?{strategy:"explicit-id"}:null;if(!c){let u=String(i||s||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((h,g)=>(h.position||0)-(g.position||0));if(!u)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=na(m,u);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${u}" 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 p=(await Y(`
275
275
  mutation MoveIssue($id: String!, $input: IssueUpdateInput!) {
276
276
  issueUpdate(id: $id, input: $input) {
277
277
  success
278
278
  issue { id identifier state { id name type } }
279
279
  }
280
280
  }
281
- `,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!p?.success,issue:p?.issue?.identifier||a.identifier,stateAfter:p?.issue?.state?.name||null,stateTypeAfter:p?.issue?.state?.type||null,resolution:d})}case"linear_link_attachment":{let t=e?.issueId||e?.identifier||e?.issueKey,{url:n,title:i,subtitle:s}=e||{};if(!t||!n)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await Ge(t,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${t}`});let c=(await W(`
281
+ `,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!p?.success,issue:p?.issue?.identifier||a.identifier,stateAfter:p?.issue?.state?.name||null,stateTypeAfter:p?.issue?.state?.type||null,resolution:d})}case"linear_link_attachment":{let t=e?.issueId||e?.identifier||e?.issueKey,{url:n,title:i,subtitle:s}=e||{};if(!t||!n)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await Ge(t,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${t}`});let c=(await Y(`
282
282
  mutation LinkAttachment($input: AttachmentCreateInput!) {
283
283
  attachmentCreate(input: $input) {
284
284
  success
285
285
  attachment { id url title }
286
286
  }
287
287
  }
288
- `,{input:{issueId:o.id,url:n,title:i||n,subtitle:s||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 Wr(r){return(await W(`
288
+ `,{input:{issueId:o.id,url:n,title:i||n,subtitle:s||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 Zr(r){return(await Y(`
289
289
  query TeamByKey($filter: TeamFilter) {
290
290
  teams(first: 1, filter: $filter) { nodes { id key } }
291
291
  }
292
- `,{filter:{key:{eq:r}}}))?.teams?.nodes?.[0]?.id||null}async function Ge(r,e=Zo){let t=String(r).trim(),n=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(t);if(n){let s=n[1].toUpperCase(),o=Number(n[2]);return(await W(`
292
+ `,{filter:{key:{eq:r}}}))?.teams?.nodes?.[0]?.id||null}async function Ge(r,e=ia){let t=String(r).trim(),n=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(t);if(n){let s=n[1].toUpperCase(),o=Number(n[2]);return(await Y(`
293
293
  query IssueByIdentifier($filter: IssueFilter) {
294
294
  issues(first: 1, filter: $filter) {
295
295
  nodes { ${e} }
296
296
  }
297
297
  }
298
- `,{filter:{number:{eq:o},team:{key:{eq:s}}}}))?.issues?.nodes?.[0]||null}return(await W(`
298
+ `,{filter:{number:{eq:o},team:{key:{eq:s}}}}))?.issues?.nodes?.[0]||null}return(await Y(`
299
299
  query IssueById($id: String!) {
300
300
  issue(id: $id) { ${e} }
301
301
  }
302
- `,{id:t}))?.issue||null}var Zr={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)
302
+ `,{id:t}))?.issue||null}var Qr={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)
303
303
  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.
304
304
 
305
305
  - List/get projects and work items, then create/update/delete or search work items as needed.
306
306
  - For status changes, read the project's available states first, then set the work item's state.
307
307
  - Cycles and modules group work items \u2014 list them to scope queries before drilling into items.
308
- - 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 r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);return{type:"stdio",command:"uvx",args:["plane-mcp-server","stdio"],env:r,description:this.description}}};import{existsSync as Vo}from"fs";import{fileURLToPath as Qo}from"url";import{dirname as Xo,resolve as ea}from"path";import{resolveIntegrationToken as ta}from"@zibby/core/backend-client.js";function ra(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Xo(Qo(import.meta.url)),e=ea(r,"..","bin","mcp-skill.mjs");return Vo(e)?e:null}async function Vr(){let r=await ta(v.OPEN_DESIGN),e=r?.token,t=r?.baseUrl;if(!e||typeof e!="string")throw new Error("OpenDesign is not connected: missing token. Connect it in Integrations.");if(!t||typeof t!="string")throw new Error("OpenDesign is not connected: missing baseUrl. Connect it in Integrations.");let n=t.replace(/\/+$/,"");return{token:e,baseUrl:n}}async function fe(r,e={}){let{token:t,baseUrl:n}=await Vr(),i=`${n}/api${r}`;if(e.query&&typeof e.query=="object"){let a=new URLSearchParams;for(let[d,l]of Object.entries(e.query))l!=null&&l!==""&&a.set(d,String(l));let c=a.toString();c&&(i+=(i.includes("?")?"&":"?")+c)}let s={Authorization:`Bearer ${t}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},o=await fetch(i,{method:e.method||"GET",headers:s,body:e.body?JSON.stringify(e.body):void 0});return Qr(o,"OpenDesign")}async function Qr(r,e){if(!r.ok){let n=await r.text().catch(()=>""),i=n.slice(0,300);try{let s=JSON.parse(n),o=s?.code||s?.error?.code,a=s?.message||s?.error?.message||s?.error;(o||a)&&(i=[o?`[${o}]`:null,a].filter(Boolean).join(" ")||i)}catch{}throw new Error(`${e} API ${r.status}: ${i}`)}let t=await r.text().catch(()=>"");if(!t)return{};try{return JSON.parse(t)}catch{return{raw:t}}}var Xr={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)
308
+ - 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 r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);return{type:"stdio",command:"uvx",args:["plane-mcp-server","stdio"],env:r,description:this.description}}};import{existsSync as sa}from"fs";import{fileURLToPath as oa}from"url";import{dirname as aa,resolve as ca}from"path";import{resolveIntegrationToken as la}from"@zibby/core/backend-client.js";function da(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=aa(oa(import.meta.url)),e=ca(r,"..","bin","mcp-skill.mjs");return sa(e)?e:null}async function Xr(){let r=await la(I.OPEN_DESIGN),e=r?.token,t=r?.baseUrl;if(!e||typeof e!="string")throw new Error("OpenDesign is not connected: missing token. Connect it in Integrations.");if(!t||typeof t!="string")throw new Error("OpenDesign is not connected: missing baseUrl. Connect it in Integrations.");let n=t.replace(/\/+$/,"");return{token:e,baseUrl:n}}async function fe(r,e={}){let{token:t,baseUrl:n}=await Xr(),i=`${n}/api${r}`;if(e.query&&typeof e.query=="object"){let a=new URLSearchParams;for(let[d,l]of Object.entries(e.query))l!=null&&l!==""&&a.set(d,String(l));let c=a.toString();c&&(i+=(i.includes("?")?"&":"?")+c)}let s={Authorization:`Bearer ${t}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},o=await fetch(i,{method:e.method||"GET",headers:s,body:e.body?JSON.stringify(e.body):void 0});return en(o,"OpenDesign")}async function en(r,e){if(!r.ok){let n=await r.text().catch(()=>""),i=n.slice(0,300);try{let s=JSON.parse(n),o=s?.code||s?.error?.code,a=s?.message||s?.error?.message||s?.error;(o||a)&&(i=[o?`[${o}]`:null,a].filter(Boolean).join(" ")||i)}catch{}throw new Error(`${e} API ${r.status}: ${i}`)}let t=await r.text().catch(()=>"");if(!t)return{};try{return JSON.parse(t)}catch{return{raw:t}}}var tn={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)
309
309
  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__*):
310
310
 
311
311
  ### Connectivity
@@ -327,30 +327,30 @@ You may have access to the user's OpenDesign workspace (the Zibby-managed design
327
327
 
328
328
  ### Notes
329
329
  - A design artifact lookup ALWAYS needs its projectId (it scopes the query).
330
- - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let r=ra();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/opendesign.js","opendesignSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"opendesign_health":{let{baseUrl:t}=await Vr(),n=await fetch(`${t}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),i=await Qr(n,"OpenDesign");return JSON.stringify({ok:!0,health:i})}case"opendesign_list_projects":{let t=await fe("/projects");return JSON.stringify(t)}case"opendesign_get_project":{let t=e?.id||e?.projectId;if(!t)return JSON.stringify({error:"id is required"});let n=await fe(`/projects/${encodeURIComponent(t)}`);return JSON.stringify(n)}case"opendesign_list_designs":{let t=e?.projectId;if(!t)return JSON.stringify({error:"projectId is required"});let n=await fe("/live-artifacts",{query:{projectId:t}});return JSON.stringify(n)}case"opendesign_get_design":{let t=e?.id,n=e?.projectId;if(!t)return JSON.stringify({error:"id is required"});if(!n)return JSON.stringify({error:"projectId is required"});let i=await fe(`/live-artifacts/${encodeURIComponent(t)}`,{query:{projectId:n}});return JSON.stringify(i)}case"opendesign_export_pdf":{let t=e?.projectId||e?.id,{fileName:n,title:i,deck:s}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});if(!n)return JSON.stringify({error:"fileName is required"});let o={fileName:n};i!==void 0&&(o.title=i),s!==void 0&&(o.deck=s);let a=await fe(`/projects/${encodeURIComponent(t)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(a)}case"opendesign_export_html":{let t=e?.projectId||e?.id,n=e?.path;if(!t)return JSON.stringify({error:"projectId is required"});if(!n)return JSON.stringify({error:"path is required (the export sub-path)"});let s=String(n).replace(/^\/+/,"").split("/").map(a=>encodeURIComponent(a)).join("/"),o=await fe(`/projects/${encodeURIComponent(t)}/export/${s}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:t,message:n,projectId:i,conversationId:s,model:o}=e||{};if(!t)return JSON.stringify({error:"agentId is required"});if(!n)return JSON.stringify({error:"message is required"});let a={agentId:t,message:n};i!==void 0&&(a.projectId=i),s!==void 0&&(a.conversationId=s),o!==void 0&&(a.model=o);let c=await fe("/runs",{method:"POST",body:a});return JSON.stringify(c)}case"opendesign_cli_status":{let t=e?.id||e?.runId;if(!t)return JSON.stringify({error:"id (runId) is required"});let n=await fe(`/runs/${encodeURIComponent(t)}`);return JSON.stringify(n)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 na}from"fs";import{fileURLToPath as ia}from"url";import{dirname as sa,resolve as oa}from"path";import{resolveIntegrationToken as aa}from"@zibby/core/backend-client.js";function ca(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let r=sa(ia(import.meta.url)),e=oa(r,"..","bin","mcp-slack.mjs");return na(e)?e:null}async function G(r,e={}){let{token:t}=await aa("slack"),n=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(r),i=`https://slack.com/api/${r}`,s={Authorization:`Bearer ${t}`},o;if(n){let d=new URLSearchParams(e).toString();d&&(i+=`?${d}`)}else s["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(e);let c=await(await fetch(i,{method:n?"GET":"POST",headers:s,body:o})).json();if(!c.ok)throw new Error(`Slack API error: ${c.error}`);return c}var C={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:v.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
330
+ - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let r=da();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/opendesign.js","opendesignSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"opendesign_health":{let{baseUrl:t}=await Xr(),n=await fetch(`${t}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),i=await en(n,"OpenDesign");return JSON.stringify({ok:!0,health:i})}case"opendesign_list_projects":{let t=await fe("/projects");return JSON.stringify(t)}case"opendesign_get_project":{let t=e?.id||e?.projectId;if(!t)return JSON.stringify({error:"id is required"});let n=await fe(`/projects/${encodeURIComponent(t)}`);return JSON.stringify(n)}case"opendesign_list_designs":{let t=e?.projectId;if(!t)return JSON.stringify({error:"projectId is required"});let n=await fe("/live-artifacts",{query:{projectId:t}});return JSON.stringify(n)}case"opendesign_get_design":{let t=e?.id,n=e?.projectId;if(!t)return JSON.stringify({error:"id is required"});if(!n)return JSON.stringify({error:"projectId is required"});let i=await fe(`/live-artifacts/${encodeURIComponent(t)}`,{query:{projectId:n}});return JSON.stringify(i)}case"opendesign_export_pdf":{let t=e?.projectId||e?.id,{fileName:n,title:i,deck:s}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});if(!n)return JSON.stringify({error:"fileName is required"});let o={fileName:n};i!==void 0&&(o.title=i),s!==void 0&&(o.deck=s);let a=await fe(`/projects/${encodeURIComponent(t)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(a)}case"opendesign_export_html":{let t=e?.projectId||e?.id,n=e?.path;if(!t)return JSON.stringify({error:"projectId is required"});if(!n)return JSON.stringify({error:"path is required (the export sub-path)"});let s=String(n).replace(/^\/+/,"").split("/").map(a=>encodeURIComponent(a)).join("/"),o=await fe(`/projects/${encodeURIComponent(t)}/export/${s}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:t,message:n,projectId:i,conversationId:s,model:o}=e||{};if(!t)return JSON.stringify({error:"agentId is required"});if(!n)return JSON.stringify({error:"message is required"});let a={agentId:t,message:n};i!==void 0&&(a.projectId=i),s!==void 0&&(a.conversationId=s),o!==void 0&&(a.model=o);let c=await fe("/runs",{method:"POST",body:a});return JSON.stringify(c)}case"opendesign_cli_status":{let t=e?.id||e?.runId;if(!t)return JSON.stringify({error:"id (runId) is required"});let n=await fe(`/runs/${encodeURIComponent(t)}`);return JSON.stringify(n)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 pa}from"fs";import{fileURLToPath as ua}from"url";import{dirname as ma,resolve as fa}from"path";import{resolveIntegrationToken as ha}from"@zibby/core/backend-client.js";function ya(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let r=ma(ua(import.meta.url)),e=fa(r,"..","bin","mcp-slack.mjs");return pa(e)?e:null}async function G(r,e={}){let{token:t}=await ha("slack"),n=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(r),i=`https://slack.com/api/${r}`,s={Authorization:`Bearer ${t}`},o;if(n){let d=new URLSearchParams(e).toString();d&&(i+=`?${d}`)}else s["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(e);let c=await(await fetch(i,{method:n?"GET":"POST",headers:s,body:o})).json();if(!c.ok)throw new Error(`Slack API error: ${c.error}`);return c}var C={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:I.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
331
331
  You have access to the user's Slack workspace. Use these tools:
332
332
  - slack_list_channels, slack_post_message, slack_reply_to_thread
333
333
  - slack_add_reaction, slack_get_channel_history, slack_get_thread_replies
334
334
  - slack_get_users, slack_get_user_profile
335
335
  - slack_lookup_user_by_email (precise email\u2192user_id, prefer this over scanning slack_get_users)
336
- - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=ca();if(!r)return null;let e={};for(let t 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[t]&&(e[t]=process.env[t]);for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"slack_list_channels":{let t=await G("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(t.channels||[]).map(n=>({id:n.id,name:n.name,topic:n.topic?.value}))})}case"slack_post_message":{if(!e.channel||!e.text)return JSON.stringify({error:"channel and text are required"});let t=await G("chat.postMessage",{channel:e.channel,text:e.text,...e.blocks?{blocks:e.blocks}:{}});return JSON.stringify({ok:!0,ts:t.ts,channel:t.channel})}case"slack_reply_to_thread":{if(!e.channel||!e.thread_ts||!e.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let t=await G("chat.postMessage",{channel:e.channel,thread_ts:e.thread_ts,text:e.text});return JSON.stringify({ok:!0,ts:t.ts})}case"slack_add_reaction":return!e.channel||!e.timestamp||!e.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await G("reactions.add",{channel:e.channel,timestamp:e.timestamp,name:e.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!e.channel)return JSON.stringify({error:"channel is required"});let t=await G("conversations.history",{channel:e.channel,limit:e.limit||20});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_thread_replies":{if(!e.channel||!e.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let t=await G("conversations.replies",{channel:e.channel,ts:e.thread_ts});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_users":{let t=await G("users.list",{limit:100});return JSON.stringify({users:(t.members||[]).filter(n=>!n.is_bot&&!n.deleted).map(n=>({id:n.id,name:n.real_name||n.name}))})}case"slack_get_user_profile":{if(!e.user_id)return JSON.stringify({error:"user_id is required"});let t=await G("users.profile.get",{user:e.user_id});return JSON.stringify({profile:t.profile})}case"slack_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});try{let t=await G("users.lookupByEmail",{email:e.email});return JSON.stringify({ok:!0,user:{id:t.user?.id,name:t.user?.real_name||t.user?.name,email:t.user?.profile?.email||e.email}})}catch(t){if(/users_not_found/.test(t.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw t}}case"slack_list_usergroups":{let t=await G("usergroups.list",{});return JSON.stringify({usergroups:(t.usergroups||[]).map(n=>({id:n.id,handle:n.handle,name:n.name,description:n.description||"",user_count:Number(n.user_count||0)}))})}case"slack_get_usergroup_members":{if(!e.usergroup)return JSON.stringify({error:"usergroup id is required"});let t=await G("usergroups.users.list",{usergroup:e.usergroup});return JSON.stringify({users:t.users||[]})}case"slack_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),i=[],s,o=5;for(let c=0;c<o;c+=1){let d={limit:200};s&&(d.cursor=s);let l=await G("users.list",d);for(let p of l.members||[])p.deleted||p.is_bot||i.push(p);if(s=l.response_metadata?.next_cursor,!s)break}let a=[];for(let c of i){let d=(c.real_name||"").toLowerCase(),l=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;d.includes(t)&&(u+=100-Math.abs(d.length-t.length)),l.includes(t)&&(u+=60-Math.abs(l.length-t.length)),p.includes(t)&&(u+=30-Math.abs(p.length-t.length)),(d===t||l===t)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,n).map(({_score:c,...d})=>d),scanned:i.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 la}from"fs";import{fileURLToPath as da}from"url";import{dirname as pa,resolve as ua}from"path";import{resolveIntegrationToken as ma}from"@zibby/core/backend-client.js";function fa(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=pa(da(import.meta.url)),e=ua(r,"..","bin","mcp-lark.mjs");return la(e)?e:null}var ha=6e3*1e3,He=null;async function ga(){let{appId:r,appSecret:e,host:t}=await ma("lark");if(He&&He.appId===r&&He.expiresAt>Date.now())return{token:He.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return He={token:i.tenant_access_token,expiresAt:Date.now()+ha,appId:r},{token:i.tenant_access_token,host:t}}async function _e(r,e,t={}){let{token:n,host:i}=await ga(),s=`${i}${e}`,o={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(o.body=JSON.stringify(t));let c=await(await fetch(s,o)).json();if(c.code!==0)throw new Error(`Lark API ${e} error: ${c.msg||c.code}`);return c.data||{}}function en(r){return JSON.stringify({text:r})}function ya(r){return!r||typeof r!="string"||r.startsWith("oc_")?"chat_id":r.startsWith("ou_")?"open_id":r.startsWith("on_")?"union_id":r.startsWith("cli_")?"app_id":r.includes("@")?"email":"chat_id"}var ee={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)
336
+ - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=ya();if(!r)return null;let e={};for(let t 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[t]&&(e[t]=process.env[t]);for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"slack_list_channels":{let t=await G("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(t.channels||[]).map(n=>({id:n.id,name:n.name,topic:n.topic?.value}))})}case"slack_post_message":{if(!e.channel||!e.text)return JSON.stringify({error:"channel and text are required"});let t=await G("chat.postMessage",{channel:e.channel,text:e.text,...e.blocks?{blocks:e.blocks}:{}});return JSON.stringify({ok:!0,ts:t.ts,channel:t.channel})}case"slack_reply_to_thread":{if(!e.channel||!e.thread_ts||!e.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let t=await G("chat.postMessage",{channel:e.channel,thread_ts:e.thread_ts,text:e.text});return JSON.stringify({ok:!0,ts:t.ts})}case"slack_add_reaction":return!e.channel||!e.timestamp||!e.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await G("reactions.add",{channel:e.channel,timestamp:e.timestamp,name:e.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!e.channel)return JSON.stringify({error:"channel is required"});let t=await G("conversations.history",{channel:e.channel,limit:e.limit||20});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_thread_replies":{if(!e.channel||!e.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let t=await G("conversations.replies",{channel:e.channel,ts:e.thread_ts});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_users":{let t=await G("users.list",{limit:100});return JSON.stringify({users:(t.members||[]).filter(n=>!n.is_bot&&!n.deleted).map(n=>({id:n.id,name:n.real_name||n.name}))})}case"slack_get_user_profile":{if(!e.user_id)return JSON.stringify({error:"user_id is required"});let t=await G("users.profile.get",{user:e.user_id});return JSON.stringify({profile:t.profile})}case"slack_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});try{let t=await G("users.lookupByEmail",{email:e.email});return JSON.stringify({ok:!0,user:{id:t.user?.id,name:t.user?.real_name||t.user?.name,email:t.user?.profile?.email||e.email}})}catch(t){if(/users_not_found/.test(t.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw t}}case"slack_list_usergroups":{let t=await G("usergroups.list",{});return JSON.stringify({usergroups:(t.usergroups||[]).map(n=>({id:n.id,handle:n.handle,name:n.name,description:n.description||"",user_count:Number(n.user_count||0)}))})}case"slack_get_usergroup_members":{if(!e.usergroup)return JSON.stringify({error:"usergroup id is required"});let t=await G("usergroups.users.list",{usergroup:e.usergroup});return JSON.stringify({users:t.users||[]})}case"slack_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),i=[],s,o=5;for(let c=0;c<o;c+=1){let d={limit:200};s&&(d.cursor=s);let l=await G("users.list",d);for(let p of l.members||[])p.deleted||p.is_bot||i.push(p);if(s=l.response_metadata?.next_cursor,!s)break}let a=[];for(let c of i){let d=(c.real_name||"").toLowerCase(),l=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;d.includes(t)&&(u+=100-Math.abs(d.length-t.length)),l.includes(t)&&(u+=60-Math.abs(l.length-t.length)),p.includes(t)&&(u+=30-Math.abs(p.length-t.length)),(d===t||l===t)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,n).map(({_score:c,...d})=>d),scanned:i.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 ga}from"fs";import{fileURLToPath as _a}from"url";import{dirname as ba,resolve as ka}from"path";import{resolveIntegrationToken as wa}from"@zibby/core/backend-client.js";function Sa(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=ba(_a(import.meta.url)),e=ka(r,"..","bin","mcp-lark.mjs");return ga(e)?e:null}var va=6e3*1e3,He=null;async function Ia(){let{appId:r,appSecret:e,host:t}=await wa("lark");if(He&&He.appId===r&&He.expiresAt>Date.now())return{token:He.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return He={token:i.tenant_access_token,expiresAt:Date.now()+va,appId:r},{token:i.tenant_access_token,host:t}}async function _e(r,e,t={}){let{token:n,host:i}=await Ia(),s=`${i}${e}`,o={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(o.body=JSON.stringify(t));let c=await(await fetch(s,o)).json();if(c.code!==0)throw new Error(`Lark API ${e} error: ${c.msg||c.code}`);return c.data||{}}function rn(r){return JSON.stringify({text:r})}function Na(r){return!r||typeof r!="string"||r.startsWith("oc_")?"chat_id":r.startsWith("ou_")?"open_id":r.startsWith("on_")?"union_id":r.startsWith("cli_")?"app_id":r.includes("@")?"email":"chat_id"}var ee={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)
337
337
  You can send messages and replies on Lark. Use:
338
338
  - lark_send_message: post a message to a chat, user, or DM
339
339
  - lark_reply: reply to an existing message (threaded)
340
340
  - lark_list_chats: list chats the bot is a member of
341
341
  - lark_get_chat_history: fetch recent messages in a chat
342
342
  - 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)
343
- When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=fa();if(!r)return null;let e={};for(let t 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[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,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(r,e){try{switch(r){case"lark_send_message":{if(!e.receive_id||!e.text)return JSON.stringify({error:"receive_id and text are required"});let t=ya(e.receive_id),n=await _e("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:en(e.text)});return JSON.stringify({ok:!0,message_id:n.message_id})}case"lark_reply":{if(!e.message_id||!e.text)return JSON.stringify({error:"message_id and text are required"});let t=await _e("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:en(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,i=((await _e("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(s=>({chat_id:s.chat_id,name:s.name,description:s.description,owner_id:s.owner_id,chat_mode:s.chat_mode}));return JSON.stringify({chats:i})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,i=((await _e("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(s=>({message_id:s.message_id,sender_id:s.sender?.id,sender_type:s.sender?.sender_type,msg_type:s.msg_type,content:s.body?.content,create_time:s.create_time}));return JSON.stringify({messages:i})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let n=((await _e("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(i=>i.email===e.email&&i.user_id);return JSON.stringify(n?{ok:!0,user:{open_id:n.user_id,email:n.email,name:n.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),i=200,o=((await _e("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>=i)break;try{let p=await _e("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=i))break}catch(p){console.warn(`[lark] member scan failed for ${l}: ${p.message}`)}}let d=[];for(let l of c){let p=(l.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(t)&&(u+=100-Math.abs(p.length-t.length)),p===t&&(u+=200),u>0&&d.push({open_id:l.open_id,name:l.name,_score:u})}return d.sort((l,p)=>p._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,n).map(({_score:l,...p})=>p),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}}};import{existsSync as _a}from"fs";import{fileURLToPath as ba}from"url";import{dirname as ka,resolve as wa}from"path";import{resolveIntegrationToken as Sa}from"@zibby/core/backend-client.js";function Ia(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ka(ba(import.meta.url)),e=wa(r,"..","bin","mcp-skill.mjs");return _a(e)?e:null}var va=process.env.DISCORD_API_URL||"https://discord.com/api/v10",Na=2e3;function Oa(r,e=Na){let t=String(r??"");if(!t.trim())return[];if(t.length<=e)return[t];let n=[],i=t;for(;i.length>e;){let o=i.slice(0,e).lastIndexOf(`
344
- `),a=o>e/2?o+1:e;n.push(i.slice(0,a)),i=i.slice(a)}return i&&n.push(i),n}async function tn(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await Sa(v.DISCORD),t=(e&&e.token?String(e.token):"").trim();if(!t)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:t,guildId:(e.guildId||"").trim()}}async function Gt(r,e,{token:t,body:n}={}){let i=t.startsWith("Bot ")?t:`Bot ${t}`,s=await fetch(`${va}${e}`,{method:r,headers:{Authorization:i,...n!==void 0?{"Content-Type":"application/json"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),o=await s.json().catch(()=>null);if(!s.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${s.status}`;throw new Error(`Discord API error (${s.status}): ${a}`)}return o}async function Ra({token:r,guildId:e},t){let n=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(n)return n;let i=await Gt("GET","/users/@me/guilds",{token:r}),s=Array.isArray(i)?i:[];if(s.length===1)return s[0].id;if(s.length===0)throw new Error("The bot is not in any Discord server \u2014 invite it to a server first.");let o=s.slice(0,10).map(a=>`${a.name} (${a.id})`).join(", ");throw new Error(`The bot is in ${s.length} servers \u2014 pass guildId explicitly. Servers: ${o}`)}var rn={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)
343
+ When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=Sa();if(!r)return null;let e={};for(let t 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[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,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(r,e){try{switch(r){case"lark_send_message":{if(!e.receive_id||!e.text)return JSON.stringify({error:"receive_id and text are required"});let t=Na(e.receive_id),n=await _e("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:rn(e.text)});return JSON.stringify({ok:!0,message_id:n.message_id})}case"lark_reply":{if(!e.message_id||!e.text)return JSON.stringify({error:"message_id and text are required"});let t=await _e("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:rn(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,i=((await _e("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(s=>({chat_id:s.chat_id,name:s.name,description:s.description,owner_id:s.owner_id,chat_mode:s.chat_mode}));return JSON.stringify({chats:i})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,i=((await _e("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(s=>({message_id:s.message_id,sender_id:s.sender?.id,sender_type:s.sender?.sender_type,msg_type:s.msg_type,content:s.body?.content,create_time:s.create_time}));return JSON.stringify({messages:i})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let n=((await _e("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(i=>i.email===e.email&&i.user_id);return JSON.stringify(n?{ok:!0,user:{open_id:n.user_id,email:n.email,name:n.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),i=200,o=((await _e("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>=i)break;try{let p=await _e("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=i))break}catch(p){console.warn(`[lark] member scan failed for ${l}: ${p.message}`)}}let d=[];for(let l of c){let p=(l.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(t)&&(u+=100-Math.abs(p.length-t.length)),p===t&&(u+=200),u>0&&d.push({open_id:l.open_id,name:l.name,_score:u})}return d.sort((l,p)=>p._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,n).map(({_score:l,...p})=>p),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}}};import{existsSync as Oa}from"fs";import{fileURLToPath as Ta}from"url";import{dirname as Ra,resolve as Aa}from"path";import{resolveIntegrationToken as xa}from"@zibby/core/backend-client.js";function Ea(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ra(Ta(import.meta.url)),e=Aa(r,"..","bin","mcp-skill.mjs");return Oa(e)?e:null}var ja=process.env.DISCORD_API_URL||"https://discord.com/api/v10",La=2e3;function $a(r,e=La){let t=String(r??"");if(!t.trim())return[];if(t.length<=e)return[t];let n=[],i=t;for(;i.length>e;){let o=i.slice(0,e).lastIndexOf(`
344
+ `),a=o>e/2?o+1:e;n.push(i.slice(0,a)),i=i.slice(a)}return i&&n.push(i),n}async function nn(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await xa(I.DISCORD),t=(e&&e.token?String(e.token):"").trim();if(!t)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:t,guildId:(e.guildId||"").trim()}}async function Ht(r,e,{token:t,body:n}={}){let i=t.startsWith("Bot ")?t:`Bot ${t}`,s=await fetch(`${ja}${e}`,{method:r,headers:{Authorization:i,...n!==void 0?{"Content-Type":"application/json"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),o=await s.json().catch(()=>null);if(!s.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${s.status}`;throw new Error(`Discord API error (${s.status}): ${a}`)}return o}async function Pa({token:r,guildId:e},t){let n=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(n)return n;let i=await Ht("GET","/users/@me/guilds",{token:r}),s=Array.isArray(i)?i:[];if(s.length===1)return s[0].id;if(s.length===0)throw new Error("The bot is not in any Discord server \u2014 invite it to a server first.");let o=s.slice(0,10).map(a=>`${a.name} (${a.id})`).join(", ");throw new Error(`The bot is in ${s.length} servers \u2014 pass guildId explicitly. Servers: ${o}`)}var sn={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)
345
345
  You can post to the user's Discord server as their bot. Tools:
346
346
  - discord_send_message(channelId, text) \u2014 post a message to a channel (long text is auto-chunked to Discord's 2000-char limit)
347
- - 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 r={};for(let t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);for(let t 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[t]&&(r[t]=process.env[t]);let e=Ia();return e?{type:"stdio",command:"node",args:[e,"../dist/discord.js","discordSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,e={}){try{switch(r){case"discord_send_message":{let t=String(e.channelId||"").trim(),n=String(e.text||"");if(!t||!n.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let i=await tn(),s=Oa(n),o=[];for(let a of s){let c=await Gt("POST",`/channels/${encodeURIComponent(t)}/messages`,{token:i.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:t,messageIds:o,chunks:s.length})}case"discord_list_channels":{let t=await tn(),n=await Ra(t,e.guildId),i=await Gt("GET",`/guilds/${encodeURIComponent(n)}/channels`,{token:t.token}),s=(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:n,channels:s})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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 ln,statSync as Ta,readFileSync as Aa}from"fs";import{fileURLToPath as xa}from"url";import{basename as Ea,dirname as ja,resolve as La}from"path";import{resolveIntegrationToken as $a,clearTokenCache as Pa}from"@zibby/core/backend-client.js";function Ca(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ja(xa(import.meta.url)),e=La(r,"..","bin","mcp-skill.mjs");return ln(e)?e:null}var Ua="2022-06-28",qa="https://api.notion.com/v1",dt=2e4,nn=25,Ja=25,pt=100,sn=500,Da=20*1024*1024;function ae(r){if(!r||typeof r!="string")return null;let t=r.trim().split(/[?#]/)[0],n=t.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(n)return n[0].toLowerCase();let i=t.match(/[0-9a-fA-F]{32}/g);if(i&&i.length){let s=i[i.length-1].toLowerCase();return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}return null}async function te(r,e={}){let t=async()=>{let{token:n}=await $a("notion");if(typeof n!="string"||!n)throw new Error(`Invalid notion token type: ${typeof n}`);let i=await fetch(`${qa}${r}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"Notion-Version":Ua,Accept:"application/json",...e.body&&!e.formData?{"Content-Type":"application/json"}:{},...e.headers},body:e.formData?e.formData:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Notion API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Pa("notion"),t()}}function $e(r){if(!Array.isArray(r))return"";let e="";for(let t of r){let n=t?.plain_text??t?.text?.content??"";if(!n)continue;let i=t.annotations||{};i.code&&(n=`\`${n}\``),i.bold&&(n=`**${n}**`),i.italic&&(n=`_${n}_`),i.strikethrough&&(n=`~~${n}~~`);let s=t?.href||t?.text?.link?.url;s&&(n=`[${n}](${s})`),e+=n}return e}function Ba(r,e,t){let n=r?.type,i=r?.[n]||{},s=" ".repeat(Math.max(0,e)),o=(d="rich_text")=>$e(i[d]),a;switch(n){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=`${s}- ${o()}`;break;case"numbered_list_item":a=`${s}1. ${o()}`;break;case"to_do":a=`${s}- [${i.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${s}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${i.icon?.emoji?`${i.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${i.language||""}
347
+ - 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 r={};for(let t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);for(let t 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[t]&&(r[t]=process.env[t]);let e=Ea();return e?{type:"stdio",command:"node",args:[e,"../dist/discord.js","discordSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,e={}){try{switch(r){case"discord_send_message":{let t=String(e.channelId||"").trim(),n=String(e.text||"");if(!t||!n.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let i=await nn(),s=$a(n),o=[];for(let a of s){let c=await Ht("POST",`/channels/${encodeURIComponent(t)}/messages`,{token:i.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:t,messageIds:o,chunks:s.length})}case"discord_list_channels":{let t=await nn(),n=await Pa(t,e.guildId),i=await Ht("GET",`/guilds/${encodeURIComponent(n)}/channels`,{token:t.token}),s=(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:n,channels:s})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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 pn,statSync as Ca,readFileSync as Ua}from"fs";import{fileURLToPath as Ja}from"url";import{basename as qa,dirname as Da,resolve as Ba}from"path";import{resolveIntegrationToken as Ma,clearTokenCache as Fa}from"@zibby/core/backend-client.js";function Ga(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Da(Ja(import.meta.url)),e=Ba(r,"..","bin","mcp-skill.mjs");return pn(e)?e:null}var Ka="2022-06-28",Ha="https://api.notion.com/v1",dt=2e4,on=25,za=25,pt=100,an=500,Ya=20*1024*1024;function ae(r){if(!r||typeof r!="string")return null;let t=r.trim().split(/[?#]/)[0],n=t.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(n)return n[0].toLowerCase();let i=t.match(/[0-9a-fA-F]{32}/g);if(i&&i.length){let s=i[i.length-1].toLowerCase();return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}return null}async function te(r,e={}){let t=async()=>{let{token:n}=await Ma("notion");if(typeof n!="string"||!n)throw new Error(`Invalid notion token type: ${typeof n}`);let i=await fetch(`${Ha}${r}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"Notion-Version":Ka,Accept:"application/json",...e.body&&!e.formData?{"Content-Type":"application/json"}:{},...e.headers},body:e.formData?e.formData:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Notion API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Fa("notion"),t()}}function $e(r){if(!Array.isArray(r))return"";let e="";for(let t of r){let n=t?.plain_text??t?.text?.content??"";if(!n)continue;let i=t.annotations||{};i.code&&(n=`\`${n}\``),i.bold&&(n=`**${n}**`),i.italic&&(n=`_${n}_`),i.strikethrough&&(n=`~~${n}~~`);let s=t?.href||t?.text?.link?.url;s&&(n=`[${n}](${s})`),e+=n}return e}function Wa(r,e,t){let n=r?.type,i=r?.[n]||{},s=" ".repeat(Math.max(0,e)),o=(d="rich_text")=>$e(i[d]),a;switch(n){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=`${s}- ${o()}`;break;case"numbered_list_item":a=`${s}1. ${o()}`;break;case"to_do":a=`${s}- [${i.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${s}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${i.icon?.emoji?`${i.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${i.language||""}
348
348
  ${o()}
349
349
  \`\`\``;break}case"divider":a="---";break;case"child_page":a=`[child page: ${i.title||""}]`;break;case"child_database":a=`[child database: ${i.title||""}]`;break;case"bookmark":case"embed":case"link_preview":a=i.url?`<${i.url}>`:"";break;case"equation":a=i.expression?`$${i.expression}$`:"";break;case"table":case"column_list":case"column":a="";break;case"table_row":{let d=(i.cells||[]).map(l=>$e(l).trim());a=`${s}| ${d.join(" | ")} |`;break}default:a=o();break}let c=[];return a&&a.trim()&&c.push(a),t&&t.trim()&&c.push(t),c.join(`
350
- `)}async function dn(r,e,t){let n=[],i,s=0;do{if(t.used>=dt)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let a=await te(`/blocks/${r}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await dn(d.id,e+1,t));let p=Ba(d,e,l);if(p&&(n.push(p),t.used+=p.length+1),t.used>=dt)break}i=a.has_more?a.next_cursor:void 0,s+=1}while(i&&s<Ja);return n.join(`
351
- `)}function on(r){let e=r?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let n=$e(t.title).trim();if(n)return n}return""}function ze(r){let e=String(r??"");if(!e)return[{type:"text",text:{content:""}}];let t=[];for(let n=0;n<e.length;n+=2e3)t.push({type:"text",text:{content:e.slice(n,n+2e3)}});return t}function Ma(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:$e(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function Fa(r){if(!r||!r.type)return"";switch(r.type){case"title":return $e(r.title).trim();case"rich_text":return $e(r.rich_text).trim();case"number":return r.number==null?"":String(r.number);case"select":return r.select?.name||"";case"status":return r.status?.name||"";case"multi_select":return(r.multi_select||[]).map(t=>t.name).join(", ");case"checkbox":return r.checkbox?"true":"false";case"url":return r.url||"";case"email":return r.email||"";case"phone_number":return r.phone_number||"";case"date":return r.date?.start||"";case"people":return(r.people||[]).map(t=>t.name||t.id).join(", ");default:return""}}function Kt(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function Ga(r){let e=String(r??"").replace(/\r\n/g,`
350
+ `)}async function un(r,e,t){let n=[],i,s=0;do{if(t.used>=dt)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let a=await te(`/blocks/${r}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await un(d.id,e+1,t));let p=Wa(d,e,l);if(p&&(n.push(p),t.used+=p.length+1),t.used>=dt)break}i=a.has_more?a.next_cursor:void 0,s+=1}while(i&&s<za);return n.join(`
351
+ `)}function cn(r){let e=r?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let n=$e(t.title).trim();if(n)return n}return""}function ze(r){let e=String(r??"");if(!e)return[{type:"text",text:{content:""}}];let t=[];for(let n=0;n<e.length;n+=2e3)t.push({type:"text",text:{content:e.slice(n,n+2e3)}});return t}function Za(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:$e(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function Va(r){if(!r||!r.type)return"";switch(r.type){case"title":return $e(r.title).trim();case"rich_text":return $e(r.rich_text).trim();case"number":return r.number==null?"":String(r.number);case"select":return r.select?.name||"";case"status":return r.status?.name||"";case"multi_select":return(r.multi_select||[]).map(t=>t.name).join(", ");case"checkbox":return r.checkbox?"true":"false";case"url":return r.url||"";case"email":return r.email||"";case"phone_number":return r.phone_number||"";case"date":return r.date?.start||"";case"people":return(r.people||[]).map(t=>t.name||t.id).join(", ");default:return""}}function zt(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function Qa(r){let e=String(r??"").replace(/\r\n/g,`
352
352
  `),t=[];for(let n of e.split(`
353
- `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d;s?(c=`heading_${s[1].length}`,d=s[2]):o?(c="bulleted_list_item",d=o[1]):a?(c="numbered_list_item",d=a[1]):(c="paragraph",d=i),t.push({object:"block",type:c,[c]:{rich_text:ze(d)}})}return t}function an(r){return Array.isArray(r?.blocks)&&r.blocks.length?r.blocks.slice(0,sn):typeof r?.markdown=="string"&&r.markdown.trim()?Ga(r.markdown).slice(0,sn):null}async function cn(r,e){for(let t=0;t<e.length;t+=pt)await te(`/blocks/${r}/children`,{method:"PATCH",body:{children:e.slice(t,t+pt)}})}function Ka(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!ln(e)||!Ta(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=Aa(e);if(t.length>Da)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return t}async function Ha(r){let e=Ka(r),t=Ea(r.trim()),n=/\.png$/i.test(t)?"image/png":"image/jpeg",s=(await te("/file_uploads",{method:"POST",body:{mode:"single_part",filename:t}}))?.id;if(!s)throw new Error("Notion file upload create returned no id");let o=new FormData;return o.set("file",new Blob([e],{type:n}),t),await te(`/file_uploads/${s}/send`,{method:"POST",formData:o}),s}var pn={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:v.NOTION,description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion (connected)
353
+ `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d;s?(c=`heading_${s[1].length}`,d=s[2]):o?(c="bulleted_list_item",d=o[1]):a?(c="numbered_list_item",d=a[1]):(c="paragraph",d=i),t.push({object:"block",type:c,[c]:{rich_text:ze(d)}})}return t}function ln(r){return Array.isArray(r?.blocks)&&r.blocks.length?r.blocks.slice(0,an):typeof r?.markdown=="string"&&r.markdown.trim()?Qa(r.markdown).slice(0,an):null}async function dn(r,e){for(let t=0;t<e.length;t+=pt)await te(`/blocks/${r}/children`,{method:"PATCH",body:{children:e.slice(t,t+pt)}})}function Xa(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!pn(e)||!Ca(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=Ua(e);if(t.length>Ya)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return t}async function ec(r){let e=Xa(r),t=qa(r.trim()),n=/\.png$/i.test(t)?"image/png":"image/jpeg",s=(await te("/file_uploads",{method:"POST",body:{mode:"single_part",filename:t}}))?.id;if(!s)throw new Error("Notion file upload create returned no id");let o=new FormData;return o.set("file",new Blob([e],{type:n}),t),await te(`/file_uploads/${s}/send`,{method:"POST",formData:o}),s}var mn={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:I.NOTION,description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion (connected)
354
354
  You can read Notion content as context AND write to Notion (create pages, append blocks, insert images).
355
355
  - 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.
356
356
  - 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.
@@ -359,7 +359,7 @@ You can read Notion content as context AND write to Notion (create pages, append
359
359
  - notion_insert_image: append an image block to a page. Pass { pageId, imagePath } for a LOCAL png/jpg file (\u226420MB, uploaded via Notion's File Upload API) or { pageId, imageUrl } for an external, publicly reachable image URL. Optional caption. Returns { ok, pageId, url }.
360
360
  - 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.
361
361
  - 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.
362
- 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" / "cannot deliver to Notion" and continue.`,resolve(){let r=Ca();return r?{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,n=ae(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await te(`/pages/${n}`),s=on(i),o=i?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,c=await dn(n,0,{used:0}),d=!1;return c.length>dt&&(c=c.slice(0,dt),d=!0),JSON.stringify({ok:!0,id:n,title:s,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,n=ae(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let s={page_size:Math.max(1,Math.min(Number(e?.maxResults)||nn,nn))};e?.filter&&typeof e.filter=="object"&&(s.filter=e.filter);let o=await te(`/databases/${n}/query`,{method:"POST",body:s}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[p,u]of Object.entries(d.properties||{})){let m=Fa(u);m&&(l[p]=m)}return{id:d.id,title:on(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:n,count:c.length,hasMore:!!o.has_more,rows:c})}case"notion_create_page":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let n=e?.databaseId?ae(e.databaseId):null,i=e?.parentPageId?ae(e.parentPageId):ae(e?.parent||e?.pageId);if(!n&&!i)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let s=n?{database_id:n}:{page_id:i},o={title:{title:ze(t)}},a=an(e)||[],c=a.slice(0,pt),d=await te("/pages",{method:"POST",body:{parent:s,properties:o,...c.length?{children:c}:{}}}),l=d?.id;if(!l)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let p=a.slice(pt);return p.length&&await cn(l,p),JSON.stringify({ok:!0,pageId:l,url:d?.url||Kt(l)})}case"notion_append_blocks":{let t=ae(e?.pageId||e?.blockId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=an(e);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await cn(t,n),JSON.stringify({ok:!0,pageId:t,url:Kt(t)}))}case"notion_insert_image":{let t=ae(e?.pageId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=typeof e?.caption=="string"&&e.caption.trim()?ze(e.caption.trim()):null,i,s;if(typeof e?.imagePath=="string"&&e.imagePath.trim())s=await Ha(e.imagePath),i={type:"file_upload",file_upload:{id:s}};else if(typeof e?.imageUrl=="string"&&e.imageUrl.trim())i={type:"external",external:{url:e.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return n&&(i.caption=n),await te(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:i}]}}),JSON.stringify({ok:!0,pageId:t,url:Kt(t),...s?{fileUploadId:s}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,n=ae(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let i=new URLSearchParams({block_id:n,page_size:"100"}),s=await te(`/comments?${i.toString()}`),a=(Array.isArray(s.results)?s.results:[]).map(Ma);return JSON.stringify({ok:!0,id:n,count:a.length,comments:a})}case"notion_add_comment":{let t=typeof e?.text=="string"?e.text:typeof e?.body=="string"?e.body:"";if(!t||!t.trim())return JSON.stringify({ok:!1,error:"text is required"});let n=e?.discussionId||e?.discussion_id||null,i;if(n)i={discussion_id:String(n),rich_text:ze(t)};else{let o=e?.pageId||e?.page||e?.url||e?.id,a=ae(o);if(!a)return JSON.stringify({ok:!1,error:"Either discussionId (to reply) or a valid pageId (to start a comment) is required"});i={parent:{page_id:a},rich_text:ze(t)}}let s=await te("/comments",{method:"POST",body:i});return JSON.stringify({ok:!0,id:s?.id||"",discussionId:s?.discussion_id||n||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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_create_page",description:"Create a new Notion page under a parent page (parentPageId) OR in a database (databaseId) \u2014 exactly one parent is required. Body from markdown (#/##/### headings, - bullets, 1. ordered lists; inline marks kept as literal text) or raw Notion block objects. Long bodies are chunked automatically (Notion caps 100 blocks/request). Returns { ok, pageId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{parentPageId:{type:"string",description:"Parent PAGE id/URL to create the page under (used when databaseId is absent)."},databaseId:{type:"string",description:"Parent DATABASE id/URL to create the page in (title goes into the title property)."},title:{type:"string",description:"Page title."},markdown:{type:"string",description:"Page body as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["title"]}},{name:"notion_append_blocks",description:"Append markdown (or raw Notion blocks) to the END of an existing Notion page. Accepts a page id or full Notion URL. Chunks automatically at Notion's 100-blocks-per-request cap. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["pageId"]}},{name:"notion_insert_image",description:"Append an image block to a Notion page. Pass imagePath for a LOCAL .png/.jpg file (max 20MB \u2014 uploaded via Notion's File Upload API, stored by Notion) or imageUrl for an external publicly-reachable image URL. Optional caption. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 20MB). Preferred for locally rendered charts."},imageUrl:{type:"string",description:"External image URL (must be publicly reachable; used when imagePath is absent)."},caption:{type:"string",description:"Optional image caption."}},required:["pageId"]}},{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 za,readFileSync as Wa}from"fs";import{fileURLToPath as Ya}from"url";import{dirname as Za,resolve as Va}from"path";import{resolveIntegrationToken as Ht,clearTokenCache as Qa}from"@zibby/core/backend-client.js";function Xa(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Za(Ya(import.meta.url)),e=Va(r,"..","bin","mcp-skill.mjs");return za(e)?e:null}function ec(){let r=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!r)return null;let e=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:r,memberId:e}}function tc(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function rc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var nc="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 zt(){let r=ec();if(r)return r;if(tc()||rc())throw new Error(nc);return null}var ic="202506",sc="https://api.linkedin.com";function un(r){if(r==null)return null;let e=String(r).trim();if(!e)return null;let t=e.match(/urn:li:organization:(\d+)/i);return t?t[1]:/^\d+$/.test(e)?e:null}function mn(r){if(!r)return"";if(r.localizedName)return String(r.localizedName);let e=r.name&&r.name.localized;if(e&&typeof e=="object"){let t=Object.values(e)[0];if(t)return String(t)}return""}function ut(r,e){return r?typeof r.get=="function"?r.get(e):r[e]||r[e.toLowerCase()]||null:null}async function be(r,e={},t="linkedin_business"){let n=async()=>{let i;if(t==="linkedin_personal"){let d=zt();d&&(i=d.token)}if(i||({token:i}=await Ht(t)),typeof i!="string"||!i)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let s=r.startsWith("https://")?r:`${sc}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,"LinkedIn-Version":ic,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.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 n()}catch(i){let s=String(i?.message||i||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw i;return Qa(t),n()}}async function oc(r){let e;if(r==="linkedin_personal"){let t=zt();t&&(e=t.token)}if(e||({token:e}=await Ht(r)),typeof e!="string"||!e)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return e}function ac(r){switch(String(r||"").toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]){case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";default:return"image/png"}}async function fn(r,e,t,n){if(typeof t!="string"||!t.trim())throw new Error("imagePath (a local image file path) is required to upload an image");let{body:i}=await be("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:e}}},r),s=i?.value?.uploadUrl,o=i?.value?.image;if(!s||!o)throw new Error(`LinkedIn image initializeUpload returned no uploadUrl/image (got: ${JSON.stringify(i).slice(0,200)})`);let a=Wa(t),c=await oc(r),d=await fetch(s,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":n||ac(t)},body:a});if(!d.ok){let l=await d.text().catch(()=>"");throw new Error(`LinkedIn image upload ${d.status}: ${l.slice(0,300)}`)}return o}var hn={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)
362
+ 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" / "cannot deliver to Notion" and continue.`,resolve(){let r=Ga();return r?{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,n=ae(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await te(`/pages/${n}`),s=cn(i),o=i?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,c=await un(n,0,{used:0}),d=!1;return c.length>dt&&(c=c.slice(0,dt),d=!0),JSON.stringify({ok:!0,id:n,title:s,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,n=ae(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let s={page_size:Math.max(1,Math.min(Number(e?.maxResults)||on,on))};e?.filter&&typeof e.filter=="object"&&(s.filter=e.filter);let o=await te(`/databases/${n}/query`,{method:"POST",body:s}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[p,u]of Object.entries(d.properties||{})){let m=Va(u);m&&(l[p]=m)}return{id:d.id,title:cn(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:n,count:c.length,hasMore:!!o.has_more,rows:c})}case"notion_create_page":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let n=e?.databaseId?ae(e.databaseId):null,i=e?.parentPageId?ae(e.parentPageId):ae(e?.parent||e?.pageId);if(!n&&!i)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let s=n?{database_id:n}:{page_id:i},o={title:{title:ze(t)}},a=ln(e)||[],c=a.slice(0,pt),d=await te("/pages",{method:"POST",body:{parent:s,properties:o,...c.length?{children:c}:{}}}),l=d?.id;if(!l)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let p=a.slice(pt);return p.length&&await dn(l,p),JSON.stringify({ok:!0,pageId:l,url:d?.url||zt(l)})}case"notion_append_blocks":{let t=ae(e?.pageId||e?.blockId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=ln(e);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await dn(t,n),JSON.stringify({ok:!0,pageId:t,url:zt(t)}))}case"notion_insert_image":{let t=ae(e?.pageId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=typeof e?.caption=="string"&&e.caption.trim()?ze(e.caption.trim()):null,i,s;if(typeof e?.imagePath=="string"&&e.imagePath.trim())s=await ec(e.imagePath),i={type:"file_upload",file_upload:{id:s}};else if(typeof e?.imageUrl=="string"&&e.imageUrl.trim())i={type:"external",external:{url:e.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return n&&(i.caption=n),await te(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:i}]}}),JSON.stringify({ok:!0,pageId:t,url:zt(t),...s?{fileUploadId:s}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,n=ae(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let i=new URLSearchParams({block_id:n,page_size:"100"}),s=await te(`/comments?${i.toString()}`),a=(Array.isArray(s.results)?s.results:[]).map(Za);return JSON.stringify({ok:!0,id:n,count:a.length,comments:a})}case"notion_add_comment":{let t=typeof e?.text=="string"?e.text:typeof e?.body=="string"?e.body:"";if(!t||!t.trim())return JSON.stringify({ok:!1,error:"text is required"});let n=e?.discussionId||e?.discussion_id||null,i;if(n)i={discussion_id:String(n),rich_text:ze(t)};else{let o=e?.pageId||e?.page||e?.url||e?.id,a=ae(o);if(!a)return JSON.stringify({ok:!1,error:"Either discussionId (to reply) or a valid pageId (to start a comment) is required"});i={parent:{page_id:a},rich_text:ze(t)}}let s=await te("/comments",{method:"POST",body:i});return JSON.stringify({ok:!0,id:s?.id||"",discussionId:s?.discussion_id||n||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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_create_page",description:"Create a new Notion page under a parent page (parentPageId) OR in a database (databaseId) \u2014 exactly one parent is required. Body from markdown (#/##/### headings, - bullets, 1. ordered lists; inline marks kept as literal text) or raw Notion block objects. Long bodies are chunked automatically (Notion caps 100 blocks/request). Returns { ok, pageId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{parentPageId:{type:"string",description:"Parent PAGE id/URL to create the page under (used when databaseId is absent)."},databaseId:{type:"string",description:"Parent DATABASE id/URL to create the page in (title goes into the title property)."},title:{type:"string",description:"Page title."},markdown:{type:"string",description:"Page body as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["title"]}},{name:"notion_append_blocks",description:"Append markdown (or raw Notion blocks) to the END of an existing Notion page. Accepts a page id or full Notion URL. Chunks automatically at Notion's 100-blocks-per-request cap. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["pageId"]}},{name:"notion_insert_image",description:"Append an image block to a Notion page. Pass imagePath for a LOCAL .png/.jpg file (max 20MB \u2014 uploaded via Notion's File Upload API, stored by Notion) or imageUrl for an external publicly-reachable image URL. Optional caption. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 20MB). Preferred for locally rendered charts."},imageUrl:{type:"string",description:"External image URL (must be publicly reachable; used when imagePath is absent)."},caption:{type:"string",description:"Optional image caption."}},required:["pageId"]}},{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 tc,readFileSync as rc}from"fs";import{fileURLToPath as nc}from"url";import{dirname as ic,resolve as sc}from"path";import{resolveIntegrationToken as Yt,clearTokenCache as oc}from"@zibby/core/backend-client.js";function ac(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ic(nc(import.meta.url)),e=sc(r,"..","bin","mcp-skill.mjs");return tc(e)?e:null}function cc(){let r=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!r)return null;let e=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:r,memberId:e}}function lc(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function dc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var pc="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 Wt(){let r=cc();if(r)return r;if(lc()||dc())throw new Error(pc);return null}var uc="202506",mc="https://api.linkedin.com";function fn(r){if(r==null)return null;let e=String(r).trim();if(!e)return null;let t=e.match(/urn:li:organization:(\d+)/i);return t?t[1]:/^\d+$/.test(e)?e:null}function hn(r){if(!r)return"";if(r.localizedName)return String(r.localizedName);let e=r.name&&r.name.localized;if(e&&typeof e=="object"){let t=Object.values(e)[0];if(t)return String(t)}return""}function ut(r,e){return r?typeof r.get=="function"?r.get(e):r[e]||r[e.toLowerCase()]||null:null}async function be(r,e={},t="linkedin_business"){let n=async()=>{let i;if(t==="linkedin_personal"){let d=Wt();d&&(i=d.token)}if(i||({token:i}=await Yt(t)),typeof i!="string"||!i)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let s=r.startsWith("https://")?r:`${mc}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,"LinkedIn-Version":uc,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.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 n()}catch(i){let s=String(i?.message||i||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw i;return oc(t),n()}}async function fc(r){let e;if(r==="linkedin_personal"){let t=Wt();t&&(e=t.token)}if(e||({token:e}=await Yt(r)),typeof e!="string"||!e)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return e}function hc(r){switch(String(r||"").toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]){case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";default:return"image/png"}}async function yn(r,e,t,n){if(typeof t!="string"||!t.trim())throw new Error("imagePath (a local image file path) is required to upload an image");let{body:i}=await be("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:e}}},r),s=i?.value?.uploadUrl,o=i?.value?.image;if(!s||!o)throw new Error(`LinkedIn image initializeUpload returned no uploadUrl/image (got: ${JSON.stringify(i).slice(0,200)})`);let a=rc(t),c=await fc(r),d=await fetch(s,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":n||hc(t)},body:a});if(!d.ok){let l=await d.text().catch(()=>"");throw new Error(`LinkedIn image upload ${d.status}: ${l.slice(0,300)}`)}return o}var gn={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)
363
363
  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.
364
364
 
365
365
  Business (company Page) \u2014 DRAFT only:
@@ -375,10 +375,10 @@ Attaching an image (optional, both tools):
375
375
  Notes:
376
376
  - Org-page posts are ALWAYS created as a DRAFT; personal-profile posts are ALWAYS published live \u2014 choose the tool accordingly.
377
377
  - 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.
378
- - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=Xa();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/linkedin.js","linkedinSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"linkedin_list_organizations":{let{body:t}=await be("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(t.elements)?t.elements:[],i=[];for(let s of n){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=un(o);if(!a)continue;let c="",d="";try{let l=(await be(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=mn(l),d=l.vanityName||""}catch{}i.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:i.length,organizations:i})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,n=un(t);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u="";try{let m=(await be(`/rest/organizations/${n}`,{},"linkedin_business")).body;u=mn(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:n,urn:o},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await fn("linkedin_business",o,a);d.content={media:{id:u,altText:c||""}}}let l=await be("/rest/posts",{method:"POST",body:d},"linkedin_business"),p=ut(l.headers,"x-restli-id")||ut(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"DRAFT",visibility:s,status:l.status})}case"linkedin_publish_post":{let t=zt(),n=t?t.memberId:(await Ht("linkedin_personal")).memberId;if(!n)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u=(await be("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",f=u?.sub?String(u.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await fn("linkedin_personal",o,a);d.content={media:{id:u,altText:c||""}}}let l=await be("/rest/posts",{method:"POST",body:d},"linkedin_personal"),p=ut(l.headers,"x-restli-id")||ut(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"PUBLISHED",visibility:s,status:l.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. 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 or uploaded (a set imagePath is reported as imageWouldAttach:true).",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."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},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 or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. 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. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. 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 or uploaded (a set imagePath is reported as imageWouldAttach:true).",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."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},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 or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}}]};import{existsSync as bn,statSync as cc,readFileSync as lc}from"fs";import{fileURLToPath as dc}from"url";import{basename as pc,dirname as uc,resolve as mc}from"path";import{resolveIntegrationToken as fc,clearTokenCache as hc}from"@zibby/core/backend-client.js";function gc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=uc(dc(import.meta.url)),e=mc(r,"..","bin","mcp-skill.mjs");return bn(e)?e:null}var ke="https://docs.googleapis.com/v1",gn="https://www.googleapis.com/drive/v3",yc="https://www.googleapis.com/upload/drive/v3",_c=5*1024*1024;function bc(){let r=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!r)return null;let e=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:r,email:e}}function kc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function wc(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Sc="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.",Yt=2e4,Ic=25;function Wt(r){if(!r||typeof r!="string")return null;let e=r.trim(),t=e.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return t?t[1]:/^[a-zA-Z0-9_-]{20,}$/.test(e)?e:null}async function vc(){let r,e=bc();if(e)r=e.token;else{if(wc()||kc())throw new Error(Sc);({token:r}=await fc("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function re(r,e={}){let t=async()=>{let n=await vc(),i=await fetch(r,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Google API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return hc("google"),t()}}function Nc(r){let e=[],t="",n=0;for(;n<r.length;){let i=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(i){e.push({start:t.length,end:t.length+i[1].length,link:i[2]}),t+=i[1],n+=i[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(s){e.push({start:t.length,end:t.length+s[1].length,bold:!0}),t+=s[1],n+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(n));if(o){e.push({start:t.length,end:t.length+o[1].length,code:!0}),t+=o[1],n+=o[0].length;continue}t+=r[n],n+=1}return{text:t,styles:e}}function yn(r,e){let t=String(r??"").replace(/\r\n/g,`
378
+ - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=ac();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/linkedin.js","linkedinSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"linkedin_list_organizations":{let{body:t}=await be("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(t.elements)?t.elements:[],i=[];for(let s of n){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=fn(o);if(!a)continue;let c="",d="";try{let l=(await be(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=hn(l),d=l.vanityName||""}catch{}i.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:i.length,organizations:i})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,n=fn(t);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u="";try{let m=(await be(`/rest/organizations/${n}`,{},"linkedin_business")).body;u=hn(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:n,urn:o},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await yn("linkedin_business",o,a);d.content={media:{id:u,altText:c||""}}}let l=await be("/rest/posts",{method:"POST",body:d},"linkedin_business"),p=ut(l.headers,"x-restli-id")||ut(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"DRAFT",visibility:s,status:l.status})}case"linkedin_publish_post":{let t=Wt(),n=t?t.memberId:(await Yt("linkedin_personal")).memberId;if(!n)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u=(await be("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",f=u?.sub?String(u.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await yn("linkedin_personal",o,a);d.content={media:{id:u,altText:c||""}}}let l=await be("/rest/posts",{method:"POST",body:d},"linkedin_personal"),p=ut(l.headers,"x-restli-id")||ut(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"PUBLISHED",visibility:s,status:l.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. 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 or uploaded (a set imagePath is reported as imageWouldAttach:true).",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."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},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 or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. 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. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. 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 or uploaded (a set imagePath is reported as imageWouldAttach:true).",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."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},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 or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}}]};import{existsSync as wn,statSync as yc,readFileSync as gc}from"fs";import{fileURLToPath as _c}from"url";import{basename as bc,dirname as kc,resolve as wc}from"path";import{resolveIntegrationToken as Sc,clearTokenCache as vc}from"@zibby/core/backend-client.js";function Ic(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=kc(_c(import.meta.url)),e=wc(r,"..","bin","mcp-skill.mjs");return wn(e)?e:null}var ke="https://docs.googleapis.com/v1",_n="https://www.googleapis.com/drive/v3",Nc="https://www.googleapis.com/upload/drive/v3",Oc=5*1024*1024;function Tc(){let r=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!r)return null;let e=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:r,email:e}}function Rc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Ac(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var xc="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.",Vt=2e4,Ec=25;function Zt(r){if(!r||typeof r!="string")return null;let e=r.trim(),t=e.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return t?t[1]:/^[a-zA-Z0-9_-]{20,}$/.test(e)?e:null}async function jc(){let r,e=Tc();if(e)r=e.token;else{if(Ac()||Rc())throw new Error(xc);({token:r}=await Sc("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function re(r,e={}){let t=async()=>{let n=await jc(),i=await fetch(r,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Google API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return vc("google"),t()}}function Lc(r){let e=[],t="",n=0;for(;n<r.length;){let i=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(i){e.push({start:t.length,end:t.length+i[1].length,link:i[2]}),t+=i[1],n+=i[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(s){e.push({start:t.length,end:t.length+s[1].length,bold:!0}),t+=s[1],n+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(n));if(o){e.push({start:t.length,end:t.length+o[1].length,code:!0}),t+=o[1],n+=o[0].length;continue}t+=r[n],n+=1}return{text:t,styles:e}}function bn(r,e){let t=String(r??"").replace(/\r\n/g,`
379
379
  `);if(!t.trim())return{requests:[],endIndex:e};let n=t.split(`
380
- `),i="",s=[],o=[];for(let l of n){let p=l,u=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(p),h=/^\s*[-*]\s+(.*)$/.exec(p),y=/^\s*\d+[.)]\s+(.*)$/.exec(p);f?(u=`HEADING_${f[1].length}`,p=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",p=h[1]):y&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",p=y[1]);let{text:_,styles:b}=Nc(p),g=e+i.length;for(let k of b)o.push({...k,start:g+k.start,end:g+k.end});i+=`${_}
381
- `,s.push({start:g,end:e+i.length,named:u,bullet:m})}if(!i)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:i}}];for(let l of s)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 s)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:e+i.length}}function Oc(r){let e="",t=n=>{for(let i of Array.isArray(n)?n:[]){if(e.length>=Yt)return;if(i.paragraph)for(let s of i.paragraph.elements||[])e+=s?.textRun?.content||"";else if(i.table)for(let s of i.table.tableRows||[])for(let o of s.tableCells||[])t(o.content);else i.tableOfContents&&t(i.tableOfContents.content)}};return t(r?.content),e.slice(0,Yt)}var We=r=>`https://docs.google.com/document/d/${r}/edit`;function Rc(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!bn(e)||!cc(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=lc(e);if(t.length>_c)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:pc(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Tc(r,e,t){let n=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${n}\r
380
+ `),i="",s=[],o=[];for(let l of n){let p=l,u=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(p),h=/^\s*[-*]\s+(.*)$/.exec(p),g=/^\s*\d+[.)]\s+(.*)$/.exec(p);f?(u=`HEADING_${f[1].length}`,p=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",p=h[1]):g&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",p=g[1]);let{text:_,styles:b}=Lc(p),y=e+i.length;for(let k of b)o.push({...k,start:y+k.start,end:y+k.end});i+=`${_}
381
+ `,s.push({start:y,end:e+i.length,named:u,bullet:m})}if(!i)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:i}}];for(let l of s)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 s)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:e+i.length}}function $c(r){let e="",t=n=>{for(let i of Array.isArray(n)?n:[]){if(e.length>=Vt)return;if(i.paragraph)for(let s of i.paragraph.elements||[])e+=s?.textRun?.content||"";else if(i.table)for(let s of i.table.tableRows||[])for(let o of s.tableCells||[])t(o.content);else i.tableOfContents&&t(i.tableOfContents.content)}};return t(r?.content),e.slice(0,Vt)}var Ye=r=>`https://docs.google.com/document/d/${r}/edit`;function Pc(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!wn(e)||!yc(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=gc(e);if(t.length>Oc)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:bc(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Cc(r,e,t){let n=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${n}\r
382
382
  Content-Type: application/json; charset=UTF-8\r
383
383
  \r
384
384
  ${JSON.stringify(r)}\r
@@ -387,18 +387,18 @@ Content-Type: ${t}\r
387
387
  \r
388
388
  `,"utf8"),e,Buffer.from(`\r
389
389
  --${n}--\r
390
- `,"utf8")]),contentType:`multipart/related; boundary=${n}`}}var _n=r=>{let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t},kn={id:"google-docs",serverName:"gdocs",allowedTools:["mcp__gdocs__*"],requiresIntegration:v.GOOGLE,description:"Google Docs \u2014 create, append to, insert images into, and read Google Docs (drive.file scoped)",promptFragment:`## Google Docs (connected)
390
+ `,"utf8")]),contentType:`multipart/related; boundary=${n}`}}var kn=r=>{let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t},Sn={id:"google-docs",serverName:"gdocs",allowedTools:["mcp__gdocs__*"],requiresIntegration:I.GOOGLE,description:"Google Docs \u2014 create, append to, insert images into, and read Google Docs (drive.file scoped)",promptFragment:`## Google Docs (connected)
391
391
  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.
392
392
  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.
393
393
  - 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.
394
394
  - gdocs_append: append markdown/text to the end of a doc you created earlier (pass the documentId or doc URL).
395
395
  - gdocs_insert_image: append a LOCAL image file (png/jpg, \u22645MB) to the end of a doc \u2014 pass { documentId, imagePath, width?, height? } (width/height in PT, optional). The image is uploaded to the user's Drive and made link-readable (anyone with the link) so Docs can render it. Returns { ok, documentId, fileId, url }.
396
- - gdocs_get: read a doc back as plain text (works for app-created/user-picked docs; arbitrary docs need the extended documents.readonly connection).
396
+ - gdocs_get: read a doc back as plain text (works for app-created/user-picked docs only; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker \u2014 drive.file has no access to un-picked files).
397
397
  - gdocs_list_created: list the Google Docs visible to this app (drive.file \u2192 only docs it created or the user picked).
398
- 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 r=gc();if(!r)return null;let e={};for(let t of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gdocs_create_doc":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let i=(await re(`${ke}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!i)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=_n(e);if(s&&s.trim()){let{requests:o}=yn(s,1);o.length&&await re(`${ke}/documents/${i}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:i,title:t,url:We(i)})}case"gdocs_append":{let t=Wt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=_n(e);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await re(`${ke}/documents/${t}`))?.body,o=Array.isArray(s?.content)?s.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:`
399
- `}}),l=c+1);let p=yn(n,l);return d.push(...p.requests),await re(`${ke}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:We(t)})}case"gdocs_insert_image":{let t=Wt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:n,fileName:i,mimeType:s}=Rc(e.imagePath),{rawBody:o,contentType:a}=Tc({name:i,mimeType:s},n,s),d=(await re(`${yc}/files?uploadType=multipart&fields=id`,{method:"POST",rawBody:o,contentType:a}))?.id;if(!d)return JSON.stringify({ok:!1,error:"Drive upload returned no file id"});await re(`${gn}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await re(`${ke}/documents/${t}`),p=Array.isArray(l?.body?.content)?l.body.content:[],u=p.length&&p[p.length-1].endIndex||2,f={location:{index:Math.max(1,u-1)},uri:`https://drive.google.com/uc?export=download&id=${d}`},h=Number(e?.width),y=Number(e?.height);return(Number.isFinite(h)&&h>0||Number.isFinite(y)&&y>0)&&(f.objectSize={...Number.isFinite(h)&&h>0?{width:{magnitude:h,unit:"PT"}}:{},...Number.isFinite(y)&&y>0?{height:{magnitude:y,unit:"PT"}}:{}}),await re(`${ke}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:We(t)})}case"gdocs_get":{let t=Wt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=await re(`${ke}/documents/${t}`),i=Oc(n?.body);return JSON.stringify({ok:!0,documentId:t,title:n?.title||"",url:We(t),text:i,...i.length>=Yt?{truncated:!0}:{}})}case"gdocs_list_created":{let t=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(Ic),orderBy:"modifiedTime desc"}),n=await re(`${gn}/files?${t.toString()}`),i=(Array.isArray(n?.files)?n.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||We(s.id)}));return JSON.stringify({ok:!0,count:i.length,files:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{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 On,statSync as Ac,readFileSync as xc}from"fs";import{fileURLToPath as Ec}from"url";import{basename as jc,dirname as Lc,resolve as $c}from"path";import{resolveIntegrationToken as Pc}from"@zibby/core/backend-client.js";function Cc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Lc(Ec(import.meta.url)),e=$c(r,"..","bin","mcp-skill.mjs");return On(e)?e:null}var wn=2e4,Sn=50,Uc=10*1024*1024,qc=6e3*1e3,Ye=null;async function Rn(){let{appId:r,appSecret:e,host:t}=await Pc("lark");if(Ye&&Ye.appId===r&&Ye.expiresAt>Date.now())return{token:Ye.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return Ye={token:i.tenant_access_token,expiresAt:Date.now()+qc,appId:r},{token:i.tenant_access_token,host:t}}async function ne(r,e,t){let{token:n,host:i}=await Rn(),s={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(s.body=JSON.stringify(t));let a=await(await fetch(`${i}${e}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:i}}function mt(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function we(r){if(!r||typeof r!="string")return null;let e=r.trim();if(!e)return null;let t=e.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return t?{type:t[1],token:t[2]}:/^[A-Za-z0-9]{10,}$/.test(e)?{type:"docx",token:e}:null}async function Pe(r){let e=typeof r=="string"?we(r):r;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:t}=await ne("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),n=t?.node||{};if(n.obj_type!=="docx"||!n.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${n.obj_type||"unknown"})`);return n.obj_token}function In(r){let e=String(r??"").replace(/\r\n/g,`
398
+ 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 r=Ic();if(!r)return null;let e={};for(let t of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gdocs_create_doc":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let i=(await re(`${ke}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!i)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=kn(e);if(s&&s.trim()){let{requests:o}=bn(s,1);o.length&&await re(`${ke}/documents/${i}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:i,title:t,url:Ye(i)})}case"gdocs_append":{let t=Zt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=kn(e);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await re(`${ke}/documents/${t}`))?.body,o=Array.isArray(s?.content)?s.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:`
399
+ `}}),l=c+1);let p=bn(n,l);return d.push(...p.requests),await re(`${ke}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:Ye(t)})}case"gdocs_insert_image":{let t=Zt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:n,fileName:i,mimeType:s}=Pc(e.imagePath),{rawBody:o,contentType:a}=Cc({name:i,mimeType:s},n,s),d=(await re(`${Nc}/files?uploadType=multipart&fields=id`,{method:"POST",rawBody:o,contentType:a}))?.id;if(!d)return JSON.stringify({ok:!1,error:"Drive upload returned no file id"});await re(`${_n}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await re(`${ke}/documents/${t}`),p=Array.isArray(l?.body?.content)?l.body.content:[],u=p.length&&p[p.length-1].endIndex||2,f={location:{index:Math.max(1,u-1)},uri:`https://drive.google.com/uc?export=download&id=${d}`},h=Number(e?.width),g=Number(e?.height);return(Number.isFinite(h)&&h>0||Number.isFinite(g)&&g>0)&&(f.objectSize={...Number.isFinite(h)&&h>0?{width:{magnitude:h,unit:"PT"}}:{},...Number.isFinite(g)&&g>0?{height:{magnitude:g,unit:"PT"}}:{}}),await re(`${ke}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:Ye(t)})}case"gdocs_get":{let t=Zt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=await re(`${ke}/documents/${t}`),i=$c(n?.body);return JSON.stringify({ok:!0,documentId:t,title:n?.title||"",url:Ye(t),text:i,...i.length>=Vt?{truncated:!0}:{}})}case"gdocs_list_created":{let t=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(Ec),orderBy:"modifiedTime desc"}),n=await re(`${_n}/files?${t.toString()}`),i=(Array.isArray(n?.files)?n.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||Ye(s.id)}));return JSON.stringify({ok:!0,count:i.length,files:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). The drive.file scope grants access ONLY to docs this app created or the user explicitly picked; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker (drive.file cannot see un-picked files). 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 Rn,statSync as Uc,readFileSync as Jc}from"fs";import{fileURLToPath as qc}from"url";import{basename as Dc,dirname as Bc,resolve as Mc}from"path";import{resolveIntegrationToken as Fc}from"@zibby/core/backend-client.js";function Gc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Bc(qc(import.meta.url)),e=Mc(r,"..","bin","mcp-skill.mjs");return Rn(e)?e:null}var vn=2e4,In=50,Kc=10*1024*1024,Hc=6e3*1e3,We=null;async function An(){let{appId:r,appSecret:e,host:t}=await Fc("lark");if(We&&We.appId===r&&We.expiresAt>Date.now())return{token:We.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return We={token:i.tenant_access_token,expiresAt:Date.now()+Hc,appId:r},{token:i.tenant_access_token,host:t}}async function ne(r,e,t){let{token:n,host:i}=await An(),s={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(s.body=JSON.stringify(t));let a=await(await fetch(`${i}${e}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:i}}function mt(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function we(r){if(!r||typeof r!="string")return null;let e=r.trim();if(!e)return null;let t=e.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return t?{type:t[1],token:t[2]}:/^[A-Za-z0-9]{10,}$/.test(e)?{type:"docx",token:e}:null}async function Pe(r){let e=typeof r=="string"?we(r):r;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:t}=await ne("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),n=t?.node||{};if(n.obj_type!=="docx"||!n.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${n.obj_type||"unknown"})`);return n.obj_token}function Nn(r){let e=String(r??"").replace(/\r\n/g,`
400
400
  `),t=[];for(let n of e.split(`
401
- `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d,l;if(s){let p=s[1].length;c=`heading${p}`,d=2+p,l=s[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=i);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function ft(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function vn(r,e){let t;for(let n=0;n<e.length;n+=Sn){let i=e.slice(n,n+Sn);t=(await ne("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:i})).host}return t}function Jc(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!On(e)||!Ac(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=xc(e);if(t.length>Uc)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function Dc({fileName:r,parentNode:e,bytes:t}){let{token:n,host:i}=await Rn(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",e),s.set("size",String(t.length)),s.set("file",new Blob([t]),r);let a=await(await fetch(`${i}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${n}`},body:s})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var Bc="docx",Mc=50;function Nn(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function Fc(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function Gc(r){let e=Array.isArray(r?.reply_list?.replies)?r.reply_list.replies:[];return{commentId:r?.comment_id||"",resolved:!!r?.is_solved,replies:e.map(t=>({replyId:t?.reply_id||"",author:t?.user_id||"",text:Fc(t?.content?.elements),createTime:t?.create_time||""}))}}function Zt(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():Bc}var Tn={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:v.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs (connected)
401
+ `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d,l;if(s){let p=s[1].length;c=`heading${p}`,d=2+p,l=s[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=i);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function ft(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function On(r,e){let t;for(let n=0;n<e.length;n+=In){let i=e.slice(n,n+In);t=(await ne("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:i})).host}return t}function zc(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Rn(e)||!Uc(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=Jc(e);if(t.length>Kc)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function Yc({fileName:r,parentNode:e,bytes:t}){let{token:n,host:i}=await An(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",e),s.set("size",String(t.length)),s.set("file",new Blob([t]),r);let a=await(await fetch(`${i}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${n}`},body:s})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var Wc="docx",Zc=50;function Tn(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function Vc(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function Qc(r){let e=Array.isArray(r?.reply_list?.replies)?r.reply_list.replies:[];return{commentId:r?.comment_id||"",resolved:!!r?.is_solved,replies:e.map(t=>({replyId:t?.reply_id||"",author:t?.user_id||"",text:Vc(t?.content?.elements),createTime:t?.create_time||""}))}}function Qt(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():Wc}var xn={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:I.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs (connected)
402
402
  You can read, create, and append Lark/Feishu documents (docx). This reuses the same connected Lark app as messaging.
403
403
  - 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.
404
404
  - larkdoc_create: create a new doc from a title + markdown/text (#/##/### headings, - bullets, 1. ordered supported); returns { ok, documentId, url }. Share the url.
@@ -407,14 +407,14 @@ You can read, create, and append Lark/Feishu documents (docx). This reuses the s
407
407
  - 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.
408
408
  - 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).
409
409
  - larkdoc_add_comment: post a NEW top-level comment on a doc \u2014 pass { documentId, text }.
410
- 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 r=Cc();return r?{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Pe(n),s="";try{s=(await ne("GET",`/open-apis/docx/v1/documents/${i}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await ne("GET",`/open-apis/docx/v1/documents/${i}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>wn&&(c=c.slice(0,wn),d=!0),JSON.stringify({ok:!0,documentId:i,title:s,url:mt(a,i),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let{data:n,host:i}=await ne("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),s=n?.document?.document_id;if(!s)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let o=ft(e);if(o&&o.trim()){let a=In(o);a.length&&await vn(s,a)}return JSON.stringify({ok:!0,documentId:s,title:t,url:mt(i,s)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=ft(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Pe(n),o=In(i);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await vn(s,o);return JSON.stringify({ok:!0,documentId:s,url:mt(a,s)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let i=await Pe(n),s=e.imagePath.trim(),o=Jc(s),a=jc(s),d=(await ne("POST",`/open-apis/docx/v1/documents/${i}/blocks/${i}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!d)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let l=await Dc({fileName:a,parentNode:d,bytes:o}),p={token:l},u=Number(e?.width),m=Number(e?.height);Number.isFinite(u)&&u>0&&(p.width=Math.round(u)),Number.isFinite(m)&&m>0&&(p.height=Math.round(m));let{host:f}=await ne("PATCH",`/open-apis/docx/v1/documents/${i}/blocks/${d}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:i,blockId:d,fileToken:l,url:mt(f,i)})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Pe(n),s=Zt(e),o=new URLSearchParams({file_type:s,page_size:String(Mc)}),{data:a}=await ne("GET",`/open-apis/drive/v1/files/${i}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(Gc);return JSON.stringify({ok:!0,documentId:i,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=ft({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Pe(n),o=Zt(e),{data:a}=await ne("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:Nn(i)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=e?.commentId||e?.comment_id;if(!i)return JSON.stringify({ok:!1,error:"commentId is required"});let s=ft({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Pe(n),a=Zt(e),{data:c}=await ne("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(i)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:Nn(s)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(i),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{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 An={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:[...C.envKeys||[],...ee.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return C.serverName;if(process.env.LARK_RECEIVE_ID)return ee.serverName;if(process.env.SLACK_BOT_TOKEN)return C.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?C.allowedTools||[]:process.env.LARK_RECEIVE_ID?ee.allowedTools||[]:process.env.SLACK_BOT_TOKEN?C.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
410
+ 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 r=Gc();return r?{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Pe(n),s="";try{s=(await ne("GET",`/open-apis/docx/v1/documents/${i}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await ne("GET",`/open-apis/docx/v1/documents/${i}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>vn&&(c=c.slice(0,vn),d=!0),JSON.stringify({ok:!0,documentId:i,title:s,url:mt(a,i),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let{data:n,host:i}=await ne("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),s=n?.document?.document_id;if(!s)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let o=ft(e);if(o&&o.trim()){let a=Nn(o);a.length&&await On(s,a)}return JSON.stringify({ok:!0,documentId:s,title:t,url:mt(i,s)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=ft(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Pe(n),o=Nn(i);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await On(s,o);return JSON.stringify({ok:!0,documentId:s,url:mt(a,s)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let i=await Pe(n),s=e.imagePath.trim(),o=zc(s),a=Dc(s),d=(await ne("POST",`/open-apis/docx/v1/documents/${i}/blocks/${i}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!d)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let l=await Yc({fileName:a,parentNode:d,bytes:o}),p={token:l},u=Number(e?.width),m=Number(e?.height);Number.isFinite(u)&&u>0&&(p.width=Math.round(u)),Number.isFinite(m)&&m>0&&(p.height=Math.round(m));let{host:f}=await ne("PATCH",`/open-apis/docx/v1/documents/${i}/blocks/${d}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:i,blockId:d,fileToken:l,url:mt(f,i)})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Pe(n),s=Qt(e),o=new URLSearchParams({file_type:s,page_size:String(Zc)}),{data:a}=await ne("GET",`/open-apis/drive/v1/files/${i}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(Qc);return JSON.stringify({ok:!0,documentId:i,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=ft({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Pe(n),o=Qt(e),{data:a}=await ne("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:Tn(i)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=we(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=e?.commentId||e?.comment_id;if(!i)return JSON.stringify({ok:!1,error:"commentId is required"});let s=ft({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Pe(n),a=Qt(e),{data:c}=await ne("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(i)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:Tn(s)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(i),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.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_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{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 En={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:[...C.envKeys||[],...ee.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return C.serverName;if(process.env.LARK_RECEIVE_ID)return ee.serverName;if(process.env.SLACK_BOT_TOKEN)return C.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?C.allowedTools||[]:process.env.LARK_RECEIVE_ID?ee.allowedTools||[]:process.env.SLACK_BOT_TOKEN?C.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
411
411
  You can post chat messages via:
412
412
  - slack_post_message (channel, text[, blocks]) \u2014 Slack. The \`channel\` is REQUIRED on every call.
413
413
  - lark_send_message (receive_id, text) \u2014 Lark.
414
414
  Where to post:
415
415
  - If SLACK_CHANNEL / LARK_RECEIVE_ID is set, that is the default destination \u2014 use it.
416
416
  - 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).
417
- - If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(r){return process.env.SLACK_CHANNEL&&typeof C.resolve=="function"?C.resolve(r):process.env.LARK_RECEIVE_ID&&typeof ee.resolve=="function"?ee.resolve(r):process.env.SLACK_BOT_TOKEN&&typeof C.resolve=="function"?C.resolve(r):null},async handleToolCall(r,e,t){return typeof r=="string"&&r.startsWith("slack_")?C.handleToolCall(r,e,t):typeof r=="string"&&r.startsWith("lark_")?ee.handleToolCall(r,e,t):JSON.stringify({error:`chat_notify: unknown tool "${r}". Expected slack_* or lark_*.`})},get tools(){return[...C.tools||[],...ee.tools||[]]}};import{createRequire as Kc}from"module";import{execFileSync as Hc}from"child_process";import{join as xn}from"path";import{existsSync as zc}from"fs";var Wc=Kc(import.meta.url);function Yc(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return Wc.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var En={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:r}=await import("@zibby/ui-memory");return r()}catch{return null}},promptFragment:`BEFORE executing browser actions:
417
+ - If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(r){return process.env.SLACK_CHANNEL&&typeof C.resolve=="function"?C.resolve(r):process.env.LARK_RECEIVE_ID&&typeof ee.resolve=="function"?ee.resolve(r):process.env.SLACK_BOT_TOKEN&&typeof C.resolve=="function"?C.resolve(r):null},async handleToolCall(r,e,t){return typeof r=="string"&&r.startsWith("slack_")?C.handleToolCall(r,e,t):typeof r=="string"&&r.startsWith("lark_")?ee.handleToolCall(r,e,t):JSON.stringify({error:`chat_notify: unknown tool "${r}". Expected slack_* or lark_*.`})},get tools(){return[...C.tools||[],...ee.tools||[]]}};import{createRequire as Xc}from"module";import{execFileSync as el}from"child_process";import{join as jn}from"path";import{existsSync as tl}from"fs";var rl=Xc(import.meta.url);function nl(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return rl.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var Ln={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:r}=await import("@zibby/ui-memory");return r()}catch{return null}},promptFragment:`BEFORE executing browser actions:
418
418
  - Review any test memory/history above. Prefer selectors proven to work.
419
419
  - If a previous run failed, avoid the same approach.
420
420
  - After setup/login completes, navigate directly to the target page instead of clicking through menus.
@@ -426,7 +426,7 @@ DURING execution \u2014 when a selector fails and you switch to a fallback:
426
426
  AFTER completing the test, you MUST call memory_save_insight at least once:
427
427
  - Save any useful finding: reliable selectors, timing quirks, navigation patterns, workarounds.
428
428
  - Category: selector_tip | timing | navigation | workaround | flaky | general
429
- - Be specific \u2014 future runs will read your insights.`,resolve(){let r=Yc();if(!r)return console.warn("[memory] @zibby/ui-memory not found \u2014 memory tools disabled for this run"),null;let e=xn(process.cwd(),".zibby","memory");if(!zc(xn(e,".dolt")))return console.warn("[memory] DB/dolt unavailable \u2014 memory tools disabled for this run"),null;try{let t=Hc("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:e,encoding:"utf-8",timeout:5e3}),n=JSON.parse(t.trim()).rows||[];if(!n[0]||n[0].cnt===0)return console.log("[memory] Database empty \u2014 memory tools activate after first completed run"),null}catch(t){return console.warn(`[memory] DB/dolt unavailable \u2014 memory tools disabled for this run (${t.message})`),null}return{command:"node",args:[r,"--db-path",e],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 Zc,readFileSync as Vc}from"fs";import{homedir as Qc}from"os";import{join as Xc}from"path";import{spawn as el}from"child_process";var Se={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
429
+ - Be specific \u2014 future runs will read your insights.`,resolve(){let r=nl();if(!r)return console.warn("[memory] @zibby/ui-memory not found \u2014 memory tools disabled for this run"),null;let e=jn(process.cwd(),".zibby","memory");if(!tl(jn(e,".dolt")))return console.warn("[memory] DB/dolt unavailable \u2014 memory tools disabled for this run"),null;try{let t=el("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:e,encoding:"utf-8",timeout:5e3}),n=JSON.parse(t.trim()).rows||[];if(!n[0]||n[0].cnt===0)return console.log("[memory] Database empty \u2014 memory tools activate after first completed run"),null}catch(t){return console.warn(`[memory] DB/dolt unavailable \u2014 memory tools disabled for this run (${t.message})`),null}return{command:"node",args:[r,"--db-path",e],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 il,readFileSync as sl}from"fs";import{homedir as ol}from"os";import{join as al}from"path";import{spawn as cl}from"child_process";var Se={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
430
430
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
431
431
  2. Click "Connect Jira" and authorize via Atlassian OAuth
432
432
  3. After OAuth completes, ask me to install Jira again`},github:{description:"GitHub issues, PRs, repository management",integrationProvider:"github",envKeys:[],setupInstructions:`To connect GitHub:
@@ -438,17 +438,17 @@ AFTER completing the test, you MUST call memory_save_insight at least once:
438
438
  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:
439
439
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
440
440
  2. Click "Connect Sentry" and authorize
441
- 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 tl(){let r=["## Available Skills"];for(let[e,t]of Object.entries(Se)){let n=t.integrationProvider?`integration: ${t.integrationProvider}`:"ready";r.push(`- ${e}: ${t.description} [${n}]`)}return r.push(""),r.push("Use the install_skill / uninstall_skill / list_available_skills tools to manage skills."),r.push(`Zibby third party Integration settings page: ${Vt()}`),r.push(""),r.push("## Tool-First Policy (mandatory)"),r.push("CRITICAL RULES \u2014 follow these strictly:"),r.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."),r.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.`),r.push("3. If install_skill reports needsIntegration, tell the user to connect via the integration URL and try again after."),r.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."),r.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."),r.join(`
442
- `)}function rl(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=Xc(Qc(),".zibby","config.json");return Zc(r)&&JSON.parse(Vc(r,"utf-8")).sessionToken||null}catch{return null}}function nl(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function Vt(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function il(r){try{let e=process.platform;return el(e==="darwin"?"open":e==="win32"?"cmd":"xdg-open",e==="win32"?["/c","start","",r]:[r],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}async function sl(){let r=rl();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${nl()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});return e.ok?{checked:!0,statuses:await e.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${e.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function jn(r,e){if(!e||!r)return{connected:null};let t=r[e];return!t||typeof t.connected!="boolean"?{connected:null,details:t||null}:{connected:t.connected,details:t}}var Ln={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:Se,promptFragment:tl,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(r,e,t){let{activeSkills:n}=t,i=await sl();if(r==="list_available_skills"){let s=Object.entries(Se).map(([o,a])=>{let c=n.includes(o),d=jn(i.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:s})}if(r==="install_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(n.includes(s)){let l=Se[s],{getSkill:p}=await import("@zibby/agent-workflow"),m=(p(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?Vt():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!Se[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(Se).join(", ")}`});let o=Se[s];if(o.integrationProvider){let l=jn(i.statuses,o.integrationProvider),p=Vt();if(i.checked&&l.connected===!1){let u=il(p);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:p,openedBrowser:u,setupInstructions:`Please connect ${o.integrationProvider} first at ${p}. After you finish OAuth, ask me to install ${s} again.`})}}n.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(s)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:d,hint:`${s} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(s==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=n.indexOf(s);return o===-1?JSON.stringify({ok:!1,error:`${s} is not installed`}):(n.splice(o,1),JSON.stringify({ok:!0,uninstalled:s}))}return JSON.stringify({error:`Unknown tool: ${r}`})},resolve(){return null}};import{readFileSync as ol,readdirSync as al,statSync as Pn,writeFileSync as cl,mkdirSync as ll}from"fs";import{join as Cn,resolve as dl,relative as pl}from"path";import{execSync as Un}from"child_process";var $n=256*1024,ul=64*1024,qn={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(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"read_file":return ml(e,n);case"write_file":return fl(e,n);case"list_directory":return hl(e,n);case"run_command":return gl(e,n);case"open_url":return yl(e);case"wait":return await _l(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function ht(r,e){return dl(e,r)}function ml(r,e){let t=ht(r.path,e),n=Pn(t);return n.size>$n?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${$n/1024}KB`}):ol(t,"utf-8")}function fl(r,e){let t=ht(r.path,e),n=Cn(t,"..");return ll(n,{recursive:!0}),cl(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:pl(e,t)})}function hl(r,e){let t=ht(r.path||".",e);return al(t).map(i=>{try{return Pn(Cn(t,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
443
- `)}function gl(r,e){let t=r.cwd?ht(r.cwd,e):e;return Un(r.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:ul,stdio:["pipe","pipe","pipe"]})||"(no output)"}function yl(r){let{url:e}=r;if(!e||!e.startsWith("http://")&&!e.startsWith("https://"))return JSON.stringify({error:"Invalid URL \u2014 must start with http:// or https://"});let t=process.platform,n=t==="darwin"?"open":t==="win32"?"start":"xdg-open";try{return Un(`${n} "${e}"`,{stdio:"ignore",timeout:5e3}),JSON.stringify({ok:!0,opened:e})}catch{return JSON.stringify({ok:!1,error:`Could not open browser. Please visit: ${e}`})}}async function _l(r,e){let t=Math.min(Math.max(r.seconds||5,1),300),n=r.reason||"async operation",i=500,s=Date.now()+t*1e3;for(;Date.now()<s;){if(e?.aborted)return JSON.stringify({ok:!0,waited:Math.round((t*1e3-(s-Date.now()))/1e3),reason:n,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(i,s-Date.now())))}return JSON.stringify({ok:!0,waited:t,reason:n})}import{existsSync as bl}from"fs";import{fileURLToPath as kl}from"url";import{dirname as wl,resolve as Sl}from"path";import{resolveIntegrationToken as Ze}from"@zibby/core/backend-client.js";function Il(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=wl(kl(import.meta.url)),e=Sl(r,"..","bin","mcp-sentry.mjs");return bl(e)?e:null}function Ve(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Jn(r){let e=r||process.env.SENTRY_ORG;if(!e)throw new Error('Sentry organization not resolved \u2014 reconnect Sentry, or set SENTRY_ORG (self-hosted; the default org slug is "sentry").');return e}async function Dn(r,e={}){let{token:t,organizationSlug:n,baseUrl:i}=await Ze("sentry"),s=`${Ve(i)}/api/0/organizations/${Jn(n)}${r}`,o={method:e.method||"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}};e.body!=null&&(o.body=typeof e.body=="string"?e.body:JSON.stringify(e.body));let a=await fetch(s,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 vl(){return Dn("/projects/?per_page=50")}async function Nl({query:r="is:unresolved",sort:e="date",project:t,limit:n=25}={}){let i=`/issues/?query=${encodeURIComponent(r)}&sort=${e}&per_page=${n}`;return t&&(i+=`&project=${encodeURIComponent(t)}`),Dn(i)}async function Qt(r){let e=String(r??"").trim();if(!e)throw new Error("resolveSentryIssueId: issueRef is required");if(/^\d+$/.test(e))return e;let{token:t,organizationSlug:n,baseUrl:i}=await Ze("sentry"),s=await fetch(`${Ve(i)}/api/0/organizations/${Jn(n)}/shortids/${encodeURIComponent(e)}/`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status} resolving shortId "${e}": ${c.slice(0,200)}`)}let o=await s.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${e}" did not resolve to a numeric issue id`);return String(a)}async function Ol(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let e=await Qt(r),{token:t,baseUrl:n}=await Ze("sentry"),i=await fetch(`${Ve(n)}/api/0/issues/${e}/`,{headers:{Authorization:`Bearer ${t}`}});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`Sentry API ${i.status}: ${s.slice(0,300)}`)}return i.json()}async function Rl(r,e={}){if(!r)throw new Error("sentryUpdateIssue: issueId is required");let t={};for(let a of["status","statusDetails","assignedTo","isBookmarked","hasSeen"])e[a]!==void 0&&(t[a]=e[a]);if(Object.keys(t).length===0)throw new Error("sentryUpdateIssue: nothing to update (pass status / statusDetails / assignedTo / isBookmarked / hasSeen)");let n=await Qt(r),{token:i,baseUrl:s}=await Ze("sentry"),o=await fetch(`${Ve(s)}/api/0/issues/${n}/`,{method:"PUT",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===403?new Error(`Sentry API 403 updating issue ${r}: ${a.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 ${o.status} updating issue ${r}: ${a.slice(0,300)}`)}return o.json()}async function Tl(r,e){if(!r)throw new Error("sentryAddComment: issueId is required");if(!e||!String(e).trim())throw new Error("sentryAddComment: text is required");let t=await Qt(r),{token:n,baseUrl:i}=await Ze("sentry"),s=await fetch(`${Ve(i)}/api/0/issues/${t}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(e)})});if(!s.ok){let o=await s.text().catch(()=>"");throw s.status===403?new Error(`Sentry API 403 commenting on issue ${r}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${s.status} commenting on issue ${r}: ${o.slice(0,300)}`)}return s.json()}var gt={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:v.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
441
+ 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 ll(){let r=["## Available Skills"];for(let[e,t]of Object.entries(Se)){let n=t.integrationProvider?`integration: ${t.integrationProvider}`:"ready";r.push(`- ${e}: ${t.description} [${n}]`)}return r.push(""),r.push("Use the install_skill / uninstall_skill / list_available_skills tools to manage skills."),r.push(`Zibby third party Integration settings page: ${Xt()}`),r.push(""),r.push("## Tool-First Policy (mandatory)"),r.push("CRITICAL RULES \u2014 follow these strictly:"),r.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."),r.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.`),r.push("3. If install_skill reports needsIntegration, tell the user to connect via the integration URL and try again after."),r.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."),r.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."),r.join(`
442
+ `)}function dl(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=al(ol(),".zibby","config.json");return il(r)&&JSON.parse(sl(r,"utf-8")).sessionToken||null}catch{return null}}function pl(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function Xt(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function ul(r){try{let e=process.platform;return cl(e==="darwin"?"open":e==="win32"?"cmd":"xdg-open",e==="win32"?["/c","start","",r]:[r],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}async function ml(){let r=dl();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${pl()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});return e.ok?{checked:!0,statuses:await e.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${e.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function $n(r,e){if(!e||!r)return{connected:null};let t=r[e];return!t||typeof t.connected!="boolean"?{connected:null,details:t||null}:{connected:t.connected,details:t}}var Pn={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:Se,promptFragment:ll,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(r,e,t){let{activeSkills:n}=t,i=await ml();if(r==="list_available_skills"){let s=Object.entries(Se).map(([o,a])=>{let c=n.includes(o),d=$n(i.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:s})}if(r==="install_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(n.includes(s)){let l=Se[s],{getSkill:p}=await import("@zibby/agent-workflow"),m=(p(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?Xt():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!Se[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(Se).join(", ")}`});let o=Se[s];if(o.integrationProvider){let l=$n(i.statuses,o.integrationProvider),p=Xt();if(i.checked&&l.connected===!1){let u=ul(p);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:p,openedBrowser:u,setupInstructions:`Please connect ${o.integrationProvider} first at ${p}. After you finish OAuth, ask me to install ${s} again.`})}}n.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(s)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:d,hint:`${s} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(s==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=n.indexOf(s);return o===-1?JSON.stringify({ok:!1,error:`${s} is not installed`}):(n.splice(o,1),JSON.stringify({ok:!0,uninstalled:s}))}return JSON.stringify({error:`Unknown tool: ${r}`})},resolve(){return null}};import{readFileSync as fl,readdirSync as hl,statSync as Un,writeFileSync as yl,mkdirSync as gl}from"fs";import{join as Jn,resolve as _l,relative as bl}from"path";import{execSync as qn}from"child_process";var Cn=256*1024,kl=64*1024,Dn={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(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"read_file":return wl(e,n);case"write_file":return Sl(e,n);case"list_directory":return vl(e,n);case"run_command":return Il(e,n);case"open_url":return Nl(e);case"wait":return await Ol(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function ht(r,e){return _l(e,r)}function wl(r,e){let t=ht(r.path,e),n=Un(t);return n.size>Cn?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${Cn/1024}KB`}):fl(t,"utf-8")}function Sl(r,e){let t=ht(r.path,e),n=Jn(t,"..");return gl(n,{recursive:!0}),yl(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:bl(e,t)})}function vl(r,e){let t=ht(r.path||".",e);return hl(t).map(i=>{try{return Un(Jn(t,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
443
+ `)}function Il(r,e){let t=r.cwd?ht(r.cwd,e):e;return qn(r.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:kl,stdio:["pipe","pipe","pipe"]})||"(no output)"}function Nl(r){let{url:e}=r;if(!e||!e.startsWith("http://")&&!e.startsWith("https://"))return JSON.stringify({error:"Invalid URL \u2014 must start with http:// or https://"});let t=process.platform,n=t==="darwin"?"open":t==="win32"?"start":"xdg-open";try{return qn(`${n} "${e}"`,{stdio:"ignore",timeout:5e3}),JSON.stringify({ok:!0,opened:e})}catch{return JSON.stringify({ok:!1,error:`Could not open browser. Please visit: ${e}`})}}async function Ol(r,e){let t=Math.min(Math.max(r.seconds||5,1),300),n=r.reason||"async operation",i=500,s=Date.now()+t*1e3;for(;Date.now()<s;){if(e?.aborted)return JSON.stringify({ok:!0,waited:Math.round((t*1e3-(s-Date.now()))/1e3),reason:n,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(i,s-Date.now())))}return JSON.stringify({ok:!0,waited:t,reason:n})}import{existsSync as Tl}from"fs";import{fileURLToPath as Rl}from"url";import{dirname as Al,resolve as xl}from"path";import{resolveIntegrationToken as Ze}from"@zibby/core/backend-client.js";function El(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=Al(Rl(import.meta.url)),e=xl(r,"..","bin","mcp-sentry.mjs");return Tl(e)?e:null}function Ve(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Bn(r){let e=r||process.env.SENTRY_ORG;if(!e)throw new Error('Sentry organization not resolved \u2014 reconnect Sentry, or set SENTRY_ORG (self-hosted; the default org slug is "sentry").');return e}async function Mn(r,e={}){let{token:t,organizationSlug:n,baseUrl:i}=await Ze("sentry"),s=`${Ve(i)}/api/0/organizations/${Bn(n)}${r}`,o={method:e.method||"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}};e.body!=null&&(o.body=typeof e.body=="string"?e.body:JSON.stringify(e.body));let a=await fetch(s,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 jl(){return Mn("/projects/?per_page=50")}async function Ll({query:r="is:unresolved",sort:e="date",project:t,limit:n=25}={}){let i=`/issues/?query=${encodeURIComponent(r)}&sort=${e}&per_page=${n}`;return t&&(i+=`&project=${encodeURIComponent(t)}`),Mn(i)}async function er(r){let e=String(r??"").trim();if(!e)throw new Error("resolveSentryIssueId: issueRef is required");if(/^\d+$/.test(e))return e;let{token:t,organizationSlug:n,baseUrl:i}=await Ze("sentry"),s=await fetch(`${Ve(i)}/api/0/organizations/${Bn(n)}/shortids/${encodeURIComponent(e)}/`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status} resolving shortId "${e}": ${c.slice(0,200)}`)}let o=await s.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${e}" did not resolve to a numeric issue id`);return String(a)}async function $l(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let e=await er(r),{token:t,baseUrl:n}=await Ze("sentry"),i=await fetch(`${Ve(n)}/api/0/issues/${e}/`,{headers:{Authorization:`Bearer ${t}`}});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`Sentry API ${i.status}: ${s.slice(0,300)}`)}return i.json()}async function Pl(r,e={}){if(!r)throw new Error("sentryUpdateIssue: issueId is required");let t={};for(let a of["status","statusDetails","assignedTo","isBookmarked","hasSeen"])e[a]!==void 0&&(t[a]=e[a]);if(Object.keys(t).length===0)throw new Error("sentryUpdateIssue: nothing to update (pass status / statusDetails / assignedTo / isBookmarked / hasSeen)");let n=await er(r),{token:i,baseUrl:s}=await Ze("sentry"),o=await fetch(`${Ve(s)}/api/0/issues/${n}/`,{method:"PUT",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===403?new Error(`Sentry API 403 updating issue ${r}: ${a.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 ${o.status} updating issue ${r}: ${a.slice(0,300)}`)}return o.json()}async function Cl(r,e){if(!r)throw new Error("sentryAddComment: issueId is required");if(!e||!String(e).trim())throw new Error("sentryAddComment: text is required");let t=await er(r),{token:n,baseUrl:i}=await Ze("sentry"),s=await fetch(`${Ve(i)}/api/0/issues/${t}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(e)})});if(!s.ok){let o=await s.text().catch(()=>"");throw s.status===403?new Error(`Sentry API 403 commenting on issue ${r}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${s.status} commenting on issue ${r}: ${o.slice(0,300)}`)}return s.json()}var yt={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:I.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
444
444
  You have access to the user's Sentry. Use these tools:
445
445
  - sentry_list_projects: List projects in the organization
446
446
  - sentry_list_issues: List errors/issues (supports Sentry search query, project filter, sort)
447
447
  - sentry_get_issue: Get detailed info about a specific issue (requires issueId)
448
448
  - sentry_update_issue: Change an issue's status (resolved / resolvedInNextRelease / ignored / unresolved / muted), assignment, or bookmark (requires issueId; needs write scope)
449
- - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=Il();if(!r)return null;let e={};for(let t 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[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},async handleToolCall(r,e={}){try{switch(r){case"sentry_list_projects":{let t=await vl();return JSON.stringify({projects:t.map(n=>({slug:n.slug,name:n.name,platform:n.platform}))})}case"sentry_list_issues":{let t=await Nl({query:e.query,sort:e.sort,project:e.project,limit:e.limit});return JSON.stringify({issues:t.map(n=>({id:n.id,title:n.title,culprit:n.culprit,count:n.count,firstSeen:n.firstSeen,lastSeen:n.lastSeen,level:n.level,status:n.status}))})}case"sentry_get_issue":{let t=await Ol(e.issueId);return JSON.stringify({id:t.id,title:t.title,culprit:t.culprit,metadata:t.metadata,count:t.count,userCount:t.userCount,firstSeen:t.firstSeen,lastSeen:t.lastSeen,level:t.level,status:t.status,project:{slug:t.project?.slug,name:t.project?.name}})}case"sentry_update_issue":{let t=await Rl(e.issueId,{status:e.status,statusDetails:e.statusDetails,assignedTo:e.assignedTo,isBookmarked:e.isBookmarked,hasSeen:e.hasSeen});return JSON.stringify({ok:!0,id:t.id??e.issueId,status:t.status,assignedTo:t.assignedTo,isBookmarked:t.isBookmarked})}case"sentry_add_comment":{let t=await Tl(e.issueId,e.text);return JSON.stringify({ok:!0,id:t.id,issueId:e.issueId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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"]}}]};gt.tools=gt.toolsForAssistant;import{spawn as Zn}from"child_process";import{writeFileSync as Al,mkdirSync as Bn,existsSync as ie,readdirSync as kt,readFileSync as bt,unlinkSync as xl,createWriteStream as El,statSync as jl}from"fs";import{resolve as Ie,join as Y}from"path";import{resolveMaxParallelRuns as Vn}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Ll}from"@zibby/core/constants/zibby-scratch.js";var tr="sessions",rr=".zibby/output",yt=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",$l=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",Qn=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",B=new Map,he=[],Pl=0,Xt=0,Mn=3e3;function Xn(){return`run_${++Pl}_${Date.now().toString(36)}`}function Fn(r){let e=Math.floor(r/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ei(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function q(r,e,t){if(!$l)return;let n=`
449
+ - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=El();if(!r)return null;let e={};for(let t 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[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},async handleToolCall(r,e={}){try{switch(r){case"sentry_list_projects":{let t=await jl();return JSON.stringify({projects:t.map(n=>({slug:n.slug,name:n.name,platform:n.platform}))})}case"sentry_list_issues":{let t=await Ll({query:e.query,sort:e.sort,project:e.project,limit:e.limit});return JSON.stringify({issues:t.map(n=>({id:n.id,title:n.title,culprit:n.culprit,count:n.count,firstSeen:n.firstSeen,lastSeen:n.lastSeen,level:n.level,status:n.status}))})}case"sentry_get_issue":{let t=await $l(e.issueId);return JSON.stringify({id:t.id,title:t.title,culprit:t.culprit,metadata:t.metadata,count:t.count,userCount:t.userCount,firstSeen:t.firstSeen,lastSeen:t.lastSeen,level:t.level,status:t.status,project:{slug:t.project?.slug,name:t.project?.name}})}case"sentry_update_issue":{let t=await Pl(e.issueId,{status:e.status,statusDetails:e.statusDetails,assignedTo:e.assignedTo,isBookmarked:e.isBookmarked,hasSeen:e.hasSeen});return JSON.stringify({ok:!0,id:t.id??e.issueId,status:t.status,assignedTo:t.assignedTo,isBookmarked:t.isBookmarked})}case"sentry_add_comment":{let t=await Cl(e.issueId,e.text);return JSON.stringify({ok:!0,id:t.id,issueId:e.issueId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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"]}}]};yt.tools=yt.toolsForAssistant;import{spawn as Qn}from"child_process";import{writeFileSync as Ul,mkdirSync as Fn,existsSync as ie,readdirSync as kt,readFileSync as bt,unlinkSync as Jl,createWriteStream as ql,statSync as Dl}from"fs";import{resolve as ve,join as W}from"path";import{resolveMaxParallelRuns as Xn}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Bl}from"@zibby/core/constants/zibby-scratch.js";var nr="sessions",ir=".zibby/output",gt=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",Ml=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",ei=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",B=new Map,he=[],Fl=0,tr=0,Gn=3e3;function ti(){return`run_${++Fl}_${Date.now().toString(36)}`}function Kn(r){let e=Math.floor(r/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ri(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function J(r,e,t){if(!Ml)return;let n=`
450
450
  ${e} [${r}] ${t}
451
- `;try{process.stderr.write(n)}catch{}}function nr(){he.length=0;for(let[,r]of B)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",nr);process.on("SIGINT",()=>{nr(),process.exit(0)});process.on("SIGTERM",()=>{nr(),process.exit(0)});var ti={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
451
+ `;try{process.stderr.write(n)}catch{}}function sr(){he.length=0;for(let[,r]of B)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",sr);process.on("SIGINT",()=>{sr(),process.exit(0)});process.on("SIGTERM",()=>{sr(),process.exit(0)});var ni={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
452
452
  You can run zibby test workflows directly from chat:
453
453
 
454
454
  **CRITICAL: When user asks to test a ticket:**
@@ -585,8 +585,8 @@ Each run generates:
585
585
  - events.json: All browser events
586
586
  - raw_stream_output.txt: Agent log
587
587
 
588
- Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"run_generate":return await Cl(e,n);case"run_test":return await Ml(e,n,t);case"run_status":return Fl(e);case"run_cancel":return Gl(e);case"run_artifacts":return zl(e,n);case"run_diagnose":return Wl(e,n);case"list_specs":return Yl(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}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 er(){let r=0;for(let[,e]of B)e.status==="running"&&r++;return r}function Gn(){for(;he.length>0;){let r=Vn(he[0]?.context?.options?.config);if(er()>=r)break;let{args:e,cwd:t,context:n}=he.shift();ri(e,t,n)}}async function Cl(r,e){let{ticket:t,description:n,input:i,repo:s,agent:o,output:a}=r,c=["generate"];t&&c.push("--ticket",t),n&&c.push("--description",n),i&&c.push("--input",i),s&&c.push("--repo",s),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,p=l&&d.includes(l)?l:null;p&&c.push("--agent",p);let u=t||"generate";return q(u,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{Qn&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(_=>/\s/.test(_)?JSON.stringify(_):_).join(" ")} cwd=${e}`);let f=Zn("zibby",c,{cwd:e,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",y="";f.stdout.on("data",_=>{let b=_.toString();h+=b;for(let g of b.split(`
589
- `)){let k=ei(g).trim();k.startsWith("\u2705")?q(u,"\u2705",k.slice(2).trim()):k.startsWith("\u2713")&&q(u,"\u2714",k.slice(2).trim())}}),f.stderr.on("data",_=>{y+=_.toString()}),f.on("close",_=>{if(_!==0){q(u,"\u274C",`Generation failed (exit ${_})`),m(JSON.stringify({error:`zibby generate failed with exit code ${_}`,stderr:y.slice(-1e3)}));return}let b=Ie(e,a||"test-specs"),g=[];try{let k=t?t.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";g=kt(b).filter(R=>R.endsWith(".txt")&&(!k||R.startsWith(k))).map(R=>Y(b,R))}catch{}q(u,"\u2705",`Generated ${g.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:t||null,specFiles:g.map(k=>k.replace(`${e}/`,"")),total:g.length,message:`Generated ${g.length} specs. Now call run_test for each file.`}))}),f.on("error",_=>{q(u,"\u274C",`Spawn error: ${_.message}`),m(JSON.stringify({error:_.message}))})})}var Kn=1e5,Hn=/^[A-Z][A-Z0-9]+-\d+$/,Ul=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function ql(r,e){if(!e||!e.length)return r;let t=r;for(let n of e)n.type==="strong"?t=`**${t}**`:n.type==="em"?t=`_${t}_`:n.type==="code"?t=`\`${t}\``:n.type==="strike"?t=`~~${t}~~`:n.type==="link"&&n.attrs?.href&&(t=`[${t}](${n.attrs.href})`);return t}function _t(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(ql(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
588
+ Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"run_generate":return await Gl(e,n);case"run_test":return await Zl(e,n,t);case"run_status":return Vl(e);case"run_cancel":return Ql(e);case"run_artifacts":return td(e,n);case"run_diagnose":return rd(e,n);case"list_specs":return nd(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}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 rr(){let r=0;for(let[,e]of B)e.status==="running"&&r++;return r}function Hn(){for(;he.length>0;){let r=Xn(he[0]?.context?.options?.config);if(rr()>=r)break;let{args:e,cwd:t,context:n}=he.shift();ii(e,t,n)}}async function Gl(r,e){let{ticket:t,description:n,input:i,repo:s,agent:o,output:a}=r,c=["generate"];t&&c.push("--ticket",t),n&&c.push("--description",n),i&&c.push("--input",i),s&&c.push("--repo",s),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,p=l&&d.includes(l)?l:null;p&&c.push("--agent",p);let u=t||"generate";return J(u,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{ei&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(_=>/\s/.test(_)?JSON.stringify(_):_).join(" ")} cwd=${e}`);let f=Qn("zibby",c,{cwd:e,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",g="";f.stdout.on("data",_=>{let b=_.toString();h+=b;for(let y of b.split(`
589
+ `)){let k=ri(y).trim();k.startsWith("\u2705")?J(u,"\u2705",k.slice(2).trim()):k.startsWith("\u2713")&&J(u,"\u2714",k.slice(2).trim())}}),f.stderr.on("data",_=>{g+=_.toString()}),f.on("close",_=>{if(_!==0){J(u,"\u274C",`Generation failed (exit ${_})`),m(JSON.stringify({error:`zibby generate failed with exit code ${_}`,stderr:g.slice(-1e3)}));return}let b=ve(e,a||"test-specs"),y=[];try{let k=t?t.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";y=kt(b).filter(T=>T.endsWith(".txt")&&(!k||T.startsWith(k))).map(T=>W(b,T))}catch{}J(u,"\u2705",`Generated ${y.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:t||null,specFiles:y.map(k=>k.replace(`${e}/`,"")),total:y.length,message:`Generated ${y.length} specs. Now call run_test for each file.`}))}),f.on("error",_=>{J(u,"\u274C",`Spawn error: ${_.message}`),m(JSON.stringify({error:_.message}))})})}var zn=1e5,Yn=/^[A-Z][A-Z0-9]+-\d+$/,Kl=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Hl(r,e){if(!e||!e.length)return r;let t=r;for(let n of e)n.type==="strong"?t=`**${t}**`:n.type==="em"?t=`_${t}_`:n.type==="code"?t=`\`${t}\``:n.type==="strike"?t=`~~${t}~~`:n.type==="link"&&n.attrs?.href&&(t=`[${t}](${n.attrs.href})`);return t}function _t(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(Hl(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
590
590
  `);continue}if(n.type==="rule"){t.push(`
591
591
  ---
592
592
  `);continue}let i=n.content?_t(n.content,e+1):"";if(n.type==="listItem")t.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${_t(o.content||[],e+1).trim()}`);t.push(`
@@ -599,21 +599,21 @@ ${s.join(`
599
599
 
600
600
  ${"#".repeat(s)} ${i.trim()}
601
601
 
602
- `)}else Ul.has(n.type)?t.push(`
602
+ `)}else Kl.has(n.type)?t.push(`
603
603
 
604
604
  ${i}
605
605
  `):t.push(i)}return t.join("").replace(/\n{3,}/g,`
606
606
 
607
- `)}function Jl(r){return r==null||r===""?"":typeof r=="string"?r.trim():typeof r=="object"&&Array.isArray(r.content)?_t(r.content).trim():""}async function Dl(r){let{getSkill:e}=await import("@zibby/agent-workflow"),t=e("jira");if(!t||typeof t.handleToolCall!="function")return null;try{let n=await t.handleToolCall("jira_get_issue",{issueKey:r}),i=JSON.parse(n);if(i?.error)return null;let s=await t.handleToolCall("jira_get_comments",{issueKey:r,maxResults:50}),o=JSON.parse(s);if(o?.error)return null;let a=Jl(i.description),c=[];a&&c.push(a);let d=Array.isArray(o.comments)?o.comments:[];if(d.length>0){let p=d.map(u=>String(u.body||"").trim()).filter(Boolean).join(`
607
+ `)}function zl(r){return r==null||r===""?"":typeof r=="string"?r.trim():typeof r=="object"&&Array.isArray(r.content)?_t(r.content).trim():""}async function Yl(r){let{getSkill:e}=await import("@zibby/agent-workflow"),t=e("jira");if(!t||typeof t.handleToolCall!="function")return null;try{let n=await t.handleToolCall("jira_get_issue",{issueKey:r}),i=JSON.parse(n);if(i?.error)return null;let s=await t.handleToolCall("jira_get_comments",{issueKey:r,maxResults:50}),o=JSON.parse(s);if(o?.error)return null;let a=zl(i.description),c=[];a&&c.push(a);let d=Array.isArray(o.comments)?o.comments:[];if(d.length>0){let p=d.map(u=>String(u.body||"").trim()).filter(Boolean).join(`
608
608
 
609
609
  `);p&&c.push(p)}let l=c.join(`
610
610
 
611
- `).trim();return l?(l.length>Kn&&(l=`${l.slice(0,Kn)}
611
+ `).trim();return l?(l.length>zn&&(l=`${l.slice(0,zn)}
612
612
 
613
- ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function Bl(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function Ml(r,e,t){let n={...r},i=String(n.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let s=null;if(Hn.test(i)&&!i.startsWith("inline:")){let l=await Dl(i);l&&(i=l.inlineSpec,n.spec=i,String(n.ticketKey||"").trim()||(n.ticketKey=l.issueKey),s=l.issueKey)}let o=String(n.ticketKey||"").trim();if(o){for(let[l,p]of B.entries())if(p?.ticketKey===o&&!(p?.status!=="running"&&p?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:p.status,reused:!0,message:`A run for ${o} is already ${p.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let l=Ie(e,i);if(!ie(l))return Hn.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 a=Vn(t?.options?.config);if(er()>=a){let l=Xn(),p=n.ticketKey||l,u={runId:l,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};B.set(l,u),he.push({args:{...n,_queuedRunId:l},cwd:e,context:t}),q(p,"\u23F3",`Queued (${er()}/${a} running, ${he.length} queued)`);let m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return s&&(m.resolvedFromJiraIssue=s,m.message+=` (spec built from Jira ${s})`),JSON.stringify(m)}let c=Date.now()-Xt;c<Mn&&Xt>0&&await new Promise(l=>setTimeout(l,Mn-c)),Xt=Date.now();let d=ri(n,e,t);return s?Bl(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function ri(r,e,t){let{spec:n,ticketKey:i,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||Xn(),l=n,p=!1;if(n.startsWith("inline:")){p=!0;let T=Ll(e);Bn(T,{recursive:!0}),l=Y(T,`${d}.txt`),Al(l,n.slice(7).trim(),"utf-8")}let u=Ie(e,".zibby","output","runs");Bn(u,{recursive:!0});let m=Y(u,`${d}.log`),f=El(m,{flags:"a"}),y=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,_=["test",l];y&&_.push("--agent",y),o&&_.push("--headless"),a&&_.push("--workflow",a),Qn&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${_.map(T=>/\s/.test(T)?JSON.stringify(T):T).join(" ")} cwd=${e}`);let b=Zn("zibby",_,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),g={runId:d,spec:i?`${i}: ${n}`:n,ticketKey:i||null,specPath:l,logPath:m,isInline:p,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=i||d,R="";function K(T){let O=ei(T).trim();if(!O)return;if(O.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let x=JSON.parse(O.slice(22));x.phase==="node_begin"?g.currentNode=x.node:x.phase==="node_end"&&(x.node&&!g.completedNodes.includes(x.node)&&g.completedNodes.push(x.node),g.currentNode===x.node&&(g.currentNode=null))}catch{}return}let D=O.match(/Session\s+(\S+)/);if(D&&!g.sessionId&&(g.sessionId=D[1],g.sessionPath=Ie(e,rr,tr,g.sessionId)),O.startsWith("\u250C ")||O.startsWith("\u250C ")){let x=O.slice(2).trim();g.currentNode=x,yt&&q(k,"\u25B6",`${x}`)}else if(O.startsWith("\u2514 ")||O.startsWith("\u2514 ")){let x=O.slice(2).trim();x.startsWith("done")?(g.currentNode&&!g.completedNodes.includes(g.currentNode)&&g.completedNodes.push(g.currentNode),yt&&q(k,"\u2714",`${g.currentNode||"node"} done ${x.replace("done","").trim()}`),g.currentNode=null):x.startsWith("failed")&&(yt&&q(k,"\u2718",`${g.currentNode||"node"} failed ${x.replace("failed","").trim()}`),g.currentNode=null)}else O.includes("Workflow completed")&&(g.currentNode=null,yt&&q(k,"\u2714",`Workflow completed (${Fn(Date.now()-g.startTime)})`))}function Te(T){let O=T.toString();g.output+=O,f.write(O),g.output.length>5e4&&(g.output=g.output.slice(-3e4)),R+=O;let D=R.split(`
614
- `);R=D.pop();for(let x of D)K(x)}return b.stdout.on("data",Te),b.stderr.on("data",T=>{let O=T.toString();g.error+=O,f.write(O),g.error.length>2e4&&(g.error=g.error.slice(-1e4))}),b.on("close",T=>{g.status=T===0?"passed":"failed",g.exitCode=T,g.endTime=Date.now(),R&&K(R),f.end();let O=Fn(Date.now()-g.startTime);if(T===0?q(k,"\u2705",`Passed (${O})`):q(k,"\u274C",`Failed (${O})`),g.isInline)try{xl(g.specPath)}catch{}Gn()}),b.on("error",T=>{g.status="error",g.error+=`
615
- Spawn error: ${T.message}`,q(k,"\u274C",`Spawn error: ${T.message}`),f.end(),Gn()}),g._child=b,B.set(d,g),JSON.stringify({runId:d,spec:g.spec,ticketKey:g.ticketKey,status:"running",pid:b.pid,logFile:m})}function zn(r){let e=Math.round(((r.endTime||Date.now())-r.startTime)/1e3),t=r.completedNodes||[],n=r.currentNode||null;if(r.status!=="running")return{elapsed:e,stage:r.status,completedNodes:t,currentNode:null};let i;return n?(i=`Actively executing node "${n}"`,t.length&&(i+=` (completed: ${t.join(", ")})`)):t.length?i=`Between nodes (completed: ${t.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${e}s. This is normal progress \u2014 do not cancel.`,{elapsed:e,stage:"running",currentNode:n,completedNodes:t,progress:i}}function Fl(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let s=[...B.entries()].map(([l,p])=>{let u=zn(p),m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:p.status,elapsed:u.elapsed,exitCode:p.exitCode,sessionId:p.sessionId||null};return p.status==="running"?(m.currentNode=u.currentNode,m.completedNodes=u.completedNodes,m.progress=u.progress):m.outputTail=p.output.slice(-500),m}),o=s.filter(l=>l.status==="running").length,a=s.filter(l=>l.status==="passed").length,c=s.filter(l=>l.status==="failed").length,d={total:s.length,running:o,passed:a,failed:c,runs:s};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 t=B.get(e);if(!t)return JSON.stringify({error:`Run not found: ${e}`});let n=zn(t),i={runId:e,spec:t.spec,ticketKey:t.ticketKey,status:t.status,elapsed:n.elapsed,exitCode:t.exitCode,sessionId:t.sessionId||null};return t.status==="running"?(i.currentNode=n.currentNode,i.completedNodes=n.completedNodes,i.progress=n.progress):(i.outputTail=t.output.slice(-1e3),i.errorTail=t.error.slice(-500)),t.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 Wn(r,e){if(e.status==="queued"){let t=he.findIndex(n=>n.args._queuedRunId===r);return t>=0&&he.splice(t,1),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}if(e.status!=="running")return{ok:!1,runId:r,error:`Run is not active (status: ${e.status})`};try{return e._child.kill("SIGTERM"),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}catch(t){return{ok:!1,runId:r,error:`Failed to cancel: ${t.message}`}}}function Gl(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let n=[];for(let[i,s]of B.entries())(s.status==="running"||s.status==="queued")&&n.push(Wn(i,s));return n.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:n.length,results:n})}let t=B.get(e);return JSON.stringify(t?Wn(e,t):{error:`Run not found: ${e}`})}function Kl(r,e){let t=B.get(r);if(t?.sessionPath&&ie(t.sessionPath))return t.sessionPath;if(t?.sessionId){let n=Ie(e,rr,tr,t.sessionId);if(ie(n))return n}return null}function ni(r,e=""){let t=[];if(!ie(r))return t;for(let n of kt(r,{withFileTypes:!0})){let i=e?`${e}/${n.name}`:n.name;if(n.isDirectory())t.push(...ni(Y(r,n.name),i));else{let s=jl(Y(r,n.name));t.push({path:i,size:s.size})}}return t}function Yn(r){if(!ie(r))return null;try{return JSON.parse(bt(r,"utf-8"))}catch{return null}}function ii(r,e=2e3){if(!r||!ie(r))return"";try{return bt(r,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function Hl({run:r,logTail:e,errorTail:t}){let i=`${e||""}
616
- ${t||""}`.toLowerCase(),s={runId:r?.runId||null,status:r?.status||null,exitCode:r?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return r?.status==="running"||r?.status==="queued"?{...s,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")?{...s,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'")?{...s,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")?{...s,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")?{...s,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")?{...s,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" }).'}:s}function zl(r,e){let{runId:t,type:n,node:i="execute_live",query:s,tail:o=3e3}=r;if(n==="search"){if(!s)return JSON.stringify({error:'query is required for type="search"'});let c=Ie(e,rr,tr);if(!ie(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=s.toLowerCase();for(let p of kt(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=Y(c,p.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 y=Y(u,f);if(ie(y))try{let _=bt(y,"utf-8");if(_.toLowerCase().includes(l)){let b=_.toLowerCase().indexOf(l),g=Math.max(0,b-100),k=Math.min(_.length,b+s.length+100);d.push({sessionId:p.name,artifact:h,snippet:_.slice(g,k)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:s,matches:d,total:d.length})}if(!t)return JSON.stringify({error:"runId is required for this type"});if(n==="log"){let c=B.get(t),d=ii(c?.logPath,o);if(d)return JSON.stringify({runId:t,source:"run-log",totalLength:d.length,tail:d})}let a=Kl(t,e);if(!a)return JSON.stringify({error:`No session found for run ${t}. The run may still be starting.`});switch(n){case"list":{let c=ni(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=Yn(Y(a,i,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:i,result:c}:{error:`No result.json found in ${i}`})}case"events":{let c=Yn(Y(a,i,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${i}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=Y(a,i,"raw_stream_output.txt");if(!ie(c))return JSON.stringify({error:`No log found in ${i}`});let d=bt(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${n}. Use: list, result, events, log, search`})}}function Wl(r,e){let t=String(r?.runId||"all"),n=Number(r?.tail||2e3),i=t==="all"?[...B.keys()]:[t];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let s=i.map(c=>{let d=B.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=ii(d.logPath,n),p=String(d.error||"").slice(-Math.max(200,n));return{...Hl({run:d,logTail:l,errorTail:p}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:p}}),o=s.filter(c=>c.status==="failed"||c.status==="error"),a=s.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:s.length,failed:o.length,active:a.length,diagnoses:s})}function Yl(r,e){let t=r?.directory||"test-specs",n=Ie(e,t);if(!ie(n))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let s=function(o,a){for(let c of kt(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(Y(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&i.push(d)}},i=[];return s(n,""),JSON.stringify({specs:i.map(o=>`${t}/${o}`),total:i.length,directory:t})}catch(i){return JSON.stringify({error:i.message})}}function si(r){let e=(r||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return e?{provider:"github",owner:e[1],repo:e[2]}:(e=(r||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),e?{provider:"gitlab",owner:e[1],repo:e[2]}:null)}var oi={...ue,id:"git-write",envKeys:[...ue.envKeys||[],...Ee.envKeys||[],...je.envKeys||[]].filter((r,e,t)=>t.indexOf(r)===e),promptFragment:`${ue.promptFragment}
613
+ ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function Wl(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function Zl(r,e,t){let n={...r},i=String(n.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let s=null;if(Yn.test(i)&&!i.startsWith("inline:")){let l=await Yl(i);l&&(i=l.inlineSpec,n.spec=i,String(n.ticketKey||"").trim()||(n.ticketKey=l.issueKey),s=l.issueKey)}let o=String(n.ticketKey||"").trim();if(o){for(let[l,p]of B.entries())if(p?.ticketKey===o&&!(p?.status!=="running"&&p?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:p.status,reused:!0,message:`A run for ${o} is already ${p.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let l=ve(e,i);if(!ie(l))return Yn.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 a=Xn(t?.options?.config);if(rr()>=a){let l=ti(),p=n.ticketKey||l,u={runId:l,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};B.set(l,u),he.push({args:{...n,_queuedRunId:l},cwd:e,context:t}),J(p,"\u23F3",`Queued (${rr()}/${a} running, ${he.length} queued)`);let m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return s&&(m.resolvedFromJiraIssue=s,m.message+=` (spec built from Jira ${s})`),JSON.stringify(m)}let c=Date.now()-tr;c<Gn&&tr>0&&await new Promise(l=>setTimeout(l,Gn-c)),tr=Date.now();let d=ii(n,e,t);return s?Wl(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function ii(r,e,t){let{spec:n,ticketKey:i,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||ti(),l=n,p=!1;if(n.startsWith("inline:")){p=!0;let R=Bl(e);Fn(R,{recursive:!0}),l=W(R,`${d}.txt`),Ul(l,n.slice(7).trim(),"utf-8")}let u=ve(e,".zibby","output","runs");Fn(u,{recursive:!0});let m=W(u,`${d}.log`),f=ql(m,{flags:"a"}),g=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,_=["test",l];g&&_.push("--agent",g),o&&_.push("--headless"),a&&_.push("--workflow",a),ei&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${_.map(R=>/\s/.test(R)?JSON.stringify(R):R).join(" ")} cwd=${e}`);let b=Qn("zibby",_,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),y={runId:d,spec:i?`${i}: ${n}`:n,ticketKey:i||null,specPath:l,logPath:m,isInline:p,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=i||d,T="";function K(R){let O=ri(R).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 D=O.match(/Session\s+(\S+)/);if(D&&!y.sessionId&&(y.sessionId=D[1],y.sessionPath=ve(e,ir,nr,y.sessionId)),O.startsWith("\u250C ")||O.startsWith("\u250C ")){let x=O.slice(2).trim();y.currentNode=x,gt&&J(k,"\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),gt&&J(k,"\u2714",`${y.currentNode||"node"} done ${x.replace("done","").trim()}`),y.currentNode=null):x.startsWith("failed")&&(gt&&J(k,"\u2718",`${y.currentNode||"node"} failed ${x.replace("failed","").trim()}`),y.currentNode=null)}else O.includes("Workflow completed")&&(y.currentNode=null,gt&&J(k,"\u2714",`Workflow completed (${Kn(Date.now()-y.startTime)})`))}function Re(R){let O=R.toString();y.output+=O,f.write(O),y.output.length>5e4&&(y.output=y.output.slice(-3e4)),T+=O;let D=T.split(`
614
+ `);T=D.pop();for(let x of D)K(x)}return b.stdout.on("data",Re),b.stderr.on("data",R=>{let O=R.toString();y.error+=O,f.write(O),y.error.length>2e4&&(y.error=y.error.slice(-1e4))}),b.on("close",R=>{y.status=R===0?"passed":"failed",y.exitCode=R,y.endTime=Date.now(),T&&K(T),f.end();let O=Kn(Date.now()-y.startTime);if(R===0?J(k,"\u2705",`Passed (${O})`):J(k,"\u274C",`Failed (${O})`),y.isInline)try{Jl(y.specPath)}catch{}Hn()}),b.on("error",R=>{y.status="error",y.error+=`
615
+ Spawn error: ${R.message}`,J(k,"\u274C",`Spawn error: ${R.message}`),f.end(),Hn()}),y._child=b,B.set(d,y),JSON.stringify({runId:d,spec:y.spec,ticketKey:y.ticketKey,status:"running",pid:b.pid,logFile:m})}function Wn(r){let e=Math.round(((r.endTime||Date.now())-r.startTime)/1e3),t=r.completedNodes||[],n=r.currentNode||null;if(r.status!=="running")return{elapsed:e,stage:r.status,completedNodes:t,currentNode:null};let i;return n?(i=`Actively executing node "${n}"`,t.length&&(i+=` (completed: ${t.join(", ")})`)):t.length?i=`Between nodes (completed: ${t.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${e}s. This is normal progress \u2014 do not cancel.`,{elapsed:e,stage:"running",currentNode:n,completedNodes:t,progress:i}}function Vl(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let s=[...B.entries()].map(([l,p])=>{let u=Wn(p),m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:p.status,elapsed:u.elapsed,exitCode:p.exitCode,sessionId:p.sessionId||null};return p.status==="running"?(m.currentNode=u.currentNode,m.completedNodes=u.completedNodes,m.progress=u.progress):m.outputTail=p.output.slice(-500),m}),o=s.filter(l=>l.status==="running").length,a=s.filter(l=>l.status==="passed").length,c=s.filter(l=>l.status==="failed").length,d={total:s.length,running:o,passed:a,failed:c,runs:s};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 t=B.get(e);if(!t)return JSON.stringify({error:`Run not found: ${e}`});let n=Wn(t),i={runId:e,spec:t.spec,ticketKey:t.ticketKey,status:t.status,elapsed:n.elapsed,exitCode:t.exitCode,sessionId:t.sessionId||null};return t.status==="running"?(i.currentNode=n.currentNode,i.completedNodes=n.completedNodes,i.progress=n.progress):(i.outputTail=t.output.slice(-1e3),i.errorTail=t.error.slice(-500)),t.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 Zn(r,e){if(e.status==="queued"){let t=he.findIndex(n=>n.args._queuedRunId===r);return t>=0&&he.splice(t,1),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}if(e.status!=="running")return{ok:!1,runId:r,error:`Run is not active (status: ${e.status})`};try{return e._child.kill("SIGTERM"),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}catch(t){return{ok:!1,runId:r,error:`Failed to cancel: ${t.message}`}}}function Ql(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let n=[];for(let[i,s]of B.entries())(s.status==="running"||s.status==="queued")&&n.push(Zn(i,s));return n.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:n.length,results:n})}let t=B.get(e);return JSON.stringify(t?Zn(e,t):{error:`Run not found: ${e}`})}function Xl(r,e){let t=B.get(r);if(t?.sessionPath&&ie(t.sessionPath))return t.sessionPath;if(t?.sessionId){let n=ve(e,ir,nr,t.sessionId);if(ie(n))return n}return null}function si(r,e=""){let t=[];if(!ie(r))return t;for(let n of kt(r,{withFileTypes:!0})){let i=e?`${e}/${n.name}`:n.name;if(n.isDirectory())t.push(...si(W(r,n.name),i));else{let s=Dl(W(r,n.name));t.push({path:i,size:s.size})}}return t}function Vn(r){if(!ie(r))return null;try{return JSON.parse(bt(r,"utf-8"))}catch{return null}}function oi(r,e=2e3){if(!r||!ie(r))return"";try{return bt(r,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function ed({run:r,logTail:e,errorTail:t}){let i=`${e||""}
616
+ ${t||""}`.toLowerCase(),s={runId:r?.runId||null,status:r?.status||null,exitCode:r?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return r?.status==="running"||r?.status==="queued"?{...s,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")?{...s,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'")?{...s,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")?{...s,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")?{...s,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")?{...s,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" }).'}:s}function td(r,e){let{runId:t,type:n,node:i="execute_live",query:s,tail:o=3e3}=r;if(n==="search"){if(!s)return JSON.stringify({error:'query is required for type="search"'});let c=ve(e,ir,nr);if(!ie(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=s.toLowerCase();for(let p of kt(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=W(c,p.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 g=W(u,f);if(ie(g))try{let _=bt(g,"utf-8");if(_.toLowerCase().includes(l)){let b=_.toLowerCase().indexOf(l),y=Math.max(0,b-100),k=Math.min(_.length,b+s.length+100);d.push({sessionId:p.name,artifact:h,snippet:_.slice(y,k)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:s,matches:d,total:d.length})}if(!t)return JSON.stringify({error:"runId is required for this type"});if(n==="log"){let c=B.get(t),d=oi(c?.logPath,o);if(d)return JSON.stringify({runId:t,source:"run-log",totalLength:d.length,tail:d})}let a=Xl(t,e);if(!a)return JSON.stringify({error:`No session found for run ${t}. The run may still be starting.`});switch(n){case"list":{let c=si(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=Vn(W(a,i,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:i,result:c}:{error:`No result.json found in ${i}`})}case"events":{let c=Vn(W(a,i,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${i}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=W(a,i,"raw_stream_output.txt");if(!ie(c))return JSON.stringify({error:`No log found in ${i}`});let d=bt(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${n}. Use: list, result, events, log, search`})}}function rd(r,e){let t=String(r?.runId||"all"),n=Number(r?.tail||2e3),i=t==="all"?[...B.keys()]:[t];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let s=i.map(c=>{let d=B.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=oi(d.logPath,n),p=String(d.error||"").slice(-Math.max(200,n));return{...ed({run:d,logTail:l,errorTail:p}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:p}}),o=s.filter(c=>c.status==="failed"||c.status==="error"),a=s.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:s.length,failed:o.length,active:a.length,diagnoses:s})}function nd(r,e){let t=r?.directory||"test-specs",n=ve(e,t);if(!ie(n))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let s=function(o,a){for(let c of kt(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(W(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&i.push(d)}},i=[];return s(n,""),JSON.stringify({specs:i.map(o=>`${t}/${o}`),total:i.length,directory:t})}catch(i){return JSON.stringify({error:i.message})}}function ai(r){let e=(r||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return e?{provider:"github",owner:e[1],repo:e[2]}:(e=(r||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),e?{provider:"gitlab",owner:e[1],repo:e[2]}:null)}var ci={...ue,id:"git-write",envKeys:[...ue.envKeys||[],...Ee.envKeys||[],...je.envKeys||[]].filter((r,e,t)=>t.indexOf(r)===e),promptFragment:`${ue.promptFragment}
617
617
 
618
618
  ## Opening a pull request / merge request (git_open_pr)
619
619
  After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
@@ -625,7 +625,7 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
625
625
  To MERGE an open PR/MR, use the provider-agnostic tool:
626
626
  - git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
627
627
  { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
628
- 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(r,e,t){if(r!=="git_open_pr"&&r!=="git_merge_pr")return ue.handleToolCall(r,e,t);try{let n=e||{},i=n.repoUrl||n.repo_url||n.url;if(!i)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(r==="git_merge_pr"){let l=n.number??n.iid??n.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let p=si(i);return p?p.provider==="github"?Ee.handleToolCall("github_merge_pr",{owner:p.owner,repo:p.repo,number:l,mergeMethod:n.mergeMethod},t):je.handleToolCall("gitlab_accept_mr",{project:`${p.owner}/${p.repo}`,iid:l},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_merge_pr supports github.com and gitlab.com.`})}let s=n.head||n.source_branch||n.sourceBranch||n.branch,o=n.base||n.target_branch||n.targetBranch,{title:a,body:c}=n;if(!s||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=si(i);return d?d.provider==="github"?Ee.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:s,base:o,title:a,body:c},t):je.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:s,target_branch:o,title:a,description:c},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_open_pr supports github.com and gitlab.com.`})}catch(n){return JSON.stringify({error:n.message})}},tools:[...ue.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 pi}from"child_process";import{existsSync as lr,mkdirSync as ui}from"fs";import{join as ce,basename as Zl}from"path";import{randomBytes as Vl}from"crypto";import{pathToFileURL as Xe}from"url";import{createRequire as mi}from"module";var or=".zibby/memory",fi="dolt",hi={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},ar="mem0",ir=new Map,wt=new Map,St=!1,Ql=mi(import.meta.url),Ot=()=>Vl(8).toString("hex"),ve=()=>new Date().toISOString(),Xl=[`CREATE TABLE IF NOT EXISTS chat_memory (
628
+ 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(r,e,t){if(r!=="git_open_pr"&&r!=="git_merge_pr")return ue.handleToolCall(r,e,t);try{let n=e||{},i=n.repoUrl||n.repo_url||n.url;if(!i)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(r==="git_merge_pr"){let l=n.number??n.iid??n.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let p=ai(i);return p?p.provider==="github"?Ee.handleToolCall("github_merge_pr",{owner:p.owner,repo:p.repo,number:l,mergeMethod:n.mergeMethod},t):je.handleToolCall("gitlab_accept_mr",{project:`${p.owner}/${p.repo}`,iid:l},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_merge_pr supports github.com and gitlab.com.`})}let s=n.head||n.source_branch||n.sourceBranch||n.branch,o=n.base||n.target_branch||n.targetBranch,{title:a,body:c}=n;if(!s||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=ai(i);return d?d.provider==="github"?Ee.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:s,base:o,title:a,body:c},t):je.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:s,target_branch:o,title:a,description:c},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_open_pr supports github.com and gitlab.com.`})}catch(n){return JSON.stringify({error:n.message})}},tools:[...ue.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 mi}from"child_process";import{existsSync as pr,mkdirSync as fi}from"fs";import{join as ce,basename as id}from"path";import{randomBytes as sd}from"crypto";import{pathToFileURL as Xe}from"url";import{createRequire as hi}from"module";var cr=".zibby/memory",yi="dolt",gi={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},lr="mem0",or=new Map,wt=new Map,St=!1,od=hi(import.meta.url),Ot=()=>sd(8).toString("hex"),Ie=()=>new Date().toISOString(),ad=[`CREATE TABLE IF NOT EXISTS chat_memory (
629
629
  id VARCHAR(64) PRIMARY KEY,
630
630
  memory_key VARCHAR(160),
631
631
  category VARCHAR(32) NOT NULL,
@@ -656,10 +656,10 @@ To MERGE an open PR/MR, use the provider-agnostic tool:
656
656
  tasks_failed INT DEFAULT 0,
657
657
  key_facts TEXT,
658
658
  created_at VARCHAR(32) NOT NULL
659
- )`],ai=new Set;function M(r,e){return pi(fi,e,{...hi,cwd:r})}function ge(r,e){try{let t=M(r,["sql","-q",e,"-r","json"]);return JSON.parse(t.trim()).rows||[]}catch{return[]}}function F(r,e){M(r,["sql","-q",e])}function It(r){if(ai.has(r))return!0;if(!lr(ce(r,".dolt"))){if(!ed())return!1;ui(r,{recursive:!0}),M(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${Xl.join(`;
660
- `)};`;F(r,e);try{F(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{F(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return ai.add(r),!0}function ed(){try{return pi(fi,["version"],{...hi,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function cr(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function Ce(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function dr(r,e){let t=["short","mid","long"].includes(r)?r:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(e||"").toLowerCase())&&t==="short"?"mid":t}function gi(r){let e=new Map;for(let t of r||[]){let n=cr(t.content),i=t.memory_key?`key:${t.memory_key}`:n?`norm:${n}`:"";if(!i)continue;let s=e.get(i);if(!s){e.set(i,t);continue}let o=Ce(s.tier),a=Ce(t.tier);if(a>o){e.set(i,t);continue}a===o&&Number(t.relevance||0)>Number(s.relevance||0)&&e.set(i,t)}return[...e.values()]}function Nt(r,e){let t=String(r??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function Qe(r,e){let t={recentSessions:Array.isArray(r?.recentSessions)?r.recentSessions:[],topMemories:Array.isArray(r?.topMemories)?r.topMemories:[],taskStats:Array.isArray(r?.taskStats)?r.taskStats:[],ticketFilter:r?.ticketFilter||null,backend:e||String(r?.backend||ar),error:r?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function ci(r){let e=[];if(r.recentSessions?.length>0){e.push("Recent sessions:");for(let t of r.recentSessions.slice(0,3))t?.summary?.trim()&&e.push(`- ${Nt(t.summary,150)}${t.tickets?` [${t.tickets}]`:""}`)}if(r.topMemories?.length>0){e.push("Known facts:");for(let t of r.topMemories.slice(0,10)){let n=t.tier==="long"?"\u2605":"\xB7";e.push(`${n} [${t.category}] ${Nt(t.content,120)}`)}}return e.length===0?"":`## Memory Context
659
+ )`],li=new Set;function M(r,e){return mi(yi,e,{...gi,cwd:r})}function ye(r,e){try{let t=M(r,["sql","-q",e,"-r","json"]);return JSON.parse(t.trim()).rows||[]}catch{return[]}}function F(r,e){M(r,["sql","-q",e])}function vt(r){if(li.has(r))return!0;if(!pr(ce(r,".dolt"))){if(!cd())return!1;fi(r,{recursive:!0}),M(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${ad.join(`;
660
+ `)};`;F(r,e);try{F(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{F(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return li.add(r),!0}function cd(){try{return mi(yi,["version"],{...gi,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function dr(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function Ce(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function ur(r,e){let t=["short","mid","long"].includes(r)?r:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(e||"").toLowerCase())&&t==="short"?"mid":t}function _i(r){let e=new Map;for(let t of r||[]){let n=dr(t.content),i=t.memory_key?`key:${t.memory_key}`:n?`norm:${n}`:"";if(!i)continue;let s=e.get(i);if(!s){e.set(i,t);continue}let o=Ce(s.tier),a=Ce(t.tier);if(a>o){e.set(i,t);continue}a===o&&Number(t.relevance||0)>Number(s.relevance||0)&&e.set(i,t)}return[...e.values()]}function Nt(r,e){let t=String(r??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function Qe(r,e){let t={recentSessions:Array.isArray(r?.recentSessions)?r.recentSessions:[],topMemories:Array.isArray(r?.topMemories)?r.topMemories:[],taskStats:Array.isArray(r?.taskStats)?r.taskStats:[],ticketFilter:r?.ticketFilter||null,backend:e||String(r?.backend||lr),error:r?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function di(r){let e=[];if(r.recentSessions?.length>0){e.push("Recent sessions:");for(let t of r.recentSessions.slice(0,3))t?.summary?.trim()&&e.push(`- ${Nt(t.summary,150)}${t.tickets?` [${t.tickets}]`:""}`)}if(r.topMemories?.length>0){e.push("Known facts:");for(let t of r.topMemories.slice(0,10)){let n=t.tier==="long"?"\u2605":"\xB7";e.push(`${n} [${t.category}] ${Nt(t.content,120)}`)}}return e.length===0?"":`## Memory Context
661
661
  ${e.join(`
662
- `)}`}function vt(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:Nt(String(e?.summary||""),160),tickets:e?.tickets||null,created_at:e?.created_at||null})),topMemories:r.topMemories.slice(0,8).map(e=>({category:e?.category||null,tier:e?.tier||null,content:Nt(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function td(r,e){let t=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(t==="mem0"||t==="dolt")return t;let n=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(n==="mem0"||n==="dolt")return n;if(wt.has(r))return wt.get(r);try{let i=ce(r,".zibby.config.mjs");if(lr(i)){let s=await import(Xe(i).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return wt.set(r,o),o}}catch{}return wt.set(r,ar),ar}function yi(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${Zl(r||process.cwd())}`}var rd="mem0";function _i(r){let e=ce(r,or,rd);return{dir:e,vectorDbPath:ce(e,"vectors.db"),historyDbPath:ce(e,"history.db")}}function nd(r){let e=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!e)return null;let t=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),n=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(),s=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=_i(r||process.cwd());return{llm:{provider:"openai",config:{model:n,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:s,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function bi(r){let e=r||process.cwd();if(ir.has(e))return ir.get(e);let t;try{let a=mi(Xe(ce(e,"package.json")).href).resolve("mem0ai/oss");t=await import(Xe(a).href)}catch{try{let o=Ql.resolve("mem0ai/oss");t=await import(Xe(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let n=t?.Memory;if(!n)throw new Error("mem0ai/oss does not export Memory");let i=nd(e);if(i)try{ui(_i(e).dir,{recursive:!0})}catch{}let s=i?new n(i):new n;return ir.set(e,s),s}function li(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||Ot(),memory_key:n?.metadata?.memoryKey||n?.metadata?.memory_key||null,category:n?.metadata?.category||"fact",content:n?.memory||n?.content||"",source:n?.metadata?.source||"mem0",ticket_key:n?.metadata?.ticketKey||n?.metadata?.ticket_key||null,tier:dr(n?.metadata?.tier||e,n?.metadata?.category||"fact"),relevance:Number(n?.score??n?.metadata?.relevance??.8),created_at:n?.created_at||n?.metadata?.created_at||ve()})).filter(n=>String(n.content||"").trim().length>0)}var Ue={id:"dolt",store:(r,e)=>wi(r,e),recall:(r,e)=>ld(r,e),brief:(r,e)=>dd(r,e),endSession:(r,e)=>Ii(r,e),logTask:(r,e)=>vi(r,e),taskHistory:(r,e)=>Ni(r,e)},id={id:"mem0",store:(r,e,t)=>cd(r,e,t),recall:(r,e,t)=>Si(r,e,t),brief:(r,e,t)=>pd(r,e,t),endSession:(r,e)=>Ii(r,e),logTask:(r,e)=>vi(r,e),taskHistory:(r,e)=>Ni(r,e)},sd={dolt:Ue,mem0:id};async function di(r,e){let t=await td(r,e);return sd[t]||Ue}var ki={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
662
+ `)}`}function It(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:Nt(String(e?.summary||""),160),tickets:e?.tickets||null,created_at:e?.created_at||null})),topMemories:r.topMemories.slice(0,8).map(e=>({category:e?.category||null,tier:e?.tier||null,content:Nt(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function ld(r,e){let t=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(t==="mem0"||t==="dolt")return t;let n=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(n==="mem0"||n==="dolt")return n;if(wt.has(r))return wt.get(r);try{let i=ce(r,".zibby.config.mjs");if(pr(i)){let s=await import(Xe(i).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return wt.set(r,o),o}}catch{}return wt.set(r,lr),lr}function bi(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${id(r||process.cwd())}`}var dd="mem0";function ki(r){let e=ce(r,cr,dd);return{dir:e,vectorDbPath:ce(e,"vectors.db"),historyDbPath:ce(e,"history.db")}}function pd(r){let e=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!e)return null;let t=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),n=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(),s=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=ki(r||process.cwd());return{llm:{provider:"openai",config:{model:n,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:s,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function wi(r){let e=r||process.cwd();if(or.has(e))return or.get(e);let t;try{let a=hi(Xe(ce(e,"package.json")).href).resolve("mem0ai/oss");t=await import(Xe(a).href)}catch{try{let o=od.resolve("mem0ai/oss");t=await import(Xe(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let n=t?.Memory;if(!n)throw new Error("mem0ai/oss does not export Memory");let i=pd(e);if(i)try{fi(ki(e).dir,{recursive:!0})}catch{}let s=i?new n(i):new n;return or.set(e,s),s}function pi(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||Ot(),memory_key:n?.metadata?.memoryKey||n?.metadata?.memory_key||null,category:n?.metadata?.category||"fact",content:n?.memory||n?.content||"",source:n?.metadata?.source||"mem0",ticket_key:n?.metadata?.ticketKey||n?.metadata?.ticket_key||null,tier:ur(n?.metadata?.tier||e,n?.metadata?.category||"fact"),relevance:Number(n?.score??n?.metadata?.relevance??.8),created_at:n?.created_at||n?.metadata?.created_at||Ie()})).filter(n=>String(n.content||"").trim().length>0)}var Ue={id:"dolt",store:(r,e)=>vi(r,e),recall:(r,e)=>gd(r,e),brief:(r,e)=>_d(r,e),endSession:(r,e)=>Ni(r,e),logTask:(r,e)=>Oi(r,e),taskHistory:(r,e)=>Ti(r,e)},ud={id:"mem0",store:(r,e,t)=>yd(r,e,t),recall:(r,e,t)=>Ii(r,e,t),brief:(r,e,t)=>bd(r,e,t),endSession:(r,e)=>Ni(r,e),logTask:(r,e)=>Oi(r,e),taskHistory:(r,e)=>Ti(r,e)},md={dolt:Ue,mem0:ud};async function ui(r,e){let t=await ld(r,e);return md[t]||Ue}var Si={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
663
663
  You have persistent memory across sessions. Use it to avoid losing context:
664
664
  - **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
665
665
  - **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
@@ -675,40 +675,40 @@ You have persistent memory across sessions. Use it to avoid losing context:
675
675
  - When the user's request is complete: call memory_end_session
676
676
 
677
677
  ### Categories for memory_store
678
- fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,e={}){let t=r?.options?.workspace||process.cwd(),n=ce(t,or),i=await di(t,r),s=i.id;if(s==="dolt"&&!It(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:Qe({backend:s,error:o},s),promptContext:"",debugPreview:vt(Qe({backend:s,error:o},s)),error:o}}try{let o=await i.brief(e,n,t),a=JSON.parse(o||"{}"),c=Qe({...a,backend:s},s);return{backend:s,brief:c,promptContext:ci(c),debugPreview:vt(c),error:c.error||null}}catch(o){if(s==="mem0"&&i!==Ue&&It(n)){if(!St){St=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
679
- `)}catch{}}try{let d=await Ue.brief(e,n,t),l=JSON.parse(d||"{}"),p=Qe({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:ci(p),debugPreview:vt(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=Qe({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:vt(c),error:a}}},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd(),i=ce(n,or),s=await di(n,t),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!It(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(r){case"memory_store":return d.store(e,i,n);case"memory_recall":return d.recall(e,i,n);case"memory_brief":return d.brief(e,i,n);case"memory_end_session":return d.endSession(e,i,n);case"task_log":return d.logTask(e,i,n);case"task_history":return d.taskHistory(e,i,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(d){if(o==="mem0"&&s!==Ue){if(It(i)){if(!St){St=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
680
- `)}catch{}}try{return await c(Ue)}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 wi(r,e){let{content:t,category:n,source:i,ticketKey:s,tier:o,memoryKey:a}=r;if(!t||!n)return JSON.stringify({error:"content and category are required"});let c=cr(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=dr(o,n),l=d==="long"?1:d==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let _=ge(e,`SELECT id, tier, relevance
678
+ fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,e={}){let t=r?.options?.workspace||process.cwd(),n=ce(t,cr),i=await ui(t,r),s=i.id;if(s==="dolt"&&!vt(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:Qe({backend:s,error:o},s),promptContext:"",debugPreview:It(Qe({backend:s,error:o},s)),error:o}}try{let o=await i.brief(e,n,t),a=JSON.parse(o||"{}"),c=Qe({...a,backend:s},s);return{backend:s,brief:c,promptContext:di(c),debugPreview:It(c),error:c.error||null}}catch(o){if(s==="mem0"&&i!==Ue&&vt(n)){if(!St){St=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
679
+ `)}catch{}}try{let d=await Ue.brief(e,n,t),l=JSON.parse(d||"{}"),p=Qe({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:di(p),debugPreview:It(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=Qe({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:It(c),error:a}}},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd(),i=ce(n,cr),s=await ui(n,t),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!vt(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(r){case"memory_store":return d.store(e,i,n);case"memory_recall":return d.recall(e,i,n);case"memory_brief":return d.brief(e,i,n);case"memory_end_session":return d.endSession(e,i,n);case"task_log":return d.logTask(e,i,n);case"task_history":return d.taskHistory(e,i,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(d){if(o==="mem0"&&s!==Ue){if(vt(i)){if(!St){St=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
680
+ `)}catch{}}try{return await c(Ue)}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 vi(r,e){let{content:t,category:n,source:i,ticketKey:s,tier:o,memoryKey:a}=r;if(!t||!n)return JSON.stringify({error:"content and category are required"});let c=dr(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=ur(o,n),l=d==="long"?1:d==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let _=ye(e,`SELECT id, tier, relevance
681
681
  FROM chat_memory
682
682
  WHERE memory_key = ${S(p)}
683
683
  ORDER BY created_at DESC
684
- LIMIT 1`)[0];if(_){let b=String(_.tier||"mid"),g=Number(_.relevance||0),k=Ce(d)>Ce(b)?d:b,R=Math.max(l,g);F(e,`UPDATE chat_memory
684
+ LIMIT 1`)[0];if(_){let b=String(_.tier||"mid"),y=Number(_.relevance||0),k=Ce(d)>Ce(b)?d:b,T=Math.max(l,y);F(e,`UPDATE chat_memory
685
685
  SET content = ${S(t)},
686
686
  category = ${S(n)},
687
687
  source = ${S(i)},
688
688
  ticket_key = ${S(s)},
689
689
  tier = ${S(k)},
690
- relevance = ${R},
691
- created_at = ${S(ve())}
692
- WHERE id = ${S(_.id)}`);try{M(e,["add","."]),M(e,["commit","-m",`memory upsert: ${n} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:_.id,category:n,tier:k,memoryKey:p,upserted:!0})}}let m=ge(e,`SELECT id, content, tier, relevance
690
+ relevance = ${T},
691
+ created_at = ${S(Ie())}
692
+ WHERE id = ${S(_.id)}`);try{M(e,["add","."]),M(e,["commit","-m",`memory upsert: ${n} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:_.id,category:n,tier:k,memoryKey:p,upserted:!0})}}let m=ye(e,`SELECT id, content, tier, relevance
693
693
  FROM chat_memory
694
694
  WHERE category = ${S(n)}
695
695
  ORDER BY created_at DESC
696
- LIMIT 200`).find(y=>cr(y.content)===c);if(m){let y=String(m.tier||"mid"),_=Number(m.relevance||0),b=Ce(d)>Ce(y),g=l>_;if(b||g){F(e,`UPDATE chat_memory
697
- SET tier = ${S(b?d:y)},
696
+ LIMIT 200`).find(g=>dr(g.content)===c);if(m){let g=String(m.tier||"mid"),_=Number(m.relevance||0),b=Ce(d)>Ce(g),y=l>_;if(b||y){F(e,`UPDATE chat_memory
697
+ SET tier = ${S(b?d:g)},
698
698
  relevance = ${Math.max(l,_)}
699
- WHERE id = ${S(m.id)}`);try{M(e,["add","."]),M(e,["commit","-m",`memory promote: ${n} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:n,tier:b?d:y,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:n,tier:y,deduped:!0,promoted:!1})}let f=Ot(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;F(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
700
- VALUES (${S(f)}, ${S(p||null)}, ${S(n)}, ${S(t)}, ${S(i)}, ${S(s)}, ${S(h)}, ${S(d)}, ${l}, ${S(ve())})`);try{M(e,["add","."]),M(e,["commit","-m",`memory: ${n} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:n,tier:d,memoryKey:p||null,stored:t.slice(0,100)})}function od(r){let e=String(r||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var sr=new Map;async function ad(r,e){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return od(process.env.ZIBBY_MEM0_INFER);let t=e||process.cwd();if(sr.has(t))return sr.get(t);let n=!1;try{let i=ce(t,".zibby.config.mjs");lr(i)&&(n=(await import(Xe(i).href))?.default?.memory?.infer===!0)}catch{}return sr.set(t,n),n}async function cd(r,e,t){let{content:n,category:i,source:s,ticketKey:o,tier:a,memoryKey:c,infer:d}=r;if(!n||!i)return JSON.stringify({error:"content and category are required"});try{let l=await bi(t),p=yi(t),u=dr(a,i),m=await ad(d,t);return await l.add([{role:"user",content:String(n)}],{userId:p,infer:m,metadata:{memoryKey:c||null,category:i,tier:u,source:s||"zibby-chat",ticketKey:o||null,created_at:ve()}}),JSON.stringify({ok:!0,backend:"mem0",userId:p,category:i,tier:u,infer:m,memoryKey:c||null,stored:String(n).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 ld(r,e){let{query:t,category:n,ticketKey:i,tier:s,limit:o=20}=r,a=[];t&&a.push(`content LIKE ${S(`%${t}%`)}`),n&&a.push(`category = ${S(n)}`),i&&a.push(`ticket_key = ${S(i)}`),s&&a.push(`tier = ${S(s)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
699
+ WHERE id = ${S(m.id)}`);try{M(e,["add","."]),M(e,["commit","-m",`memory promote: ${n} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:n,tier:b?d:g,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:n,tier:g,deduped:!0,promoted:!1})}let f=Ot(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;F(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
700
+ VALUES (${S(f)}, ${S(p||null)}, ${S(n)}, ${S(t)}, ${S(i)}, ${S(s)}, ${S(h)}, ${S(d)}, ${l}, ${S(Ie())})`);try{M(e,["add","."]),M(e,["commit","-m",`memory: ${n} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:n,tier:d,memoryKey:p||null,stored:t.slice(0,100)})}function fd(r){let e=String(r||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var ar=new Map;async function hd(r,e){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return fd(process.env.ZIBBY_MEM0_INFER);let t=e||process.cwd();if(ar.has(t))return ar.get(t);let n=!1;try{let i=ce(t,".zibby.config.mjs");pr(i)&&(n=(await import(Xe(i).href))?.default?.memory?.infer===!0)}catch{}return ar.set(t,n),n}async function yd(r,e,t){let{content:n,category:i,source:s,ticketKey:o,tier:a,memoryKey:c,infer:d}=r;if(!n||!i)return JSON.stringify({error:"content and category are required"});try{let l=await wi(t),p=bi(t),u=ur(a,i),m=await hd(d,t);return await l.add([{role:"user",content:String(n)}],{userId:p,infer:m,metadata:{memoryKey:c||null,category:i,tier:u,source:s||"zibby-chat",ticketKey:o||null,created_at:Ie()}}),JSON.stringify({ok:!0,backend:"mem0",userId:p,category:i,tier:u,infer:m,memoryKey:c||null,stored:String(n).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 gd(r,e){let{query:t,category:n,ticketKey:i,tier:s,limit:o=20}=r,a=[];t&&a.push(`content LIKE ${S(`%${t}%`)}`),n&&a.push(`category = ${S(n)}`),i&&a.push(`ticket_key = ${S(i)}`),s&&a.push(`tier = ${S(s)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
701
701
  FROM chat_memory ${a.length>0?`WHERE ${a.join(" AND ")}`:""}
702
702
  ORDER BY relevance DESC, created_at DESC
703
- LIMIT ${o}`,l=ge(e,d);return JSON.stringify({total:l.length,memories:l})}async function Si(r,e,t){let{query:n,category:i,ticketKey:s,tier:o,limit:a=20}=r;try{let c=await bi(t),d=yi(t),l=[];if(n&&String(n).trim()){let p=await c.search(String(n),{filters:{user_id:d},topK:a});l=li(p)}else{let p=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=li(p)}return i&&(l=l.filter(p=>p.category===i)),s&&(l=l.filter(p=>p.ticket_key===s)),o&&(l=l.filter(p=>p.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 dd(r,e){let{ticketKey:t}=r;md(e);let i=ge(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
704
- FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),s=t?`AND ticket_key = ${S(t)}`:"",o=ge(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
705
- WHERE tier = 'long' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=ge(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
706
- WHERE tier = 'mid' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 8`),d=ge(e,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
707
- GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=gi([...o,...a]);return JSON.stringify({recentSessions:i,topMemories:l,taskStats:d,ticketFilter:t||null})}async function pd(r,e,t){let{ticketKey:n}=r,i=await Si({limit:80},e,t),s=JSON.parse(i||"{}"),o=Array.isArray(s.memories)?s.memories:[];n&&(o=o.filter(u=>u.ticket_key===n));let a=u=>{let m=Date.parse(String(u?.created_at||""))||0;return Number(u?.relevance||0)*1e12+m},c=(u,m)=>a(m)-a(u),d=o.filter(u=>u.tier==="long").sort(c).slice(0,10),l=o.filter(u=>u.tier==="mid").sort(c).slice(0,8),p=gi([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:p,taskStats:[],ticketFilter:n||null,backend:"mem0"})}function Ii(r,e){let{summary:t,tickets:n,tasksRun:i=0,tasksPassed:s=0,tasksFailed:o=0,keyFacts:a}=r;if(!t)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${Ot()}`;if(F(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
708
- VALUES (${S(c)}, ${S(t)}, ${S(n)}, ${i}, ${s}, ${o}, ${S(a)}, ${S(ve())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))wi({content:d,category:"fact",source:"session_summary",tier:"mid"},e);ud(e);try{M(e,["add","."]),M(e,["commit","-m",`session end: ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:t.slice(0,200)})}function vi(r,e){let{title:t,type:n,status:i,ticketKey:s,specPath:o,resultSummary:a}=r;if(!t||!n||!i)return JSON.stringify({error:"title, type, and status are required"});let c=Ot(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;F(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
709
- VALUES (${S(c)}, ${S(s)}, ${S(n)}, ${S(t)}, ${S(i)}, ${S(o)}, ${S(d)}, ${S(a)}, ${S(ve())}, ${S(ve())})`);try{M(e,["add","."]),M(e,["commit","-m",`task: ${i} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:t,type:n,status:i})}function Ni(r,e){let{ticketKey:t,type:n,status:i,limit:s=20}=r,o=[];t&&o.push(`ticket_key = ${S(t)}`),n&&o.push(`type = ${S(n)}`),i&&o.push(`status = ${S(i)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
703
+ LIMIT ${o}`,l=ye(e,d);return JSON.stringify({total:l.length,memories:l})}async function Ii(r,e,t){let{query:n,category:i,ticketKey:s,tier:o,limit:a=20}=r;try{let c=await wi(t),d=bi(t),l=[];if(n&&String(n).trim()){let p=await c.search(String(n),{filters:{user_id:d},topK:a});l=pi(p)}else{let p=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=pi(p)}return i&&(l=l.filter(p=>p.category===i)),s&&(l=l.filter(p=>p.ticket_key===s)),o&&(l=l.filter(p=>p.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 _d(r,e){let{ticketKey:t}=r;wd(e);let i=ye(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
704
+ FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),s=t?`AND ticket_key = ${S(t)}`:"",o=ye(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
705
+ WHERE tier = 'long' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=ye(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
706
+ WHERE tier = 'mid' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 8`),d=ye(e,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
707
+ GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=_i([...o,...a]);return JSON.stringify({recentSessions:i,topMemories:l,taskStats:d,ticketFilter:t||null})}async function bd(r,e,t){let{ticketKey:n}=r,i=await Ii({limit:80},e,t),s=JSON.parse(i||"{}"),o=Array.isArray(s.memories)?s.memories:[];n&&(o=o.filter(u=>u.ticket_key===n));let a=u=>{let m=Date.parse(String(u?.created_at||""))||0;return Number(u?.relevance||0)*1e12+m},c=(u,m)=>a(m)-a(u),d=o.filter(u=>u.tier==="long").sort(c).slice(0,10),l=o.filter(u=>u.tier==="mid").sort(c).slice(0,8),p=_i([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:p,taskStats:[],ticketFilter:n||null,backend:"mem0"})}function Ni(r,e){let{summary:t,tickets:n,tasksRun:i=0,tasksPassed:s=0,tasksFailed:o=0,keyFacts:a}=r;if(!t)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${Ot()}`;if(F(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
708
+ VALUES (${S(c)}, ${S(t)}, ${S(n)}, ${i}, ${s}, ${o}, ${S(a)}, ${S(Ie())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))vi({content:d,category:"fact",source:"session_summary",tier:"mid"},e);kd(e);try{M(e,["add","."]),M(e,["commit","-m",`session end: ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:t.slice(0,200)})}function Oi(r,e){let{title:t,type:n,status:i,ticketKey:s,specPath:o,resultSummary:a}=r;if(!t||!n||!i)return JSON.stringify({error:"title, type, and status are required"});let c=Ot(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;F(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
709
+ VALUES (${S(c)}, ${S(s)}, ${S(n)}, ${S(t)}, ${S(i)}, ${S(o)}, ${S(d)}, ${S(a)}, ${S(Ie())}, ${S(Ie())})`);try{M(e,["add","."]),M(e,["commit","-m",`task: ${i} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:t,type:n,status:i})}function Ti(r,e){let{ticketKey:t,type:n,status:i,limit:s=20}=r,o=[];t&&o.push(`ticket_key = ${S(t)}`),n&&o.push(`type = ${S(n)}`),i&&o.push(`status = ${S(i)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
710
710
  FROM chat_tasks ${o.length>0?`WHERE ${o.join(" AND ")}`:""}
711
- ORDER BY created_at DESC LIMIT ${s}`,d=ge(e,c);return JSON.stringify({total:d.length,tasks:d})}function ud(r){try{F(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),F(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),F(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),F(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function md(r){try{let e=new Date(Date.now()-864e5).toISOString();F(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(e)}`)}catch{}}import{existsSync as Oi,readFileSync as fd}from"node:fs";import{homedir as hd}from"node:os";import{join as gd,dirname as yd,resolve as _d}from"node:path";import{fileURLToPath as bd}from"node:url";function kd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=yd(bd(import.meta.url)),e=_d(r,"..","bin","mcp-skill.mjs");return Oi(e)?e:null}function wd(){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 r=gd(hd(),".zibby","config.json");return Oi(r)&&JSON.parse(fd(r,"utf-8")).sessionToken||null}catch{return null}}function Sd(){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 Id(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function pr(r){return`${Id()}:${r}`}async function ur(r,e){let t=wd();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${Sd()}/credits/review-memory`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${i.status}): ${s.slice(0,300)}`)}return i.json()}var Ri={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)
711
+ ORDER BY created_at DESC LIMIT ${s}`,d=ye(e,c);return JSON.stringify({total:d.length,tasks:d})}function kd(r){try{F(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),F(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),F(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),F(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function wd(r){try{let e=new Date(Date.now()-864e5).toISOString();F(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(e)}`)}catch{}}import{existsSync as Ri,readFileSync as Sd}from"node:fs";import{homedir as vd}from"node:os";import{join as Id,dirname as Nd,resolve as Od}from"node:path";import{fileURLToPath as Td}from"node:url";function Rd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Nd(Td(import.meta.url)),e=Od(r,"..","bin","mcp-skill.mjs");return Ri(e)?e:null}function Ad(){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 r=Id(vd(),".zibby","config.json");return Ri(r)&&JSON.parse(Sd(r,"utf-8")).sessionToken||null}catch{return null}}function xd(){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 Ed(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function mr(r){return`${Ed()}:${r}`}async function fr(r,e){let t=Ad();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${xd()}/credits/review-memory`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${i.status}): ${s.slice(0,300)}`)}return i.json()}var Ai={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)
712
712
  You have a PRIVATE per-agent key-value memory that survives across your
713
713
  stateless runs. It is automatically namespaced to YOU (this agent type) \u2014 other
714
714
  agents cannot see or collide with your entries, and you don't need to prefix
@@ -723,7 +723,7 @@ Tools:
723
723
  Use to record durable facts \u2014 e.g. dedup markers, prior decisions, summaries.
724
724
 
725
725
  Your namespace is added for you automatically; pass plain keys like
726
- "seen#owner/repo#42" or "lastRun".`,resolve(){let r=kd();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/kvMemory.js","kvMemorySkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"kv_recall":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});let n=await ur("recall",{scope:pr(t)});return JSON.stringify(n)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let n=await ur("recall-prefix",{scopePrefix:pr(t)});return JSON.stringify(n)}case"kv_store":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});if(typeof e?.content!="string"||e.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let n={scope:pr(t),content:e.content};e.metadata!=null&&(n.metadata=e.metadata);let i=await ur("store",n);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 Ai,readFileSync as vd}from"node:fs";import{homedir as Nd}from"node:os";import{join as Od,dirname as Rd,resolve as Td}from"node:path";import{fileURLToPath as Ad}from"node:url";function xd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Rd(Ad(import.meta.url)),e=Td(r,"..","bin","mcp-skill.mjs");return Ai(e)?e:null}function xi(){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 r=Od(Nd(),".zibby","config.json");return Ai(r)&&JSON.parse(vd(r,"utf-8")).sessionToken||null}catch{return null}}function Ei(){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 Ti(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Ed(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}var ji={};function mr(r){let e={...Ed(),...ji},t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function jd(r){let e=xi();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${Ei()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let n=await t.text().catch(()=>"");throw new Error(`ensure_store failed (${t.status}): ${n.slice(0,300)}`)}return t.json()}async function fr(r,e,t){let n=xi();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${Ei()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${e} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var Li={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)
726
+ "seen#owner/repo#42" or "lastRun".`,resolve(){let r=Rd();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/kvMemory.js","kvMemorySkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"kv_recall":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});let n=await fr("recall",{scope:mr(t)});return JSON.stringify(n)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let n=await fr("recall-prefix",{scopePrefix:mr(t)});return JSON.stringify(n)}case"kv_store":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});if(typeof e?.content!="string"||e.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let n={scope:mr(t),content:e.content};e.metadata!=null&&(n.metadata=e.metadata);let i=await fr("store",n);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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 Ei,readFileSync as jd}from"node:fs";import{homedir as Ld}from"node:os";import{join as $d,dirname as Pd,resolve as Cd}from"node:path";import{fileURLToPath as Ud}from"node:url";function Jd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Pd(Ud(import.meta.url)),e=Cd(r,"..","bin","mcp-skill.mjs");return Ei(e)?e:null}function ji(){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 r=$d(Ld(),".zibby","config.json");return Ei(r)&&JSON.parse(jd(r,"utf-8")).sessionToken||null}catch{return null}}function Li(){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 xi(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function qd(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}var $i={};function hr(r){let e={...qd(),...$i},t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function Dd(r){let e=ji();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${Li()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let n=await t.text().catch(()=>"");throw new Error(`ensure_store failed (${t.status}): ${n.slice(0,300)}`)}return t.json()}async function yr(r,e,t){let n=ji();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${Li()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${e} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var Pi={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)
727
727
  You have one or more durable stores for STRUCTURED records that survive across
728
728
  your stateless runs. Unlike key-value memory (for picking up where you left
729
729
  off), this is for accumulating DATA you want to QUERY and AGGREGATE later \u2014 e.g.
@@ -759,17 +759,38 @@ Tools:
759
759
  - sqlite_query: (sqlite stores) Run a SELECT (optionally with \`params\` for safe
760
760
  binding). Returns { columns, rows }. Read-only \u2014 never changes data.
761
761
  Pick the tool that matches the store's TYPE; using a dataset tool on a sqlite
762
- store (or vice-versa) is rejected.`,resolve(){let r=xd();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);for(let t of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(t)&&process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/datasetStore.js","datasetStoreSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e){try{switch(r){case"dataset_append":{if(e?.record==null||typeof e.record!="object"||Array.isArray(e.record))return JSON.stringify({error:"record is required (a JSON object)"});let t=mr(e?.store);if(t.error)return JSON.stringify({error:t.error});let n=typeof e?.agent=="string"&&e.agent.trim()?e.agent.trim():Ti(),i={record:e.record,agent:n};typeof e?.description=="string"&&e.description.trim()&&(i.description=e.description.trim());let s=await fr(t.storeId,"append",i);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"dataset_query":{let t=mr(e?.store);if(t.error)return JSON.stringify({error:t.error});let n={};for(let s of["select","where","groupBy","orderBy","limit","since","until","agent"])e?.[s]!=null&&(n[s]=e[s]);let i=await fr(t.storeId,"query",n);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}case"ensure_store":{let t=typeof e?.name=="string"?e.name.trim():"";if(!t)return JSON.stringify({error:"name is required"});let n=typeof e?.type=="string"&&e.type.trim()?e.type.trim().toLowerCase():"sqlite",i=typeof e?.description=="string"?e.description.trim():"",s=await jd({name:t,type:n,description:i,namespace:Ti()});return s?.storeId&&(ji[t]=s.storeId),JSON.stringify({...s,store:t})}case"sqlite_exec":case"sqlite_query":{let t=mr(e?.store);if(t.error)return JSON.stringify({error:t.error});if(typeof e?.sql!="string"||!e.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let n={sql:e.sql};Array.isArray(e?.params)&&(n.params=e.params);let i=await fr(t.storeId,"sql",n);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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{createRequire as Ld}from"node:module";import{existsSync as Ui,mkdirSync as $d,writeFileSync as $i}from"node:fs";import{dirname as qi,join as qe,resolve as Ji}from"node:path";import{fileURLToPath as Di}from"node:url";var Bi=Ld(import.meta.url),hr=null;function Pd(){return hr||(hr=Bi("echarts")),hr}var gr=null;function Cd(){return gr||(gr=Bi("@resvg/resvg-js")),gr}var Ud=800,qd=600,Jd=4096,Dd=16,Pi=60,Mi="Noto Sans";function Bd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=qi(Di(import.meta.url)),e=Ji(r,"..","bin","mcp-skill.mjs");return Ui(e)?e:null}function Md(){let r=qi(Di(import.meta.url)),e=Ji(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>qe(e,t)).filter(t=>Ui(t))}function Fd(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?qe(e,"chart-render"):qe(process.cwd(),".zibby","output","charts"));return $d(t,{recursive:!0}),t}function Ne(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function Ci(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(Dd,Math.min(Jd,Math.round(t))):e}function yr(r){return typeof r!="string"||r.length<=Pi?r:`${r.slice(0,Pi-1)}\u2026`}function Rt(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=yr(t):Ne(t)&&typeof t.name=="string"&&(t.name=yr(t.name))}}function Gd(r){for(let n of["xAxis","yAxis"]){let i=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let s of i)Ne(s)&&Rt(s.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of e)Ne(n)&&Rt(n.indicator);Ne(r.legend)&&Rt(r.legend.data);let t=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of t)Ne(n)&&(typeof n.name=="string"&&(n.name=yr(n.name)),Rt(n.data))}function Kd(r){let e=JSON.parse(JSON.stringify(r));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),Ne(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=Mi),Gd(e),e}function Hd(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function zd(r,e,t){let i=Pd().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return i.setOption(r),i.renderToSVGString()}finally{i.dispose()}}function Wd(r){let{Resvg:e}=Cd();return new e(r,{font:{fontFiles:Md(),loadSystemFonts:!0,defaultFontFamily:Mi}}).render().asPng()}var Fi={id:"chart-render",serverName:"chart_render",allowedTools:["mcp__chart_render__*"],description:"Chart render \u2014 local server-side chart rendering (Apache ECharts SVG SSR + resvg PNG); data never leaves the box",promptFragment:`## Chart Render (local, no external service)
762
+ store (or vice-versa) is rejected.`,resolve(){let r=Jd();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);for(let t of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(t)&&process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/datasetStore.js","datasetStoreSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e){try{switch(r){case"dataset_append":{if(e?.record==null||typeof e.record!="object"||Array.isArray(e.record))return JSON.stringify({error:"record is required (a JSON object)"});let t=hr(e?.store);if(t.error)return JSON.stringify({error:t.error});let n=typeof e?.agent=="string"&&e.agent.trim()?e.agent.trim():xi(),i={record:e.record,agent:n};typeof e?.description=="string"&&e.description.trim()&&(i.description=e.description.trim());let s=await yr(t.storeId,"append",i);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"dataset_query":{let t=hr(e?.store);if(t.error)return JSON.stringify({error:t.error});let n={};for(let s of["select","where","groupBy","orderBy","limit","since","until","agent"])e?.[s]!=null&&(n[s]=e[s]);let i=await yr(t.storeId,"query",n);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}case"ensure_store":{let t=typeof e?.name=="string"?e.name.trim():"";if(!t)return JSON.stringify({error:"name is required"});let n=typeof e?.type=="string"&&e.type.trim()?e.type.trim().toLowerCase():"sqlite",i=typeof e?.description=="string"?e.description.trim():"",s=await Dd({name:t,type:n,description:i,namespace:xi()});return s?.storeId&&($i[t]=s.storeId),JSON.stringify({...s,store:t})}case"sqlite_exec":case"sqlite_query":{let t=hr(e?.store);if(t.error)return JSON.stringify({error:t.error});if(typeof e?.sql!="string"||!e.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let n={sql:e.sql};Array.isArray(e?.params)&&(n.params=e.params);let i=await yr(t.storeId,"sql",n);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.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{SKILL_META as Bd}from"@zibby/skill-ids";import{existsSync as qi,readFileSync as Md}from"node:fs";import{homedir as Fd}from"node:os";import{join as Gd,dirname as Kd,resolve as Hd}from"node:path";import{fileURLToPath as zd}from"node:url";function Yd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Kd(zd(import.meta.url)),e=Hd(r,"..","bin","mcp-skill.mjs");return qi(e)?e:null}function Tt(){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 r=Gd(Fd(),".zibby","config.json");return qi(r)&&JSON.parse(Md(r,"utf-8")).sessionToken||null}catch{return null}}function Rt(){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 Wd(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Di(r){return`${Wd()}:artifact:${r}`}async function Ci(r){let e=Tt();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let t=await fetch(`${Rt()}/artifacts`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let n=await t.text().catch(()=>"");throw new Error(`artifact write failed (${t.status}): ${n.slice(0,300)}`)}return t.json()}async function Zd(r){let e=Tt();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let t=await fetch(`${Rt()}/artifacts/${encodeURIComponent(r)}`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let n=await t.text().catch(()=>"");throw new Error(`artifact get failed (${t.status}): ${n.slice(0,300)}`)}return t.json()}async function Ui(r,e){let t=Tt();if(!t)return;let n=await fetch(`${Rt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:"store",scope:Di(r),content:JSON.stringify(e)})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`artifact index write failed (${n.status}): ${i.slice(0,200)}`)}}async function Vd(r){let e=Tt();if(!e)return null;let t=await fetch(`${Rt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:"recall",scope:Di(r)})});if(!t.ok)return null;let n=await t.json().catch(()=>null);if(!n?.found||!n?.memory?.content)return null;try{return JSON.parse(n.memory.content)}catch{return null}}function Ji(r){return typeof r?.html=="string"&&r.html.length>0?{format:"html",content:r.html}:typeof r?.markdown=="string"&&r.markdown.length>0?{format:"markdown",content:r.markdown}:null}var Bi={id:"artifact",meta:Bd.artifact,serverName:"artifact",allowedTools:["mcp__artifact__*"],description:"Artifacts \u2014 publish a self-contained, shareable HTML/Markdown page to Zibby and get back a URL; the index of what you published is your memory.",promptFragment:`## Artifacts (publish a shareable page, remember what you made)
763
+ You can PUBLISH a standalone page \u2014 a status report, a plan, a comparison table,
764
+ a dashboard-y summary, a diagram, a "here's what I found" write-up \u2014 and get back
765
+ a shareable URL. The page is a self-contained HTML (or Markdown) document; it is
766
+ sandboxed when viewed (no external network, no ambient credentials), so keep all
767
+ CSS/JS/images INLINE (inline <style>/<script>, data: URIs) \u2014 external URLs will
768
+ be blocked.
769
+
770
+ Tools:
771
+ - artifact_publish: Publish a NEW page. Pass a \`title\` and EITHER \`html\` OR
772
+ \`markdown\` (not both). Optional \`kind\` (e.g. "report", "plan", "dashboard"),
773
+ \`favicon\` (an emoji), and \`summary\` (one line for your own index). Returns
774
+ { id, url }. Share the url; keep the id if you'll update it later.
775
+ - artifact_update: Revise an EXISTING page by \`id\` (same url, new version). Pass
776
+ the fields to change (\`title\`, \`html\`|\`markdown\`).
777
+ - artifact_get: Fetch one artifact by \`id\` \u2192 { metadata, content } so you can
778
+ reuse / edit / re-publish it.
779
+
780
+ To recall WHAT YOU HAVE ALREADY PUBLISHED, use your kv-memory tool
781
+ kv_recall_prefix with keyPrefix "artifact:" \u2014 each entry is the index record
782
+ { id, title, url, kind, createdAt, summary } for a page you made. (Publishing
783
+ records this automatically; you don't store it yourself.)`,resolve(){let r=Yd();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/artifact.js","artifactSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"artifact_publish":{let t=typeof e?.title=="string"?e.title.trim():"";if(!t)return JSON.stringify({error:"title is required"});let n=Ji(e);if(!n)return JSON.stringify({error:"provide exactly one of html or markdown (non-empty string)"});let i={title:t,[n.format]:n.content};typeof e?.kind=="string"&&e.kind.trim()&&(i.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(i.favicon=e.favicon.trim());let s=await Ci(i),o=s?.id,a=s?.url;if(!o||!a)return JSON.stringify({error:"artifact write returned no id/url",response:s});let c={id:o,title:t,url:a,kind:i.kind||null,createdAt:s.createdAt||new Date().toISOString(),summary:typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():t};try{await Ui(o,c)}catch(d){return JSON.stringify({id:o,url:a,indexWarning:d.message})}return JSON.stringify({id:o,url:a})}case"artifact_update":{let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let n=Ji(e),i=typeof e?.title=="string"?e.title.trim():"";if(!n&&!i)return JSON.stringify({error:"nothing to update \u2014 pass a new title and/or html|markdown"});let s={id:t};i&&(s.title=i),n&&(s[n.format]=n.content),typeof e?.kind=="string"&&e.kind.trim()&&(s.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(s.favicon=e.favicon.trim());let o=await Ci(s),a=o?.url;if(!a)return JSON.stringify({error:"artifact update returned no url",response:o});let c=await Vd(t)||{},d={...c,id:t,url:a,title:i||c.title||"Untitled",kind:s.kind||c.kind||null,createdAt:c.createdAt||o.createdAt||new Date().toISOString(),updatedAt:o.updatedAt||new Date().toISOString()};typeof e?.summary=="string"&&e.summary.trim()?d.summary=e.summary.trim():d.summary||(d.summary=d.title);try{await Ui(t,d)}catch(l){return JSON.stringify({id:t,url:a,indexWarning:l.message})}return JSON.stringify({id:t,url:a})}case"artifact_get":{let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let n=await Zd(t);return JSON.stringify(n)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"artifact_publish",description:"Publish a NEW self-contained, shareable page (report/plan/table/dashboard/diagram/write-up) and get back a shareable URL. Pass a title and EITHER html OR markdown. Keep all CSS/JS/images INLINE (inline <style>/<script>, data: URIs) \u2014 the page is sandboxed on view and external URLs are blocked. Returns { id, url }.",input_schema:{type:"object",properties:{title:{type:"string",description:"The page title (also the browser tab title)."},html:{type:"string",description:"The page content as a self-contained HTML document (or fragment). Provide this OR markdown, not both."},markdown:{type:"string",description:"The page content as Markdown (rendered to HTML on serve). Provide this OR html, not both."},kind:{type:"string",description:'Optional label for what this is, e.g. "report", "plan", "dashboard", "diagram". Stored in your index.'},favicon:{type:"string",description:'Optional emoji used as the browser-tab icon, e.g. "\u{1F4CA}".'},summary:{type:"string",description:"Optional one-line summary for your own index (defaults to the title). Helps you recall later what this page was."}},required:["title"]}},{name:"artifact_update",description:"Revise an EXISTING artifact by id \u2014 the shareable URL stays the same, the content is replaced (new version). Pass the fields to change (title and/or html|markdown). Returns { id, url }.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to update (from a prior artifact_publish, or your kv-memory "artifact:" index).'},title:{type:"string",description:"New title (optional)."},html:{type:"string",description:"New HTML content (optional). Provide this OR markdown."},markdown:{type:"string",description:"New Markdown content (optional). Provide this OR html."},kind:{type:"string",description:"Optional updated kind label."},favicon:{type:"string",description:"Optional updated emoji favicon."},summary:{type:"string",description:"Optional updated one-line index summary."}},required:["id"]}},{name:"artifact_get",description:'Fetch ONE artifact you published, by id \u2192 { metadata, content }. Use to reuse / edit / re-publish a page. To LIST what you have published, use your kv-memory tool kv_recall_prefix with keyPrefix "artifact:".',input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id."}},required:["id"]}}]};import{createRequire as Qd}from"node:module";import{existsSync as Ki,mkdirSync as Xd,writeFileSync as Mi}from"node:fs";import{dirname as Hi,join as Je,resolve as zi}from"node:path";import{fileURLToPath as Yi}from"node:url";var Wi=Qd(import.meta.url),gr=null;function ep(){return gr||(gr=Wi("echarts")),gr}var _r=null;function tp(){return _r||(_r=Wi("@resvg/resvg-js")),_r}var rp=800,np=600,ip=4096,sp=16,Fi=60,Zi="Noto Sans";function op(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Hi(Yi(import.meta.url)),e=zi(r,"..","bin","mcp-skill.mjs");return Ki(e)?e:null}function ap(){let r=Hi(Yi(import.meta.url)),e=zi(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>Je(e,t)).filter(t=>Ki(t))}function cp(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?Je(e,"chart-render"):Je(process.cwd(),".zibby","output","charts"));return Xd(t,{recursive:!0}),t}function Ne(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function Gi(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(sp,Math.min(ip,Math.round(t))):e}function br(r){return typeof r!="string"||r.length<=Fi?r:`${r.slice(0,Fi-1)}\u2026`}function At(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=br(t):Ne(t)&&typeof t.name=="string"&&(t.name=br(t.name))}}function lp(r){for(let n of["xAxis","yAxis"]){let i=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let s of i)Ne(s)&&At(s.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of e)Ne(n)&&At(n.indicator);Ne(r.legend)&&At(r.legend.data);let t=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of t)Ne(n)&&(typeof n.name=="string"&&(n.name=br(n.name)),At(n.data))}function dp(r){let e=JSON.parse(JSON.stringify(r));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),Ne(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=Zi),lp(e),e}function pp(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function up(r,e,t){let i=ep().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return i.setOption(r),i.renderToSVGString()}finally{i.dispose()}}function mp(r){let{Resvg:e}=tp();return new e(r,{font:{fontFiles:ap(),loadSystemFonts:!0,defaultFontFamily:Zi}}).render().asPng()}var Vi={id:"chart-render",serverName:"chart_render",allowedTools:["mcp__chart_render__*"],description:"Chart render \u2014 local server-side chart rendering (Apache ECharts SVG SSR + resvg PNG); data never leaves the box",promptFragment:`## Chart Render (local, no external service)
763
784
  You can render charts LOCALLY with the chart_render tool \u2014 pass a standard
764
785
  Apache ECharts option object as \`spec\` (any chart type: bar, line, pie,
765
786
  radar, scatter, heatmap, \u2026). It renders server-side to SVG/PNG files in the
766
787
  run's output folder (auto-attached to the run as artifacts) and returns the
767
788
  file paths. No browser, no external chart service \u2014 the data never leaves
768
- the machine. Don't set animation (it's forced off). Default 800\xD7600 PNG.`,resolve({sessionPath:r,nodeName:e}={}){let t=Bd();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?qe(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/chartRender.js","chartRenderSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="chart_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.spec;if(!Ne(t))return JSON.stringify({error:"spec must be a plain ECharts option OBJECT (e.g. { xAxis: {...}, yAxis: {...}, series: [...] }) \u2014 got "+(t===null?"null":Array.isArray(t)?"an array":typeof t)+". Pass the option object itself, not a string or an array."});let n=Ci(e?.width,Ud),i=Ci(e?.height,qd),s=["svg","png","both"].includes(e?.output)?e.output:"png",o=Hd(e?.filename)||`chart-${Date.now()}`,a;try{a=zd(Kd(t),n,i)}catch(l){return JSON.stringify({error:`Chart render failed: ${l.message}. The spec must be a valid Apache ECharts option (check series[].type, and that xAxis/yAxis/radar match the series type). Fix the spec and retry.`})}if(typeof a!="string"||!a.includes("<svg"))return JSON.stringify({error:"Chart render produced no SVG \u2014 the spec likely describes an empty chart (no series?). Add at least one series and retry."});let c=Fd(),d=[];if(s==="svg"||s==="both"){let l=qe(c,`${o}.svg`);$i(l,a,"utf-8"),d.push({path:l,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}if(s==="png"||s==="both"){let l;try{l=Wd(a)}catch(u){return JSON.stringify({error:`PNG rasterization failed: ${u.message}. Retry with output:'svg' if you only need the vector.`})}let p=qe(c,`${o}.png`);$i(p,l),d.push({path:p,format:"png",bytes:l.length})}return JSON.stringify({ok:!0,width:n,height:i,files:d})}catch(t){return JSON.stringify({error:`chart_render failed: ${t.message}`})}},tools:[{name:"chart_render",description:'Render a chart LOCALLY (no external service) from a standard Apache ECharts option and save it as SVG/PNG files in the run output folder. Pass the raw ECharts option as `spec` \u2014 every ECharts chart type works (bar, line, pie, radar, scatter, heatmap, \u2026). Returns the written file path(s). animation is forced off; background defaults to white. Bar example: {"xAxis":{"type":"category","data":["Q1","Q2"]},"yAxis":{},"series":[{"type":"bar","data":[12,30]}]}. Radar example: {"legend":{"data":["A","B"]},"radar":{"indicator":[{"name":"speed","max":10},{"name":"cost","max":10},{"name":"quality","max":10}]},"series":[{"type":"radar","data":[{"name":"A","value":[7,4,9]},{"name":"B","value":[5,8,6]}]}]}.',input_schema:{type:"object",properties:{spec:{type:"object",description:"The Apache ECharts option object, passed through as-is (series, xAxis/yAxis, radar, legend, title, \u2026)."},width:{type:"number",description:"Image width in px (default 800, max 4096)."},height:{type:"number",description:"Image height in px (default 600, max 4096)."},output:{type:"string",enum:["svg","png","both"],description:"Which file(s) to write (default 'png')."},filename:{type:"string",description:"Optional file basename (no extension); defaults to chart-<timestamp>."}},required:["spec"]}}]};import{createRequire as Yd}from"node:module";import{existsSync as zi,mkdirSync as Zd,writeFileSync as Gi}from"node:fs";import{dirname as Wi,join as De,resolve as Yi}from"node:path";import{fileURLToPath as Zi}from"node:url";var Vd=Yd(import.meta.url),_r=null;function Qd(){return _r||(_r=Vd("@resvg/resvg-js")),_r}var Vi=1200,Xd=627,ep=4096,tp=320,rp="#3b82f6",Oe="Noto Sans",np=3;function ip(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Wi(Zi(import.meta.url)),e=Yi(r,"..","bin","mcp-skill.mjs");return zi(e)?e:null}function sp(){let r=Wi(Zi(import.meta.url)),e=Yi(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>De(e,t)).filter(t=>zi(t))}function op(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?De(e,"social-card"):De(process.cwd(),".zibby","output","social-cards"));return Zd(t,{recursive:!0}),t}function Ki(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(tp,Math.min(ep,Math.round(t))):e}function Je(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function ap(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function cp(r,e){if(typeof r!="string")return e;let t=r.trim();return/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(t)?t:e}function Qi(r,e,t){return String(r).length*e*t}function br(r,e,t,n){let i=String(r).trim().split(/\s+/).filter(Boolean),s=[],o="";for(let a of i){let c=o?`${o} ${a}`:a;o&&Qi(c,t,n)>e?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function lp(r){return r==="light"?{bg:"#ffffff",fg:"#0b0f14",muted:"#5b6673",pillText:"#0b0f14",checkFg:"#ffffff",divider:"#e2e6ea"}:{bg:"#0b0f14",fg:"#e9edf1",muted:"#8b98a5",pillText:"#e9edf1",checkFg:"#0b0f14",divider:"#22303c"}}function Hi(r,e,t,n,i){let s=(Array.isArray(r)?r:[]).map(y=>String(y??"").trim()).filter(Boolean).slice(0,np);if(s.length<2)return null;let o=24,a=54,c=26,d=90,l=17,p=s.map(y=>Math.max(96,Qi(y,o,.58)+c*2)),u=p.reduce((y,_)=>y+_,0)+d*(s.length-1),m=e-u/2,f=t+a/2,h=[];for(let y=0;y<s.length;y++){let _=p[y];if(h.push(`<rect x="${m.toFixed(1)}" y="${t}" width="${_.toFixed(1)}" height="${a}" rx="${a/2}" fill="${i}" fill-opacity="0.12" stroke="${i}" stroke-opacity="0.55" stroke-width="1.5"/>`,`<text x="${(m+_/2).toFixed(1)}" y="${(f+o*.35).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${o}" font-weight="700" fill="${n.pillText}">${Je(s[y])}</text>`),m+=_,y<s.length-1){let b=m,g=m+d,k=(b+g)/2;h.push(`<line x1="${b.toFixed(1)}" y1="${f}" x2="${g.toFixed(1)}" y2="${f}" stroke="${i}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${k.toFixed(1)}" cy="${f}" r="${l}" fill="${i}"/>`,`<path d="M ${(k-8).toFixed(1)} ${f.toFixed(1)} l 5 5 l 9 -11" fill="none" stroke="${n.checkFg}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`),m=g}}return{svg:h.join(`
769
- `),height:a}}function dp(r){let{width:e,height:t,theme:n,accent:i}=r,s=lp(n),o=e/2,a=Math.round(e*.07),c=e-a*2,d=String(r.headline).trim(),l=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",p=r.subhead?String(r.subhead).trim():"",u=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=e/Vi,h=Math.round(22*f),y=Math.round(29*f),_=p?br(p,c,y,.52):[],b=Math.round(y*1.28),g=4,k=Math.round(26*f),R=Math.round(20*f),K=Math.round(24*f),Te=Math.round(30*f),T=!!(u||m),O=a,D=T?Math.round(110*f):a,x=t-O-D,ye=Hi(r.diagram,o,0,s,i),$r=(L,de)=>{let Me=g+k;return l&&(Me+=h+R),Me+=de.length*Math.round(L*1.16),_.length&&(Me+=K+_.length*b),ye&&(Me+=Te+ye.height),Me},Ut=[76,66,58,50,44,38].map(L=>Math.round(L*f)),Ps=4,Ae=Ut[Ut.length-1],qt=br(d,c,Ae,.6);for(let L of Ut){let de=br(d,c,L,.6);if(de.length<=Ps&&$r(L,de)<=x){Ae=L,qt=de;break}}let Cs=Math.round(Ae*1.16),Us=$r(Ae,qt),H=O+Math.max(0,(x-Us)/2),se=[];se.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${s.bg}"/>`);let Pr=Math.round(60*f);se.push(`<rect x="${(o-Pr/2).toFixed(1)}" y="${H}" width="${Pr}" height="${g}" rx="2" fill="${i}"/>`),H+=g+k,l&&(se.push(`<text x="${o}" y="${(H+h*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${i}">${Je(l)}</text>`),H+=h+R);for(let L of qt)se.push(`<text x="${o}" y="${(H+Ae*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${Ae}" font-weight="700" fill="${s.fg}">${Je(L)}</text>`),H+=Cs;if(_.length){H+=K;for(let L of _)se.push(`<text x="${o}" y="${(H+y*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${y}" font-weight="400" fill="${s.muted}">${Je(L)}</text>`),H+=b}if(ye){H+=Te;let L=Hi(r.diagram,o,H,s,i);L&&se.push(L.svg)}if(T){let L=Math.round(24*f),de=t-Math.round(46*f);m&&se.push(`<text x="${a}" y="${de}" text-anchor="start" font-family="${Oe}" font-size="${L}" font-weight="400" fill="${s.muted}">${Je(m)}</text>`),u&&se.push(`<text x="${e-a}" y="${de}" text-anchor="end" font-family="${Oe}" font-size="${L}" font-weight="700" fill="${i}">${Je(u)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
789
+ the machine. Don't set animation (it's forced off). Default 800\xD7600 PNG.`,resolve({sessionPath:r,nodeName:e}={}){let t=op();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?Je(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/chartRender.js","chartRenderSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="chart_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.spec;if(!Ne(t))return JSON.stringify({error:"spec must be a plain ECharts option OBJECT (e.g. { xAxis: {...}, yAxis: {...}, series: [...] }) \u2014 got "+(t===null?"null":Array.isArray(t)?"an array":typeof t)+". Pass the option object itself, not a string or an array."});let n=Gi(e?.width,rp),i=Gi(e?.height,np),s=["svg","png","both"].includes(e?.output)?e.output:"png",o=pp(e?.filename)||`chart-${Date.now()}`,a;try{a=up(dp(t),n,i)}catch(l){return JSON.stringify({error:`Chart render failed: ${l.message}. The spec must be a valid Apache ECharts option (check series[].type, and that xAxis/yAxis/radar match the series type). Fix the spec and retry.`})}if(typeof a!="string"||!a.includes("<svg"))return JSON.stringify({error:"Chart render produced no SVG \u2014 the spec likely describes an empty chart (no series?). Add at least one series and retry."});let c=cp(),d=[];if(s==="svg"||s==="both"){let l=Je(c,`${o}.svg`);Mi(l,a,"utf-8"),d.push({path:l,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}if(s==="png"||s==="both"){let l;try{l=mp(a)}catch(u){return JSON.stringify({error:`PNG rasterization failed: ${u.message}. Retry with output:'svg' if you only need the vector.`})}let p=Je(c,`${o}.png`);Mi(p,l),d.push({path:p,format:"png",bytes:l.length})}return JSON.stringify({ok:!0,width:n,height:i,files:d})}catch(t){return JSON.stringify({error:`chart_render failed: ${t.message}`})}},tools:[{name:"chart_render",description:'Render a chart LOCALLY (no external service) from a standard Apache ECharts option and save it as SVG/PNG files in the run output folder. Pass the raw ECharts option as `spec` \u2014 every ECharts chart type works (bar, line, pie, radar, scatter, heatmap, \u2026). Returns the written file path(s). animation is forced off; background defaults to white. Bar example: {"xAxis":{"type":"category","data":["Q1","Q2"]},"yAxis":{},"series":[{"type":"bar","data":[12,30]}]}. Radar example: {"legend":{"data":["A","B"]},"radar":{"indicator":[{"name":"speed","max":10},{"name":"cost","max":10},{"name":"quality","max":10}]},"series":[{"type":"radar","data":[{"name":"A","value":[7,4,9]},{"name":"B","value":[5,8,6]}]}]}.',input_schema:{type:"object",properties:{spec:{type:"object",description:"The Apache ECharts option object, passed through as-is (series, xAxis/yAxis, radar, legend, title, \u2026)."},width:{type:"number",description:"Image width in px (default 800, max 4096)."},height:{type:"number",description:"Image height in px (default 600, max 4096)."},output:{type:"string",enum:["svg","png","both"],description:"Which file(s) to write (default 'png')."},filename:{type:"string",description:"Optional file basename (no extension); defaults to chart-<timestamp>."}},required:["spec"]}}]};import{createRequire as fp}from"node:module";import{existsSync as ts,mkdirSync as hp,writeFileSync as Qi}from"node:fs";import{dirname as rs,join as De,resolve as ns}from"node:path";import{fileURLToPath as is}from"node:url";var yp=fp(import.meta.url),kr=null;function gp(){return kr||(kr=yp("@resvg/resvg-js")),kr}var ss=1200,_p=627,bp=4096,kp=320,wp="#3b82f6",Oe="Noto Sans",Sp=3;function vp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=rs(is(import.meta.url)),e=ns(r,"..","bin","mcp-skill.mjs");return ts(e)?e:null}function Ip(){let r=rs(is(import.meta.url)),e=ns(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>De(e,t)).filter(t=>ts(t))}function Np(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?De(e,"social-card"):De(process.cwd(),".zibby","output","social-cards"));return hp(t,{recursive:!0}),t}function Xi(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(kp,Math.min(bp,Math.round(t))):e}function qe(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Op(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Tp(r,e){if(typeof r!="string")return e;let t=r.trim();return/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(t)?t:e}function os(r,e,t){return String(r).length*e*t}function wr(r,e,t,n){let i=String(r).trim().split(/\s+/).filter(Boolean),s=[],o="";for(let a of i){let c=o?`${o} ${a}`:a;o&&os(c,t,n)>e?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function Rp(r){return r==="light"?{bg:"#ffffff",fg:"#0b0f14",muted:"#5b6673",pillText:"#0b0f14",checkFg:"#ffffff",divider:"#e2e6ea"}:{bg:"#0b0f14",fg:"#e9edf1",muted:"#8b98a5",pillText:"#e9edf1",checkFg:"#0b0f14",divider:"#22303c"}}function es(r,e,t,n,i){let s=(Array.isArray(r)?r:[]).map(g=>String(g??"").trim()).filter(Boolean).slice(0,Sp);if(s.length<2)return null;let o=24,a=54,c=26,d=90,l=17,p=s.map(g=>Math.max(96,os(g,o,.58)+c*2)),u=p.reduce((g,_)=>g+_,0)+d*(s.length-1),m=e-u/2,f=t+a/2,h=[];for(let g=0;g<s.length;g++){let _=p[g];if(h.push(`<rect x="${m.toFixed(1)}" y="${t}" width="${_.toFixed(1)}" height="${a}" rx="${a/2}" fill="${i}" fill-opacity="0.12" stroke="${i}" stroke-opacity="0.55" stroke-width="1.5"/>`,`<text x="${(m+_/2).toFixed(1)}" y="${(f+o*.35).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${o}" font-weight="700" fill="${n.pillText}">${qe(s[g])}</text>`),m+=_,g<s.length-1){let b=m,y=m+d,k=(b+y)/2;h.push(`<line x1="${b.toFixed(1)}" y1="${f}" x2="${y.toFixed(1)}" y2="${f}" stroke="${i}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${k.toFixed(1)}" cy="${f}" r="${l}" fill="${i}"/>`,`<path d="M ${(k-8).toFixed(1)} ${f.toFixed(1)} l 5 5 l 9 -11" fill="none" stroke="${n.checkFg}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`),m=y}}return{svg:h.join(`
790
+ `),height:a}}function Ap(r){let{width:e,height:t,theme:n,accent:i}=r,s=Rp(n),o=e/2,a=Math.round(e*.07),c=e-a*2,d=String(r.headline).trim(),l=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",p=r.subhead?String(r.subhead).trim():"",u=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=e/ss,h=Math.round(22*f),g=Math.round(29*f),_=p?wr(p,c,g,.52):[],b=Math.round(g*1.28),y=4,k=Math.round(26*f),T=Math.round(20*f),K=Math.round(24*f),Re=Math.round(30*f),R=!!(u||m),O=a,D=R?Math.round(110*f):a,x=t-O-D,ge=es(r.diagram,o,0,s,i),Cr=(L,de)=>{let Me=y+k;return l&&(Me+=h+T),Me+=de.length*Math.round(L*1.16),_.length&&(Me+=K+_.length*b),ge&&(Me+=Re+ge.height),Me},qt=[76,66,58,50,44,38].map(L=>Math.round(L*f)),Fs=4,Ae=qt[qt.length-1],Dt=wr(d,c,Ae,.6);for(let L of qt){let de=wr(d,c,L,.6);if(de.length<=Fs&&Cr(L,de)<=x){Ae=L,Dt=de;break}}let Gs=Math.round(Ae*1.16),Ks=Cr(Ae,Dt),H=O+Math.max(0,(x-Ks)/2),se=[];se.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${s.bg}"/>`);let Ur=Math.round(60*f);se.push(`<rect x="${(o-Ur/2).toFixed(1)}" y="${H}" width="${Ur}" height="${y}" rx="2" fill="${i}"/>`),H+=y+k,l&&(se.push(`<text x="${o}" y="${(H+h*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${i}">${qe(l)}</text>`),H+=h+T);for(let L of Dt)se.push(`<text x="${o}" y="${(H+Ae*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${Ae}" font-weight="700" fill="${s.fg}">${qe(L)}</text>`),H+=Gs;if(_.length){H+=K;for(let L of _)se.push(`<text x="${o}" y="${(H+g*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${g}" font-weight="400" fill="${s.muted}">${qe(L)}</text>`),H+=b}if(ge){H+=Re;let L=es(r.diagram,o,H,s,i);L&&se.push(L.svg)}if(R){let L=Math.round(24*f),de=t-Math.round(46*f);m&&se.push(`<text x="${a}" y="${de}" text-anchor="start" font-family="${Oe}" font-size="${L}" font-weight="400" fill="${s.muted}">${qe(m)}</text>`),u&&se.push(`<text x="${e-a}" y="${de}" text-anchor="end" font-family="${Oe}" font-size="${L}" font-weight="700" fill="${i}">${qe(u)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
770
791
  ${se.join(`
771
792
  `)}
772
- </svg>`}function pp(r){let{Resvg:e}=Qd();return new e(r,{font:{fontFiles:sp(),loadSystemFonts:!0,defaultFontFamily:Oe}}).render().asPng()}var Xi={id:"social-card",serverName:"social_card",allowedTools:["mcp__social_card__*"],description:'Social card \u2014 render a branded LinkedIn "concept card" PNG locally (bold headline + eyebrow + optional stat/footer/diagram); nothing leaves the box',promptFragment:`## Social Card (branded concept card, local)
793
+ </svg>`}function xp(r){let{Resvg:e}=gp();return new e(r,{font:{fontFiles:Ip(),loadSystemFonts:!0,defaultFontFamily:Oe}}).render().asPng()}var as={id:"social-card",serverName:"social_card",allowedTools:["mcp__social_card__*"],description:'Social card \u2014 render a branded LinkedIn "concept card" PNG locally (bold headline + eyebrow + optional stat/footer/diagram); nothing leaves the box',promptFragment:`## Social Card (branded concept card, local)
773
794
  You can render a BRANDED concept card PNG with the social_card_render tool \u2014 the
774
795
  clean, high-signal LinkedIn "concept card" style (bold headline + small uppercase
775
796
  eyebrow + optional stat/footer + optional A\u2014\u2713\u2014B diagram). Give it STRUCTURED
@@ -783,15 +804,15 @@ fields that capture the ONE key idea of your post:
783
804
  It renders server-side to a PNG in the run's output folder and returns
784
805
  { ok:true, files:[{ path, format:'png', bytes }] }. Pass the returned \`path\` as
785
806
  \`imagePath\` when you draft/publish a LinkedIn post to ATTACH the card as the
786
- post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=ip();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?De(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/socialCard.js","socialCardSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="social_card_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.headline;if(typeof t!="string"||!t.trim())return JSON.stringify({error:"headline (the big bold line) is required and must be a non-empty string."});let n=Ki(e?.width,Vi),i=Ki(e?.height,Xd),s=e?.theme==="light"?"light":"dark",o=cp(e?.accent,rp),a;try{a=dp({width:n,height:i,theme:s,accent:o,headline:t,eyebrow:e?.eyebrow,subhead:e?.subhead,stat:e?.stat,footer:e?.footer,diagram:e?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=pp(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=op(),l=ap(e?.filename)||`social-card-${Date.now()}`,p=De(d,`${l}.png`);Gi(p,c);let u=[{path:p,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=De(d,`${l}.svg`);Gi(m,a,"utf-8"),u.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:i,theme:s,files:u})}catch(t){return JSON.stringify({error:`social_card_render failed: ${t.message}`})}},tools:[{name:"social_card_render",description:'Render a BRANDED "concept card" PNG LOCALLY (no external service) from structured fields \u2014 the clean LinkedIn concept-card style: bold headline + small uppercase eyebrow + optional supporting subhead, stat, footer, and an A\u2014\u2713\u2014B diagram. Returns { ok:true, files:[{ path, format:"png", bytes }] }. Pass the returned `path` as `imagePath` to a LinkedIn post tool to attach it as the post image. Example: { "headline":"No more copy-paste between AI tools", "eyebrow":"MY WORKFLOW", "stat":"11.8k stars", "footer":"Apache 2.0", "diagram":["Claude Code","Codex"] }.',input_schema:{type:"object",properties:{headline:{type:"string",description:"REQUIRED. The big, bold line \u2014 the single key idea/takeaway. Word-wrapped + auto-sized."},eyebrow:{type:"string",description:'Small uppercase kicker above the headline (e.g. "MY WORKFLOW", "OPEN SOURCE"). Rendered uppercased in the accent color.'},subhead:{type:"string",description:"One supporting line under the headline (muted)."},stat:{type:"string",description:'Optional stat, shown bottom-right in the accent color (e.g. "11.8k stars", "3x faster").'},footer:{type:"string",description:'Optional footer, shown bottom-left (muted) (e.g. "Apache 2.0", a repo name).'},diagram:{type:"array",items:{type:"string"},description:'Optional 2-3 short labels rendered as a chain of pills joined by a checkmark (A \u2014\u2713\u2014 B), e.g. ["Claude Code","Codex"].'},theme:{type:"string",enum:["dark","light"],description:"Card theme (default 'dark' \u2014 near-black bg, off-white text)."},accent:{type:"string",description:'Accent hex color (e.g. "#f97316"). Defaults to a tasteful blue (#3b82f6).'},width:{type:"number",description:"Image width in px (default 1200 \u2014 LinkedIn 1.91:1 link image)."},height:{type:"number",description:"Image height in px (default 627)."},filename:{type:"string",description:"Optional file basename (no extension); defaults to social-card-<timestamp>."},output:{type:"string",enum:["png","both"],description:"Which file(s) to write (default 'png'; 'both' also writes the .svg)."}},required:["headline"]}}]};import{spawnSync as up}from"node:child_process";import{existsSync as J,readdirSync as rs,statSync as ns,writeFileSync as wr,mkdirSync as Sr}from"node:fs";import{dirname as kr,extname as Et,join as $,relative as mp,resolve as xt}from"node:path";import{tmpdir as Ir}from"node:os";import{fileURLToPath as fp}from"node:url";import{SKILL_META as hp}from"@zibby/skill-ids";import{binPath as gp}from"@zibby/bin-oxlint";import{binPath as yp}from"@zibby/bin-semgrep";function _p(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=gp();if(r&&J(r))return r}catch{}return"oxlint"}function bp(){if(process.env.SEMGREP_CORE_BIN)return process.env.SEMGREP_CORE_BIN;try{let r=yp();if(r&&J(r))return r}catch{}return"semgrep-core"}function kp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=kr(fp(import.meta.url)),e=xt(r,"..","bin","mcp-skill.mjs");return J(e)?e:null}var is=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),wp=400,Sp={plugins:["react","typescript","unicorn","oxc"],categories:{correctness:"error",suspicious:"warn"},rules:{"react/react-in-jsx-scope":"off","react/jsx-max-depth":"off","react/no-array-index-key":"off","react/jsx-key":"error","react/no-unknown-property":"error","no-unused-vars":"warn",eqeqeq:"warn"}},Ip=[".oxlintrc.json",".oxlintrc","oxlint.json"],Tt=null;function vp(){if(Tt&&J(Tt))return Tt;try{let r=$(Ir(),"zibby-code-scan");Sr(r,{recursive:!0});let e=$(r,"oxlintrc.curated.json");return wr(e,JSON.stringify(Sp),"utf-8"),Tt=e,e}catch{return null}}var ss={".java":"java",".py":"python",".go":"go",".rb":"ruby",".php":"php"},es=Object.keys(ss),os={rules:[{id:"zibby-java-command-injection",languages:["java"],severity:"ERROR",message:"Command execution (Runtime.exec / ProcessBuilder) \u2014 command injection risk if the argument is attacker-influenced. Validate/allow-list the input or avoid a shell.",patterns:[{"pattern-either":[{pattern:"Runtime.getRuntime().exec(...)"},{pattern:"new ProcessBuilder(...)"}]}]},{id:"zibby-python-subprocess-shell",languages:["python"],severity:"ERROR",message:"subprocess call with shell=True \u2014 command injection risk. Pass an argv list and shell=False.",pattern:"subprocess.$F(..., shell=True, ...)"},{id:"zibby-python-yaml-load",languages:["python"],severity:"WARNING",message:"yaml.load without a safe loader can instantiate arbitrary Python objects. Use yaml.safe_load.",pattern:"yaml.load(...)"},{id:"zibby-go-command-injection",languages:["go"],severity:"WARNING",message:"os/exec with a non-constant command \u2014 verify the value is not attacker-controlled (command injection).",pattern:"exec.Command($CMD, ...)"},{id:"zibby-ruby-command-injection",languages:["ruby"],severity:"ERROR",message:"Shell/eval execution (system / eval) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...)"},{pattern:"eval(...)"}]}]},{id:"zibby-php-command-injection",languages:["php"],severity:"ERROR",message:"Shell/eval execution (system / exec / shell_exec) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...);"},{pattern:"exec(...);"},{pattern:"shell_exec(...);"}]}]}]},Np=[".semgrep.yml",".semgrep.yaml","semgrep.yml","semgrep.yaml"],At=null;function Op(){if(At&&J(At))return At;try{let r=$(Ir(),"zibby-code-scan");Sr(r,{recursive:!0});let e=$(r,"semgrep.curated.rules.json");return wr(e,JSON.stringify(os),"utf-8"),At=e,e}catch{return null}}function Rp(r){return Np.map(t=>$(r,t)).find(t=>J(t))||Op()}function Tp(r){let e=[];for(let t of Array.isArray(r)?r:[]){if(typeof t!="string"||!t)continue;let n=ss[Et(t).toLowerCase()];if(!n)continue;let i=t.replace(/\\/g,"/");e.push(["CodeTarget",{path:{fpath:i,ppath:`/${i.replace(/^\/+/,"")}`},analyzer:n,products:["sast"]}])}return["Targets",e]}var Ap=0;function xp(r){let e=Tp(r),t=e[1].length,n=$(Ir(),"zibby-code-scan");Sr(n,{recursive:!0});let i=$(n,`semgrep.targets.${process.pid}.${Ap++}.json`);return wr(i,JSON.stringify(e),"utf-8"),{path:i,count:t}}function ts(r){let e=typeof r=="string"?r.toUpperCase():"";return e==="ERROR"?"error":e==="INFO"||e==="INVENTORY"||e==="EXPERIMENT"?"info":"warning"}var Ep=Object.fromEntries(os.rules.map(r=>[r.id,r.severity]));function jp(r,e){if(e)return ts(e);let t=Ep[r];return t?ts(t):"warning"}function Lp(r){let e=String(r||""),t=e.indexOf("{");if(t<0)return[];let n;try{n=JSON.parse(e.slice(t))}catch{return[]}return(n&&Array.isArray(n.results)?n.results:[]).map(s=>{if(!s||typeof s!="object")return null;let o=s.start&&typeof s.start=="object"?s.start:{},a=s.extra&&typeof s.extra=="object"?s.extra:{};return{file:s.path||"",line:Number.isFinite(o.line)?o.line:"",severity:jp(s.check_id,a.severity),rule:s.check_id||"",message:(a.message||"").trim()}}).filter(s=>s&&(s.file||s.message))}function $p(r,e,t=4e3){let n=new Set(e.map(o=>o.toLowerCase())),i=[r],s=0;for(;i.length;){let o=i.pop(),a;try{a=rs(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(++s>t)return!1;if(c.isDirectory())!is.has(c.name)&&!c.name.startsWith(".")&&i.push($(o,c.name));else if(c.isFile()&&n.has(Et(c.name).toLowerCase()))return!0}}return!1}function Pp(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return(Array.isArray(t)?t:t&&Array.isArray(t.diagnostics)?t.diagnostics:[]).map(i=>{if(!i||typeof i!="object")return null;let s=Array.isArray(i.labels)&&i.labels.length?i.labels[0]:null,o=s&&s.span?s.span:null;return{file:i.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:i.severity||"warning",rule:i.code||"",message:i.message||""}}).filter(i=>i&&(i.file||i.message))}function Cp(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.map(n=>n&&typeof n=="object"?{file:n.filename||"",line:n.location&&Number.isFinite(n.location.row)?n.location.row:"",severity:"warning",rule:n.code||"",message:n.message||""}:null).filter(n=>n&&(n.file||n.message)):[]}function Up(r){let e=String(r||"").trim();if(!e)return[];let t=[];for(let n of e.split(`
787
- `)){let i=n.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{continue}if(!s||typeof s!="object")continue;let o=s.location||{};t.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""})}return t.filter(n=>n.file||n.message)}var qp=[{id:"oxlint",detect:r=>J($(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>_p(),args:(r,e={})=>{let t=e.baseDir||".",i=Ip.some(o=>J($(t,o)))?null:vp();return["--format","json",...i?["--config",i]:[],...r]},parse:Pp},{id:"semgrep",detect:r=>$p(r,es),langs:es,bin:()=>bp(),args:(r,e={})=>{let t=e.baseDir||".",n=Rp(t),{path:i}=xp(r);return[...n?["-rules",n]:[],"-targets",i,"-json"]},parse:Lp},{id:"ruff",detect:r=>J($(r,"pyproject.toml"))||J($(r,"requirements.txt"))||J($(r,"setup.py")),langs:[".py"],bin:()=>process.env.RUFF_BIN||"ruff",args:r=>["check","--output-format","json",...r],parse:Cp},{id:"staticcheck",detect:r=>J($(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:Up}];function Jp(r,e,t){let n=[],i=new Set(e.map(o=>o.toLowerCase())),s=[r];for(;s.length&&n.length<t;){let o=s.pop(),a;try{a=rs(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(n.length>=t)break;c.isDirectory()?!is.has(c.name)&&!c.name.startsWith(".")&&s.push($(o,c.name)):c.isFile()&&i.has(Et(c.name).toLowerCase())&&n.push($(o,c.name))}}return n}function Dp(r,e,t){let n=t.map(a=>mp(e,a)).filter(Boolean);if(!n.length)return{scanner:r.id,skipped:"no matching files"};let i=r.bin(),s=up(i,r.args(n,{baseDir:e}),{cwd:e,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(s.error){let a=s.error.code==="ENOENT"?`binary not installed (${i})`:String(s.error.message||s.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(s.stdout,s.stderr,s.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:n.length,findings:o}}var as={id:"code-scan",serverName:"code_scan",meta:hp["code-scan"],allowedTools:["mcp__code_scan__*"],description:"Code scan \u2014 run the RIGHT deterministic linter/analyzer for a checked-out repo (auto-detects the stack: JS/TS\u2192oxlint; Java/Python/Go/Ruby/PHP\u2192semgrep) and return structured findings. Fully local; the code never leaves the box.",promptFragment:`## Code Scan (deterministic linter, auto-detects the stack)
807
+ post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=vp();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?De(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/socialCard.js","socialCardSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="social_card_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.headline;if(typeof t!="string"||!t.trim())return JSON.stringify({error:"headline (the big bold line) is required and must be a non-empty string."});let n=Xi(e?.width,ss),i=Xi(e?.height,_p),s=e?.theme==="light"?"light":"dark",o=Tp(e?.accent,wp),a;try{a=Ap({width:n,height:i,theme:s,accent:o,headline:t,eyebrow:e?.eyebrow,subhead:e?.subhead,stat:e?.stat,footer:e?.footer,diagram:e?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=xp(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=Np(),l=Op(e?.filename)||`social-card-${Date.now()}`,p=De(d,`${l}.png`);Qi(p,c);let u=[{path:p,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=De(d,`${l}.svg`);Qi(m,a,"utf-8"),u.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:i,theme:s,files:u})}catch(t){return JSON.stringify({error:`social_card_render failed: ${t.message}`})}},tools:[{name:"social_card_render",description:'Render a BRANDED "concept card" PNG LOCALLY (no external service) from structured fields \u2014 the clean LinkedIn concept-card style: bold headline + small uppercase eyebrow + optional supporting subhead, stat, footer, and an A\u2014\u2713\u2014B diagram. Returns { ok:true, files:[{ path, format:"png", bytes }] }. Pass the returned `path` as `imagePath` to a LinkedIn post tool to attach it as the post image. Example: { "headline":"No more copy-paste between AI tools", "eyebrow":"MY WORKFLOW", "stat":"11.8k stars", "footer":"Apache 2.0", "diagram":["Claude Code","Codex"] }.',input_schema:{type:"object",properties:{headline:{type:"string",description:"REQUIRED. The big, bold line \u2014 the single key idea/takeaway. Word-wrapped + auto-sized."},eyebrow:{type:"string",description:'Small uppercase kicker above the headline (e.g. "MY WORKFLOW", "OPEN SOURCE"). Rendered uppercased in the accent color.'},subhead:{type:"string",description:"One supporting line under the headline (muted)."},stat:{type:"string",description:'Optional stat, shown bottom-right in the accent color (e.g. "11.8k stars", "3x faster").'},footer:{type:"string",description:'Optional footer, shown bottom-left (muted) (e.g. "Apache 2.0", a repo name).'},diagram:{type:"array",items:{type:"string"},description:'Optional 2-3 short labels rendered as a chain of pills joined by a checkmark (A \u2014\u2713\u2014 B), e.g. ["Claude Code","Codex"].'},theme:{type:"string",enum:["dark","light"],description:"Card theme (default 'dark' \u2014 near-black bg, off-white text)."},accent:{type:"string",description:'Accent hex color (e.g. "#f97316"). Defaults to a tasteful blue (#3b82f6).'},width:{type:"number",description:"Image width in px (default 1200 \u2014 LinkedIn 1.91:1 link image)."},height:{type:"number",description:"Image height in px (default 627)."},filename:{type:"string",description:"Optional file basename (no extension); defaults to social-card-<timestamp>."},output:{type:"string",enum:["png","both"],description:"Which file(s) to write (default 'png'; 'both' also writes the .svg)."}},required:["headline"]}}]};import{spawnSync as Ep}from"node:child_process";import{existsSync as q,readdirSync as ds,statSync as ps,writeFileSync as vr,mkdirSync as Ir}from"node:fs";import{dirname as Sr,extname as Lt,join as $,relative as jp,resolve as jt}from"node:path";import{tmpdir as Nr}from"node:os";import{fileURLToPath as Lp}from"node:url";import{SKILL_META as $p}from"@zibby/skill-ids";import{binPath as Pp}from"@zibby/bin-oxlint";import{binPath as Cp}from"@zibby/bin-semgrep";function Up(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=Pp();if(r&&q(r))return r}catch{}return"oxlint"}function Jp(){if(process.env.SEMGREP_CORE_BIN)return process.env.SEMGREP_CORE_BIN;try{let r=Cp();if(r&&q(r))return r}catch{}return"semgrep-core"}function qp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Sr(Lp(import.meta.url)),e=jt(r,"..","bin","mcp-skill.mjs");return q(e)?e:null}var us=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),Dp=400,Bp={plugins:["react","typescript","unicorn","oxc"],categories:{correctness:"error",suspicious:"warn"},rules:{"react/react-in-jsx-scope":"off","react/jsx-max-depth":"off","react/no-array-index-key":"off","react/jsx-key":"error","react/no-unknown-property":"error","no-unused-vars":"warn",eqeqeq:"warn"}},Mp=[".oxlintrc.json",".oxlintrc","oxlint.json"],xt=null;function Fp(){if(xt&&q(xt))return xt;try{let r=$(Nr(),"zibby-code-scan");Ir(r,{recursive:!0});let e=$(r,"oxlintrc.curated.json");return vr(e,JSON.stringify(Bp),"utf-8"),xt=e,e}catch{return null}}var ms={".java":"java",".py":"python",".go":"go",".rb":"ruby",".php":"php"},cs=Object.keys(ms),fs={rules:[{id:"zibby-java-command-injection",languages:["java"],severity:"ERROR",message:"Command execution (Runtime.exec / ProcessBuilder) \u2014 command injection risk if the argument is attacker-influenced. Validate/allow-list the input or avoid a shell.",patterns:[{"pattern-either":[{pattern:"Runtime.getRuntime().exec(...)"},{pattern:"new ProcessBuilder(...)"}]}]},{id:"zibby-python-subprocess-shell",languages:["python"],severity:"ERROR",message:"subprocess call with shell=True \u2014 command injection risk. Pass an argv list and shell=False.",pattern:"subprocess.$F(..., shell=True, ...)"},{id:"zibby-python-yaml-load",languages:["python"],severity:"WARNING",message:"yaml.load without a safe loader can instantiate arbitrary Python objects. Use yaml.safe_load.",pattern:"yaml.load(...)"},{id:"zibby-go-command-injection",languages:["go"],severity:"WARNING",message:"os/exec with a non-constant command \u2014 verify the value is not attacker-controlled (command injection).",pattern:"exec.Command($CMD, ...)"},{id:"zibby-ruby-command-injection",languages:["ruby"],severity:"ERROR",message:"Shell/eval execution (system / eval) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...)"},{pattern:"eval(...)"}]}]},{id:"zibby-php-command-injection",languages:["php"],severity:"ERROR",message:"Shell/eval execution (system / exec / shell_exec) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...);"},{pattern:"exec(...);"},{pattern:"shell_exec(...);"}]}]}]},Gp=[".semgrep.yml",".semgrep.yaml","semgrep.yml","semgrep.yaml"],Et=null;function Kp(){if(Et&&q(Et))return Et;try{let r=$(Nr(),"zibby-code-scan");Ir(r,{recursive:!0});let e=$(r,"semgrep.curated.rules.json");return vr(e,JSON.stringify(fs),"utf-8"),Et=e,e}catch{return null}}function Hp(r){return Gp.map(t=>$(r,t)).find(t=>q(t))||Kp()}function zp(r){let e=[];for(let t of Array.isArray(r)?r:[]){if(typeof t!="string"||!t)continue;let n=ms[Lt(t).toLowerCase()];if(!n)continue;let i=t.replace(/\\/g,"/");e.push(["CodeTarget",{path:{fpath:i,ppath:`/${i.replace(/^\/+/,"")}`},analyzer:n,products:["sast"]}])}return["Targets",e]}var Yp=0;function Wp(r){let e=zp(r),t=e[1].length,n=$(Nr(),"zibby-code-scan");Ir(n,{recursive:!0});let i=$(n,`semgrep.targets.${process.pid}.${Yp++}.json`);return vr(i,JSON.stringify(e),"utf-8"),{path:i,count:t}}function ls(r){let e=typeof r=="string"?r.toUpperCase():"";return e==="ERROR"?"error":e==="INFO"||e==="INVENTORY"||e==="EXPERIMENT"?"info":"warning"}var Zp=Object.fromEntries(fs.rules.map(r=>[r.id,r.severity]));function Vp(r,e){if(e)return ls(e);let t=Zp[r];return t?ls(t):"warning"}function Qp(r){let e=String(r||""),t=e.indexOf("{");if(t<0)return[];let n;try{n=JSON.parse(e.slice(t))}catch{return[]}return(n&&Array.isArray(n.results)?n.results:[]).map(s=>{if(!s||typeof s!="object")return null;let o=s.start&&typeof s.start=="object"?s.start:{},a=s.extra&&typeof s.extra=="object"?s.extra:{};return{file:s.path||"",line:Number.isFinite(o.line)?o.line:"",severity:Vp(s.check_id,a.severity),rule:s.check_id||"",message:(a.message||"").trim()}}).filter(s=>s&&(s.file||s.message))}function Xp(r,e,t=4e3){let n=new Set(e.map(o=>o.toLowerCase())),i=[r],s=0;for(;i.length;){let o=i.pop(),a;try{a=ds(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(++s>t)return!1;if(c.isDirectory())!us.has(c.name)&&!c.name.startsWith(".")&&i.push($(o,c.name));else if(c.isFile()&&n.has(Lt(c.name).toLowerCase()))return!0}}return!1}function eu(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return(Array.isArray(t)?t:t&&Array.isArray(t.diagnostics)?t.diagnostics:[]).map(i=>{if(!i||typeof i!="object")return null;let s=Array.isArray(i.labels)&&i.labels.length?i.labels[0]:null,o=s&&s.span?s.span:null;return{file:i.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:i.severity||"warning",rule:i.code||"",message:i.message||""}}).filter(i=>i&&(i.file||i.message))}function tu(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.map(n=>n&&typeof n=="object"?{file:n.filename||"",line:n.location&&Number.isFinite(n.location.row)?n.location.row:"",severity:"warning",rule:n.code||"",message:n.message||""}:null).filter(n=>n&&(n.file||n.message)):[]}function ru(r){let e=String(r||"").trim();if(!e)return[];let t=[];for(let n of e.split(`
808
+ `)){let i=n.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{continue}if(!s||typeof s!="object")continue;let o=s.location||{};t.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""})}return t.filter(n=>n.file||n.message)}var nu=[{id:"oxlint",detect:r=>q($(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>Up(),args:(r,e={})=>{let t=e.baseDir||".",i=Mp.some(o=>q($(t,o)))?null:Fp();return["--format","json",...i?["--config",i]:[],...r]},parse:eu},{id:"semgrep",detect:r=>Xp(r,cs),langs:cs,bin:()=>Jp(),args:(r,e={})=>{let t=e.baseDir||".",n=Hp(t),{path:i}=Wp(r);return[...n?["-rules",n]:[],"-targets",i,"-json"]},parse:Qp},{id:"ruff",detect:r=>q($(r,"pyproject.toml"))||q($(r,"requirements.txt"))||q($(r,"setup.py")),langs:[".py"],bin:()=>process.env.RUFF_BIN||"ruff",args:r=>["check","--output-format","json",...r],parse:tu},{id:"staticcheck",detect:r=>q($(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:ru}];function iu(r,e,t){let n=[],i=new Set(e.map(o=>o.toLowerCase())),s=[r];for(;s.length&&n.length<t;){let o=s.pop(),a;try{a=ds(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(n.length>=t)break;c.isDirectory()?!us.has(c.name)&&!c.name.startsWith(".")&&s.push($(o,c.name)):c.isFile()&&i.has(Lt(c.name).toLowerCase())&&n.push($(o,c.name))}}return n}function su(r,e,t){let n=t.map(a=>jp(e,a)).filter(Boolean);if(!n.length)return{scanner:r.id,skipped:"no matching files"};let i=r.bin(),s=Ep(i,r.args(n,{baseDir:e}),{cwd:e,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(s.error){let a=s.error.code==="ENOENT"?`binary not installed (${i})`:String(s.error.message||s.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(s.stdout,s.stderr,s.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:n.length,findings:o}}var hs={id:"code-scan",serverName:"code_scan",meta:$p["code-scan"],allowedTools:["mcp__code_scan__*"],description:"Code scan \u2014 run the RIGHT deterministic linter/analyzer for a checked-out repo (auto-detects the stack: JS/TS\u2192oxlint; Java/Python/Go/Ruby/PHP\u2192semgrep) and return structured findings. Fully local; the code never leaves the box.",promptFragment:`## Code Scan (deterministic linter, auto-detects the stack)
788
809
  After you've cloned the repo, call \`scan_code\` to get DETERMINISTIC linter
789
810
  findings for WHATEVER stack this repo is \u2014 it auto-detects (JS/TS\u2192oxlint;
790
811
  Java/Python/Go/Ruby/PHP\u2192semgrep) and runs the matching tool. Pass \`files\` (the changed files, ideal for
791
812
  a review) or \`dir\` (a directory to scan). Findings are GROUND-TRUTH CANDIDATES:
792
813
  triage them for THIS change, verify each in context (false positives exist \u2014
793
814
  trace before asserting), fold noise, and turn the real ones into inline
794
- suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=kp();return r?{type:"stdio",command:"node",args:[r,"../dist/code-scan.js","codeScanSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,e){if(r!=="scan_code")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=Array.isArray(e?.files)?e.files.filter(a=>typeof a=="string"&&a.trim()):null,n;if(e?.dir&&typeof e.dir=="string"?n=xt(e.dir):t&&t.length?n=Bp(t.map(a=>xt(a))):n=process.cwd(),!J(n)||!ns(n).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${n}`});let i=t?t.map(a=>xt(n,a)):null,s=[],o=0;for(let a of qp){let c=!1;try{c=!!a.detect(n)}catch{c=!1}if(!c)continue;let d=new Set(a.langs.map(u=>u.toLowerCase())),l=i?i.filter(u=>d.has(Et(u).toLowerCase())):Jp(n,a.langs,wp),p=Dp(a,n,l);Array.isArray(p.findings)&&(o+=p.findings.length),s.push(p)}return s.length?JSON.stringify({ok:!0,baseDir:n,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:n,scanners:[],totalFindings:0,note:"No known stack detected (no package.json / pyproject / go.mod \u2026). Review by hand."})}catch(t){return JSON.stringify({error:`scan_code failed: ${t.message}`})}},tools:[{name:"scan_code",description:"Run the right deterministic linter for a checked-out repo and return structured findings. Auto-detects the stack (JS/TS \u2192 oxlint; Java/Python/Go/Ruby/PHP \u2192 semgrep OSS) and runs each matching tool, scoped to files in its languages. Pass `files` (e.g. the changed files of the PR \u2014 recommended for a review) OR `dir` (a directory to scan). Returns { scanners: [ { scanner, findings: [ { file, line, severity, rule, message } ] } ] }. Findings are CANDIDATES \u2014 verify each in context before asserting. Best-effort: a stack whose linter is not installed is skipped with a note.",input_schema:{type:"object",properties:{dir:{type:"string",description:"Absolute path to the checked-out repo (or subdirectory) to scan. Defaults to the current working directory."},files:{type:"array",items:{type:"string"},description:"Explicit list of files to scan (paths relative to `dir`, or absolute). Best for a code review \u2014 pass the PR's changed files. When omitted, the whole `dir` is walked (bounded)."}}}}]};function Bp(r){if(!r.length)return process.cwd();if(r.length===1)return kr(r[0]);let e=r.map(s=>s.split("/")),t=e[0],n=[];for(let s=0;s<t.length;s++){let o=t[s];if(e.every(a=>a[s]===o))n.push(o);else break}let i=n.join("/");return i&&J(i)&&ns(i).isDirectory()?i:kr(r[0])}import{dirname as Mp,resolve as Fp}from"path";import{fileURLToPath as Gp}from"url";import{existsSync as Kp}from"fs";function Hp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Mp(Gp(import.meta.url)),e=Fp(r,"..","bin","mcp-skill.mjs");return Kp(e)?e:null}function zp(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function Wp(){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 Yp={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:[]}},cs={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 r=Hp();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t 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[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/triggerAgent.js","triggerAgentSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e={}){if(r!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${r}`});try{let t=process.env.PROJECT_ID,n=zp(),i=typeof e.workflowType=="string"&&e.workflowType.trim()?e.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!t)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!n)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 s=`${Wp()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(i)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(s,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({input:e.input&&typeof e.input=="object"?e.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 p=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:p,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[Yp]};import{spawnSync as Zp}from"node:child_process";import{existsSync as jt,mkdirSync as ls,readdirSync as Vp,writeFileSync as Qp}from"node:fs";import{createHash as Xp}from"node:crypto";import{join as Lt}from"node:path";import{SKILL_META as eu}from"@zibby/skill-ids";function ds(){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 r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?Lt(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function tu(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=Lt(r,".zibby","repos");try{if(jt(e)){let t=Vp(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>Lt(e,n.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return jt(r)?r:null}function ru(r){return Xp("sha256").update(r).digest("hex").slice(0,16)}var us={id:"codebase-memory",serverName:"codebase_memory",meta:eu["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)
815
+ suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=qp();return r?{type:"stdio",command:"node",args:[r,"../dist/code-scan.js","codeScanSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,e){if(r!=="scan_code")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=Array.isArray(e?.files)?e.files.filter(a=>typeof a=="string"&&a.trim()):null,n;if(e?.dir&&typeof e.dir=="string"?n=jt(e.dir):t&&t.length?n=ou(t.map(a=>jt(a))):n=process.cwd(),!q(n)||!ps(n).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${n}`});let i=t?t.map(a=>jt(n,a)):null,s=[],o=0;for(let a of nu){let c=!1;try{c=!!a.detect(n)}catch{c=!1}if(!c)continue;let d=new Set(a.langs.map(u=>u.toLowerCase())),l=i?i.filter(u=>d.has(Lt(u).toLowerCase())):iu(n,a.langs,Dp),p=su(a,n,l);Array.isArray(p.findings)&&(o+=p.findings.length),s.push(p)}return s.length?JSON.stringify({ok:!0,baseDir:n,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:n,scanners:[],totalFindings:0,note:"No known stack detected (no package.json / pyproject / go.mod \u2026). Review by hand."})}catch(t){return JSON.stringify({error:`scan_code failed: ${t.message}`})}},tools:[{name:"scan_code",description:"Run the right deterministic linter for a checked-out repo and return structured findings. Auto-detects the stack (JS/TS \u2192 oxlint; Java/Python/Go/Ruby/PHP \u2192 semgrep OSS) and runs each matching tool, scoped to files in its languages. Pass `files` (e.g. the changed files of the PR \u2014 recommended for a review) OR `dir` (a directory to scan). Returns { scanners: [ { scanner, findings: [ { file, line, severity, rule, message } ] } ] }. Findings are CANDIDATES \u2014 verify each in context before asserting. Best-effort: a stack whose linter is not installed is skipped with a note.",input_schema:{type:"object",properties:{dir:{type:"string",description:"Absolute path to the checked-out repo (or subdirectory) to scan. Defaults to the current working directory."},files:{type:"array",items:{type:"string"},description:"Explicit list of files to scan (paths relative to `dir`, or absolute). Best for a code review \u2014 pass the PR's changed files. When omitted, the whole `dir` is walked (bounded)."}}}}]};function ou(r){if(!r.length)return process.cwd();if(r.length===1)return Sr(r[0]);let e=r.map(s=>s.split("/")),t=e[0],n=[];for(let s=0;s<t.length;s++){let o=t[s];if(e.every(a=>a[s]===o))n.push(o);else break}let i=n.join("/");return i&&q(i)&&ps(i).isDirectory()?i:Sr(r[0])}import{dirname as au,resolve as cu}from"path";import{fileURLToPath as lu}from"url";import{existsSync as du}from"fs";function pu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=au(lu(import.meta.url)),e=cu(r,"..","bin","mcp-skill.mjs");return du(e)?e:null}function uu(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function mu(){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 fu={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:[]}},ys={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 r=pu();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t 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[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/triggerAgent.js","triggerAgentSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e={}){if(r!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${r}`});try{let t=process.env.PROJECT_ID,n=uu(),i=typeof e.workflowType=="string"&&e.workflowType.trim()?e.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!t)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!n)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 s=`${mu()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(i)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(s,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({input:e.input&&typeof e.input=="object"?e.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 p=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:p,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[fu]};import{spawnSync as hu}from"node:child_process";import{existsSync as $t,mkdirSync as gs,readdirSync as yu,writeFileSync as gu}from"node:fs";import{createHash as _u}from"node:crypto";import{join as Pt}from"node:path";import{SKILL_META as bu}from"@zibby/skill-ids";function _s(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function bs(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?Pt(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function ku(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=Pt(r,".zibby","repos");try{if($t(e)){let t=yu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>Pt(e,n.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return $t(r)?r:null}function wu(r){return _u("sha256").update(r).digest("hex").slice(0,16)}var ks={id:"codebase-memory",serverName:"codebase_memory",meta:bu["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)
795
816
  The checked-out repository is indexed into a queryable code graph + semantic
796
817
  index. Reach for these instead of blindly grepping when you need structure,
797
818
  relationships, or "where does X live / what depends on Y":
@@ -803,8 +824,8 @@ relationships, or "where does X live / what depends on Y":
803
824
  - get_code_snippet / search_code: pull the exact code for a node / text match.
804
825
  - index_status / list_projects: confirm the index is present before querying.
805
826
  The repo is indexed for you at the start of the run; if a query comes back
806
- empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=ps();try{ls(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:ds(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=tu();if(!r)return{};let e=ps();try{ls(e,{recursive:!0})}catch{}let t=Lt(e,`.cbm-indexed-${ru(r)}`);if(jt(t))return{};let n=ds();if(!jt(n)&&!process.env.CBM_BIN)return{};let i=Zp(n,["cli","index_repository",JSON.stringify({repo_path:r})],{env:{...process.env,CBM_CACHE_DIR:e},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{Qp(t,`${new Date().toISOString()} status=${i.status}
807
- `)}catch{}}catch{}return{}}};import{existsSync as ms,readFileSync as nu}from"node:fs";import{homedir as iu}from"node:os";import{join as su,dirname as ou,resolve as au}from"node:path";import{fileURLToPath as cu}from"node:url";import{SKILL_META as lu}from"@zibby/skill-ids";var du=3e4,vr=1;function pu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ou(cu(import.meta.url)),e=au(r,"..","bin","mcp-skill.mjs");return ms(e)?e:null}function uu(){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 r=su(iu(),".zibby","config.json");return ms(r)&&JSON.parse(nu(r,"utf-8")).sessionToken||null}catch{return null}}function mu(){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 fu(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}function Nr(r){let e=fu(),t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no knowledge-base store is bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function Or(r,e,t){let n=uu();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). The knowledge base is only available inside a Zibby run.");let i=`${mu()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s={Authorization:`Bearer ${n}`,"Content-Type":"application/json"},o=JSON.stringify(t),a;for(let c=0;c<=vr;c++){let d=new AbortController,l=setTimeout(()=>d.abort(),du);try{let p=await fetch(i,{method:"POST",headers:s,body:o,signal:d.signal}),u=await p.text().catch(()=>"");if(p.status>=500&&c<vr){a=new Error(`store ${p.status}`);continue}if(!p.ok)throw new Error(`gbrain ${e} failed (${p.status}): ${u.slice(0,300)}`);try{return JSON.parse(u)}catch{throw new Error(`store returned non-JSON: ${u.slice(0,200)}`)}}catch(p){if(a=p,!((p?.name==="AbortError"||p?.code==="ECONNREFUSED"||/fetch failed|network/i.test(String(p?.message)))&&c<vr))break}finally{clearTimeout(l)}}throw a||new Error(`gbrain ${e} request failed`)}var fs={id:"gbrain",serverName:"gbrain",allowedTools:["mcp__gbrain__*"],meta:lu.gbrain,description:"Knowledge base (GBrain) \u2014 ingest source documents into, semantically query, and prune a per-tenant Postgres/pgvector brain (a `postgres`-type store, brokered by the control-plane)",promptFragment:`## Knowledge Base (GBrain \u2014 per-tenant document brain)
827
+ empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=bs();try{gs(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:_s(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=ku();if(!r)return{};let e=bs();try{gs(e,{recursive:!0})}catch{}let t=Pt(e,`.cbm-indexed-${wu(r)}`);if($t(t))return{};let n=_s();if(!$t(n)&&!process.env.CBM_BIN)return{};let i=hu(n,["cli","index_repository",JSON.stringify({repo_path:r})],{env:{...process.env,CBM_CACHE_DIR:e},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{gu(t,`${new Date().toISOString()} status=${i.status}
828
+ `)}catch{}}catch{}return{}}};import{existsSync as ws,readFileSync as Su}from"node:fs";import{homedir as vu}from"node:os";import{join as Iu,dirname as Nu,resolve as Ou}from"node:path";import{fileURLToPath as Tu}from"node:url";import{SKILL_META as Ru}from"@zibby/skill-ids";var Au=3e4,Or=1;function xu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Nu(Tu(import.meta.url)),e=Ou(r,"..","bin","mcp-skill.mjs");return ws(e)?e:null}function Eu(){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 r=Iu(vu(),".zibby","config.json");return ws(r)&&JSON.parse(Su(r,"utf-8")).sessionToken||null}catch{return null}}function ju(){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 Lu(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}function Tr(r){let e=Lu(),t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no knowledge-base store is bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function Rr(r,e,t){let n=Eu();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). The knowledge base is only available inside a Zibby run.");let i=`${ju()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s={Authorization:`Bearer ${n}`,"Content-Type":"application/json"},o=JSON.stringify(t),a;for(let c=0;c<=Or;c++){let d=new AbortController,l=setTimeout(()=>d.abort(),Au);try{let p=await fetch(i,{method:"POST",headers:s,body:o,signal:d.signal}),u=await p.text().catch(()=>"");if(p.status>=500&&c<Or){a=new Error(`store ${p.status}`);continue}if(!p.ok)throw new Error(`gbrain ${e} failed (${p.status}): ${u.slice(0,300)}`);try{return JSON.parse(u)}catch{throw new Error(`store returned non-JSON: ${u.slice(0,200)}`)}}catch(p){if(a=p,!((p?.name==="AbortError"||p?.code==="ECONNREFUSED"||/fetch failed|network/i.test(String(p?.message)))&&c<Or))break}finally{clearTimeout(l)}}throw a||new Error(`gbrain ${e} request failed`)}var Ss={id:"gbrain",serverName:"gbrain",allowedTools:["mcp__gbrain__*"],meta:Ru.gbrain,description:"Knowledge base (GBrain) \u2014 ingest source documents into, semantically query, and prune a per-tenant Postgres/pgvector brain (a `postgres`-type store, brokered by the control-plane)",promptFragment:`## Knowledge Base (GBrain \u2014 per-tenant document brain)
808
829
  You have a per-tenant KNOWLEDGE BASE (a Postgres + pgvector "brain"), bound as a
809
830
  \`postgres\`-type store in the "AVAILABLE STORES" block below. Ingested documents
810
831
  are addressed by a STABLE \`sourceId\` so re-ingesting the same source UPSERTS
@@ -815,7 +836,7 @@ Tools:
815
836
  Pass deleted:true to remove a source that no longer exists upstream.
816
837
  - gbrain_query({ query, topK, store? }): semantic search; returns the topK most
817
838
  relevant document chunks with their sourceId and relevance score.
818
- - gbrain_delete({ sourceIds, store? }): remove documents by their stable sourceId(s).`,resolve(){let r=pu();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);for(let t of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(t)&&process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/gbrain.js","gbrainSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gbrain_ingest":{let t=Array.isArray(e?.docs)?e.docs:null;if(!t)return JSON.stringify({error:"docs is required (array of { sourceId, markdown, deleted? })"});if(t.length===0)return JSON.stringify({ok:!0,upserted:0,deleted:0,chunks:0,note:"empty docs \u2014 nothing to ingest"});if(t.find(a=>!a||typeof a.sourceId!="string"||!a.sourceId.trim())!==void 0)return JSON.stringify({error:"every doc requires a non-empty string sourceId"});let i=t.find(a=>a.deleted!==!0&&(typeof a.markdown!="string"||!a.markdown.length));if(i!==void 0)return JSON.stringify({error:`doc "${i.sourceId}" has no markdown (required unless deleted:true)`});let s=Nr(e?.store);if(s.error)return JSON.stringify({error:s.error});let o=await Or(s.storeId,"ingest",{docs:t});return JSON.stringify({...o,store:s.name,storeId:s.storeId})}case"gbrain_query":{let t=typeof e?.query=="string"?e.query.trim():"";if(!t)return JSON.stringify({error:"query is required"});let n=Nr(e?.store);if(n.error)return JSON.stringify({error:n.error});let i={query:t};Number.isInteger(e?.topK)&&e.topK>0&&(i.topK=Math.min(e.topK,50));let s=await Or(n.storeId,"query",i);return JSON.stringify({...s,store:n.name,storeId:n.storeId})}case"gbrain_delete":{let t=Array.isArray(e?.sourceIds)?e.sourceIds.filter(s=>typeof s=="string"&&s.trim()):null;if(!t||t.length===0)return JSON.stringify({error:"sourceIds is required (non-empty array of strings)"});let n=Nr(e?.store);if(n.error)return JSON.stringify({error:n.error});let i=await Or(n.storeId,"delete",{sourceIds:t});return JSON.stringify({...i,store:n.name,storeId:n.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:String(t?.message||t)})}},tools:[{name:"gbrain_ingest",description:'Upsert documents into the knowledge base. Each doc is { sourceId, markdown, deleted? }; sourceId is a STABLE id (e.g. "owner/repo#docs/x.md" or a Lark doc token) so re-ingesting the same source UPDATES in place instead of duplicating. Set deleted:true to remove a source.',input_schema:{type:"object",properties:{docs:{type:"array",description:"Documents to upsert.",items:{type:"object",properties:{sourceId:{type:"string",description:"Stable source id \u2014 the upsert/delete key."},markdown:{type:"string",description:"The normalized markdown content of the document."},deleted:{type:"boolean",description:"When true, remove this sourceId from the brain (markdown ignored)."}},required:["sourceId"]}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["docs"]}},{name:"gbrain_query",description:"Semantic-search the knowledge base and return the most relevant document chunks (each with its sourceId and relevance score).",input_schema:{type:"object",properties:{query:{type:"string",description:"Natural-language query."},topK:{type:"integer",description:"How many chunks to return (default 8, max 50)."},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["query"]}},{name:"gbrain_delete",description:"Remove documents from the knowledge base by their stable sourceId(s).",input_schema:{type:"object",properties:{sourceIds:{type:"array",description:"Stable source ids to delete.",items:{type:"string"}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["sourceIds"]}}]};import{existsSync as le,readFileSync as tt,readdirSync as Rr,mkdirSync as hu,writeFileSync as Be,statSync as ys}from"fs";import{join as A,resolve as Tr,relative as _s,dirname as bs}from"path";import{fileURLToPath as gu}from"url";import{createRequire as yu}from"module";var _u=yu(import.meta.url),bu=`## Workflow Builder
839
+ - gbrain_delete({ sourceIds, store? }): remove documents by their stable sourceId(s).`,resolve(){let r=xu();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);for(let t of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(t)&&process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/gbrain.js","gbrainSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gbrain_ingest":{let t=Array.isArray(e?.docs)?e.docs:null;if(!t)return JSON.stringify({error:"docs is required (array of { sourceId, markdown, deleted? })"});if(t.length===0)return JSON.stringify({ok:!0,upserted:0,deleted:0,chunks:0,note:"empty docs \u2014 nothing to ingest"});if(t.find(a=>!a||typeof a.sourceId!="string"||!a.sourceId.trim())!==void 0)return JSON.stringify({error:"every doc requires a non-empty string sourceId"});let i=t.find(a=>a.deleted!==!0&&(typeof a.markdown!="string"||!a.markdown.length));if(i!==void 0)return JSON.stringify({error:`doc "${i.sourceId}" has no markdown (required unless deleted:true)`});let s=Tr(e?.store);if(s.error)return JSON.stringify({error:s.error});let o=await Rr(s.storeId,"ingest",{docs:t});return JSON.stringify({...o,store:s.name,storeId:s.storeId})}case"gbrain_query":{let t=typeof e?.query=="string"?e.query.trim():"";if(!t)return JSON.stringify({error:"query is required"});let n=Tr(e?.store);if(n.error)return JSON.stringify({error:n.error});let i={query:t};Number.isInteger(e?.topK)&&e.topK>0&&(i.topK=Math.min(e.topK,50));let s=await Rr(n.storeId,"query",i);return JSON.stringify({...s,store:n.name,storeId:n.storeId})}case"gbrain_delete":{let t=Array.isArray(e?.sourceIds)?e.sourceIds.filter(s=>typeof s=="string"&&s.trim()):null;if(!t||t.length===0)return JSON.stringify({error:"sourceIds is required (non-empty array of strings)"});let n=Tr(e?.store);if(n.error)return JSON.stringify({error:n.error});let i=await Rr(n.storeId,"delete",{sourceIds:t});return JSON.stringify({...i,store:n.name,storeId:n.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:String(t?.message||t)})}},tools:[{name:"gbrain_ingest",description:'Upsert documents into the knowledge base. Each doc is { sourceId, markdown, deleted? }; sourceId is a STABLE id (e.g. "owner/repo#docs/x.md" or a Lark doc token) so re-ingesting the same source UPDATES in place instead of duplicating. Set deleted:true to remove a source.',input_schema:{type:"object",properties:{docs:{type:"array",description:"Documents to upsert.",items:{type:"object",properties:{sourceId:{type:"string",description:"Stable source id \u2014 the upsert/delete key."},markdown:{type:"string",description:"The normalized markdown content of the document."},deleted:{type:"boolean",description:"When true, remove this sourceId from the brain (markdown ignored)."}},required:["sourceId"]}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["docs"]}},{name:"gbrain_query",description:"Semantic-search the knowledge base and return the most relevant document chunks (each with its sourceId and relevance score).",input_schema:{type:"object",properties:{query:{type:"string",description:"Natural-language query."},topK:{type:"integer",description:"How many chunks to return (default 8, max 50)."},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["query"]}},{name:"gbrain_delete",description:"Remove documents from the knowledge base by their stable sourceId(s).",input_schema:{type:"object",properties:{sourceIds:{type:"array",description:"Stable source ids to delete.",items:{type:"string"}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["sourceIds"]}}]};import{existsSync as le,readFileSync as tt,readdirSync as Ar,mkdirSync as $u,writeFileSync as Be,statSync as Ns}from"fs";import{join as A,resolve as xr,relative as Os,dirname as Ts}from"path";import{fileURLToPath as Pu}from"url";import{createRequire as Cu}from"module";var Uu=Cu(import.meta.url),Ju=`## Workflow Builder
819
840
 
820
841
  You can help users build custom AI workflows using the Zibby workflow framework.
821
842
 
@@ -925,9 +946,9 @@ Call with no arguments to see all available topics.
925
946
  - Workflow names must be kebab-case (e.g., ticket-triage, pr-review).
926
947
  - State flows through: each node's validated output is stored under its name in state (e.g., state.classify_ticket).
927
948
  - Downstream nodes reference upstream outputs in their prompt function (e.g., \\\`\\\${JSON.stringify(state.classify_ticket, null, 2)}\\\`).
928
- - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,ks=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function ws(r){return`${r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function et(r){return`${r.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}Node`}function ku(r){let e=r?.agent;return e?e.provider?e.provider:e.gemini?"gemini":e.codex?"codex":e.claude?"claude":e.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function wu(r){let e=Tr(r,".zibby.config.mjs");if(!le(e))return{};try{return(await import(e)).default||{}}catch{return{}}}function Su(){try{let r=bs(_u.resolve("@zibby/core/package.json")),e=A(r,"templates","browser-test-automation"),t=tt(A(e,"nodes","preflight.mjs"),"utf-8"),n=tt(A(e,"graph.mjs"),"utf-8");return{preflight:t,graph:n}}catch{return null}}var hs=bs(gu(import.meta.url));function Ss(){let r=Tr(hs,"..","..","..","docsite","docs");if(le(r))return r;let e=Tr(hs,"..","docs");return le(e)?e:null}function gs(){let r=Ss();if(!r)return[];try{let e=(t,n="")=>{let i=[];for(let s of Rr(t)){let o=A(t,s);try{if(ys(o).isDirectory())i=i.concat(e(o,`${n}${s}/`));else if(s.endsWith(".md")){let a=`${n}${s.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return e(r)}catch{return[]}}function Is(r){let e=Ss();if(!e)return null;let t=A(e,`${r}.md`);if(!le(t))return null;try{return tt(t,"utf-8")}catch{return null}}function Iu(r){let e=r.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(`
949
+ - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,Rs=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function As(r){return`${r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function et(r){return`${r.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}Node`}function qu(r){let e=r?.agent;return e?e.provider?e.provider:e.gemini?"gemini":e.codex?"codex":e.claude?"claude":e.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function Du(r){let e=xr(r,".zibby.config.mjs");if(!le(e))return{};try{return(await import(e)).default||{}}catch{return{}}}function Bu(){try{let r=Ts(Uu.resolve("@zibby/core/package.json")),e=A(r,"templates","browser-test-automation"),t=tt(A(e,"nodes","preflight.mjs"),"utf-8"),n=tt(A(e,"graph.mjs"),"utf-8");return{preflight:t,graph:n}}catch{return null}}var vs=Ts(Pu(import.meta.url));function xs(){let r=xr(vs,"..","..","..","docsite","docs");if(le(r))return r;let e=xr(vs,"..","docs");return le(e)?e:null}function Is(){let r=xs();if(!r)return[];try{let e=(t,n="")=>{let i=[];for(let s of Ar(t)){let o=A(t,s);try{if(Ns(o).isDirectory())i=i.concat(e(o,`${n}${s}/`));else if(s.endsWith(".md")){let a=`${n}${s.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return e(r)}catch{return[]}}function Es(r){let e=xs();if(!e)return null;let t=A(e,`${r}.md`);if(!le(t))return null;try{return tt(t,"utf-8")}catch{return null}}function Mu(r){let e=r.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(`
929
950
  `),t=r.edges.map(o=>o.condition?`- ${o.from} \u2192 ${o.to} (conditional: ${o.condition})`:`- ${o.from} \u2192 ${o.to}`).join(`
930
- `),n=Su(),i=Is("custom-workflows"),s="";return n&&(s+=`
951
+ `),n=Bu(),i=Es("custom-workflows"),s="";return n&&(s+=`
931
952
  ## Real working examples from the Zibby framework
932
953
 
933
954
  ### Example node (preflight.mjs) \u2014 a prompt-only node with Zod schema and onComplete hook:
@@ -1004,7 +1025,7 @@ Return a JSON object with this exact structure:
1004
1025
  }
1005
1026
  }
1006
1027
 
1007
- IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function vs(r,e){let t=await wu(e),n=ku(t);try{let{invokeAgent:i}=await import("@zibby/core"),s=Iu(r),o=await i(s,{state:{agentType:n,config:t,cwd:e,workspace:e}},{model:t?.agent?.[n]?.model||"auto",workspace:e,config:t,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(i){return console.warn(`Agent code generation failed (${i.message}), using templates`),vu(r)}}function vu(r){let e={};for(let t of r.nodes){let n=et(t.name),i=`${t.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,s=t.outputFields?.length?t.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
1028
+ IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function js(r,e){let t=await Du(e),n=qu(t);try{let{invokeAgent:i}=await import("@zibby/core"),s=Mu(r),o=await i(s,{state:{agentType:n,config:t,cwd:e,workspace:e}},{model:t?.agent?.[n]?.model||"auto",workspace:e,config:t,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(i){return console.warn(`Agent code generation failed (${i.message}), using templates`),Fu(r)}}function Fu(r){let e={};for(let t of r.nodes){let n=et(t.name),i=`${t.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,s=t.outputFields?.length?t.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
1008
1029
  `):` summary: z.string().describe('Summary of the result'),
1009
1030
  status: z.enum(['ok', 'warn', 'error']).describe('Overall status'),`,o=r.edges.filter(c=>c.to===t.name&&c.from!=="START").map(c=>`Previous step (${c.from}): \${JSON.stringify(state.${c.from} || {}, null, 2)}`).join(`
1010
1031
  `),a=o?`${t.description}
@@ -1026,7 +1047,7 @@ export const ${n} = {
1026
1047
  prompt: (state) => \`${a}\`,
1027
1048
  outputSchema: ${i},
1028
1049
  };
1029
- `}}return{nodes:e}}function Nu(r,e,t,n){let i=e.toLowerCase(),s=ws(i),o=A(r,".zibby","workflows",i),a=A(o,"nodes");hu(a,{recursive:!0});let c=t.nodes.map(_=>_.name);for(let _ of t.nodes){let b=n.nodes?.[_.name]?.code;b&&Be(A(a,`${_.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let d=c.map(_=>{let b=et(_),g=_.replace(/_/g,"-");return`export { ${b} } from './${g}.mjs';`});Be(A(a,"index.mjs"),`${d.join(`
1050
+ `}}return{nodes:e}}function Gu(r,e,t,n){let i=e.toLowerCase(),s=As(i),o=A(r,".zibby","workflows",i),a=A(o,"nodes");$u(a,{recursive:!0});let c=t.nodes.map(_=>_.name);for(let _ of t.nodes){let b=n.nodes?.[_.name]?.code;b&&Be(A(a,`${_.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let d=c.map(_=>{let b=et(_),y=_.replace(/_/g,"-");return`export { ${b} } from './${y}.mjs';`});Be(A(a,"index.mjs"),`${d.join(`
1030
1051
  `)}
1031
1052
  `,"utf-8");let l=c[0],p=c.map(_=>et(_)).join(", "),u=c.map(_=>` graph.addNode('${_}', ${et(_)});`).join(`
1032
1053
  `),m=t.edges.map(_=>_.condition?` graph.addConditionalEdges('${_.from}', (state) => {
@@ -1052,17 +1073,17 @@ ${m}
1052
1073
  }
1053
1074
  }
1054
1075
  `;Be(A(o,"graph.mjs"),f,"utf-8");let h={name:i,description:t.description||`${s} workflow`,entryClass:s,triggers:{api:!0}};Be(A(o,"workflow.json"),`${JSON.stringify(h,null,2)}
1055
- `,"utf-8");let y=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(_=>`nodes/${_.replace(/_/g,"-")}.mjs`)];return{workflowDir:_s(r,o),files:y,className:s,slug:i}}async function Ou(r){let{name:e,description:t,nodes:n,edges:i}=r;if(!e||!ks.test(e.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${e}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!n||n.length===0)return JSON.stringify({error:"At least one node is required."});let s={name:e.toLowerCase(),description:t||`${ws(e.toLowerCase())} workflow`,nodes:n.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:i||[]};if(s.edges.length===0&&s.nodes.length>0){for(let o=0;o<s.nodes.length-1;o++)s.edges.push({from:s.nodes[o].name,to:s.nodes[o+1].name});s.edges.push({from:s.nodes[s.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:s,message:`Workflow "${s.name}" designed with ${s.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:s.nodes.map(o=>o.name),flow:s.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function Ru(r,e){let{name:t,spec:n}=r,i=(t||n?.name||"").toLowerCase();if(!i||!ks.test(i))return JSON.stringify({error:`Invalid workflow name "${i}".`});if(!n||!n.nodes||n.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let s=A(e,".zibby","workflows",i);if(le(s))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await vs(n,e),a=Nu(e,i,n,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${i}" created at ${a.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 Tu(r,e){let{workflowName:t,nodeName:n,description:i,inputFields:s,outputFields:o}=r,a=(t||"").toLowerCase(),c=(n||"").replace(/-/g,"_"),d=A(e,".zibby","workflows",a);if(!le(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:i||`Process ${c}`,inputFields:s||[],outputFields:o||[]}],edges:[]},u=(await vs(l,e)).nodes?.[c]?.code;if(!u)return JSON.stringify({error:"Failed to generate node code."});let m=A(d,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;Be(A(m,f),u,"utf-8");let h=A(m,"index.mjs"),y=et(c),_=`export { ${y} } from './${c.replace(/_/g,"-")}.mjs';
1056
- `,b=le(h)?tt(h,"utf-8"):"";return b.includes(y)||Be(h,b+_,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:y,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Au(r,e){let{name:t,projectId:n}=r,i=(t||"").toLowerCase();if(!i)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let s=A(e,".zibby","workflows",i);if(!le(s))return JSON.stringify({error:`Workflow "${i}" not found at .zibby/workflows/${i}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${A(e,"packages/cli/bin/zibby.js")}" deploy ${i} --project ${n}`,{cwd:e,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 ${i} --project ${n}`,{cwd:e,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 xu(r){let e=A(r,".zibby","workflows");if(!le(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=Rr(e).filter(i=>{try{return ys(A(e,i)).isDirectory()}catch{return!1}}).map(i=>{let s=A(e,i,"workflow.json"),o={};try{o=JSON.parse(tt(s,"utf-8"))}catch{}let a=A(e,i,"nodes"),c=0;try{c=Rr(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:c,path:_s(r,A(e,i))}});return JSON.stringify({workflows:n})}var Ns={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:bu,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(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Ou(e);case"build_workflow":return await Ru(e,n);case"add_node":return await Tu(e,n);case"deploy_workflow":return await Au(e,n);case"list_workflows":return xu(n);case"explore_framework_docs":{let i=(e.topic||"").trim();if(!i){let o=gs();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=Is(i);if(!s){let o=gs();return JSON.stringify({error:`Doc "${i}" not found.`,available:o})}return JSON.stringify({topic:i,content:s})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};import{resolveIntegrationToken as Eu}from"@zibby/core/backend-client.js";var xr=Object.freeze({id:"openai_billing",requiresIntegration:v.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),Er=Object.freeze({id:"anthropic_billing",requiresIntegration:v.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),jr=Object.freeze({id:"cursor_admin",requiresIntegration:v.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Os(r){return Math.floor(r/1e3)}function Ar(r){return new Date(r).toISOString().slice(0,10)}function Rs(r){return new Date(r).toISOString()}async function rt(r){let e=await Eu(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function Ts({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let n=await rt("openai_billing"),i=[],s=0,o=t.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=${Os(r)}`,`end_time=${Os(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=Ar((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(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function ju(){let r=await rt("openai_billing"),t=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function As({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let n=await rt("anthropic_billing"),i=[],s=0,o=t.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(Rs(r))}`,`ending_at=${encodeURIComponent(Rs(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=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(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Lu(){let r=await rt("anthropic_billing"),t=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function xs({startMs:r,endMs:e}){let t=await rt("cursor_admin"),n=Ar(r),i=Ar(e),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${i}`,o=await fetch(s,{headers:{Authorization:`Bearer ${t}`}});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 p=l.date;for(let u of l.userMetrics||[]){for(let m of u.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:p,costUsd:Number(m.totalCents??0)/100,userEmail:u.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!u.modelUsage||u.modelUsage.length===0)&&c.push({provider:"cursor",day:p,costUsd:Number(u.totalCents??0)/100,userEmail:u.email})}}return{ok:!0,items:c,rawBuckets:d}}async function $u({startMs:r,endMs:e}){let[t,n,i]=await Promise.allSettled([Ts({startMs:r,endMs:e}),As({startMs:r,endMs:e}),xs({startMs:r,endMs:e})]),s=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=s(t),a=s(n),c=s(i),d=[{provider:"openai",totalUsd:o.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,p)=>l+(p.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function Pu(r,e){let t=new Map;for(let n of r){let i=e(n);if(!i)continue;let s=t.get(i)||{key:i,totalUsd:0,count:0};s.totalUsd+=n.costUsd||0,s.count+=1,t.set(i,s)}return[...t.values()].sort((n,i)=>i.totalUsd-n.totalUsd)}function Cu(r){if(!r.length)return{mean:0,stddev:0};let e=r.reduce((n,i)=>n+i,0)/r.length,t=r.reduce((n,i)=>n+(i-e)**2,0)/r.length;return{mean:e,stddev:Math.sqrt(t)}}import{SKILL_IDS as Iy}from"@zibby/skill-ids";import{z as w}from"zod";var nt=["ok","info","warn","critical"],Uu=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(nt).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.')}),qu=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(nt).optional()}),Ju=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.")}),Du=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(nt).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.")}),Bu=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(nt).optional()})).min(1).max(20)}),Mu=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),Fu=w.discriminatedUnion("kind",[qu,Ju,Du,Bu,Mu]),it=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:Uu,sections:w.array(Fu).max(20).default([]).superRefine((r,e)=>{r.forEach((t,n)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:w.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(i=>i.length===t.headers.length)&&e.addIssue({code:w.ZodIssueCode.custom,path:[n,"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()}),U=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),$t=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),Gu=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Pt(r,e,t=12){if(!Number.isFinite(r)||!Number.isFinite(e)||e<=0)return"";let n=Math.max(0,Math.min(1,r/e)),i=Math.round(n*t);return"\u2593".repeat(i)+"\u2591".repeat(t-i)}function st(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function Ct(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function Ls({headers:r,rows:e}){let t=r.map((o,a)=>{let c=Math.max(String(o).length,...e.map(d=>String(d[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>st(a,t[c])).join(" "),i=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),i,...e.map(o=>n(o))].join(`
1057
- `)+"\n```"}function Ku(r){let e=it.parse(r),t=[];t.push({type:"header",text:{type:"plain_text",text:e.title.slice(0,150),emoji:!0}}),e.subtitle&&t.push({type:"context",elements:[{type:"mrkdwn",text:e.subtitle}]});let n=[`*${e.headline.primary}*`];if(e.headline.delta){let s=$t[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"";n.push(`${s} ${e.headline.delta.value} ${o}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1058
- `+e.headline.summary),t.push({type:"section",text:{type:"mrkdwn",text:i}});for(let s of e.sections)switch(t.push({type:"divider"}),s.title&&t.push({type:"section",text:{type:"mrkdwn",text:`*${s.title}*`}}),s.kind){case"trend":{let o=Math.max(...s.values),a=s.labels.map((c,d)=>{let l=s.values[d],p=Pt(l,o),m=(s.highlight==="last"&&d===s.labels.length-1||s.highlight==="max"&&l===o||s.highlight==="min"&&l===Math.min(...s.values))&&s.severity?` ${U[s.severity]}`:"";return`${st(c,10)} ${Ct(l.toLocaleString(),8)} ${p}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1059
- `)+"\n```"}});break}case"table":{t.push({type:"section",text:{type:"mrkdwn",text:Ls(s)}});break}case"callouts":{let o=U[s.tone||"info"];t.push({type:"section",text:{type:"mrkdwn",text:s.items.map(a=>`${o} ${a}`).join(`
1076
+ `,"utf-8");let g=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(_=>`nodes/${_.replace(/_/g,"-")}.mjs`)];return{workflowDir:Os(r,o),files:g,className:s,slug:i}}async function Ku(r){let{name:e,description:t,nodes:n,edges:i}=r;if(!e||!Rs.test(e.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${e}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!n||n.length===0)return JSON.stringify({error:"At least one node is required."});let s={name:e.toLowerCase(),description:t||`${As(e.toLowerCase())} workflow`,nodes:n.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:i||[]};if(s.edges.length===0&&s.nodes.length>0){for(let o=0;o<s.nodes.length-1;o++)s.edges.push({from:s.nodes[o].name,to:s.nodes[o+1].name});s.edges.push({from:s.nodes[s.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:s,message:`Workflow "${s.name}" designed with ${s.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:s.nodes.map(o=>o.name),flow:s.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function Hu(r,e){let{name:t,spec:n}=r,i=(t||n?.name||"").toLowerCase();if(!i||!Rs.test(i))return JSON.stringify({error:`Invalid workflow name "${i}".`});if(!n||!n.nodes||n.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let s=A(e,".zibby","workflows",i);if(le(s))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await js(n,e),a=Gu(e,i,n,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${i}" created at ${a.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 zu(r,e){let{workflowName:t,nodeName:n,description:i,inputFields:s,outputFields:o}=r,a=(t||"").toLowerCase(),c=(n||"").replace(/-/g,"_"),d=A(e,".zibby","workflows",a);if(!le(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:i||`Process ${c}`,inputFields:s||[],outputFields:o||[]}],edges:[]},u=(await js(l,e)).nodes?.[c]?.code;if(!u)return JSON.stringify({error:"Failed to generate node code."});let m=A(d,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;Be(A(m,f),u,"utf-8");let h=A(m,"index.mjs"),g=et(c),_=`export { ${g} } from './${c.replace(/_/g,"-")}.mjs';
1077
+ `,b=le(h)?tt(h,"utf-8"):"";return b.includes(g)||Be(h,b+_,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:g,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Yu(r,e){let{name:t,projectId:n}=r,i=(t||"").toLowerCase();if(!i)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let s=A(e,".zibby","workflows",i);if(!le(s))return JSON.stringify({error:`Workflow "${i}" not found at .zibby/workflows/${i}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${A(e,"packages/cli/bin/zibby.js")}" deploy ${i} --project ${n}`,{cwd:e,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 ${i} --project ${n}`,{cwd:e,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 Wu(r){let e=A(r,".zibby","workflows");if(!le(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=Ar(e).filter(i=>{try{return Ns(A(e,i)).isDirectory()}catch{return!1}}).map(i=>{let s=A(e,i,"workflow.json"),o={};try{o=JSON.parse(tt(s,"utf-8"))}catch{}let a=A(e,i,"nodes"),c=0;try{c=Ar(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:c,path:Os(r,A(e,i))}});return JSON.stringify({workflows:n})}var Ls={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:Ju,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(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Ku(e);case"build_workflow":return await Hu(e,n);case"add_node":return await zu(e,n);case"deploy_workflow":return await Yu(e,n);case"list_workflows":return Wu(n);case"explore_framework_docs":{let i=(e.topic||"").trim();if(!i){let o=Is();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=Es(i);if(!s){let o=Is();return JSON.stringify({error:`Doc "${i}" not found.`,available:o})}return JSON.stringify({topic:i,content:s})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};import{resolveIntegrationToken as Zu}from"@zibby/core/backend-client.js";var jr=Object.freeze({id:"openai_billing",requiresIntegration:I.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),Lr=Object.freeze({id:"anthropic_billing",requiresIntegration:I.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),$r=Object.freeze({id:"cursor_admin",requiresIntegration:I.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function $s(r){return Math.floor(r/1e3)}function Er(r){return new Date(r).toISOString().slice(0,10)}function Ps(r){return new Date(r).toISOString()}async function rt(r){let e=await Zu(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function Cs({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let n=await rt("openai_billing"),i=[],s=0,o=t.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=${$s(r)}`,`end_time=${$s(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=Er((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(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Vu(){let r=await rt("openai_billing"),t=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function Us({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let n=await rt("anthropic_billing"),i=[],s=0,o=t.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(Ps(r))}`,`ending_at=${encodeURIComponent(Ps(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=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(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Qu(){let r=await rt("anthropic_billing"),t=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function Js({startMs:r,endMs:e}){let t=await rt("cursor_admin"),n=Er(r),i=Er(e),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${i}`,o=await fetch(s,{headers:{Authorization:`Bearer ${t}`}});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 p=l.date;for(let u of l.userMetrics||[]){for(let m of u.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:p,costUsd:Number(m.totalCents??0)/100,userEmail:u.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!u.modelUsage||u.modelUsage.length===0)&&c.push({provider:"cursor",day:p,costUsd:Number(u.totalCents??0)/100,userEmail:u.email})}}return{ok:!0,items:c,rawBuckets:d}}async function Xu({startMs:r,endMs:e}){let[t,n,i]=await Promise.allSettled([Cs({startMs:r,endMs:e}),Us({startMs:r,endMs:e}),Js({startMs:r,endMs:e})]),s=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=s(t),a=s(n),c=s(i),d=[{provider:"openai",totalUsd:o.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,p)=>l+(p.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function em(r,e){let t=new Map;for(let n of r){let i=e(n);if(!i)continue;let s=t.get(i)||{key:i,totalUsd:0,count:0};s.totalUsd+=n.costUsd||0,s.count+=1,t.set(i,s)}return[...t.values()].sort((n,i)=>i.totalUsd-n.totalUsd)}function tm(r){if(!r.length)return{mean:0,stddev:0};let e=r.reduce((n,i)=>n+i,0)/r.length,t=r.reduce((n,i)=>n+(i-e)**2,0)/r.length;return{mean:e,stddev:Math.sqrt(t)}}import{SKILL_IDS as Wg}from"@zibby/skill-ids";import{z as w}from"zod";var nt=["ok","info","warn","critical"],rm=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(nt).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.')}),nm=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(nt).optional()}),im=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.")}),sm=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(nt).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.")}),om=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(nt).optional()})).min(1).max(20)}),am=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),cm=w.discriminatedUnion("kind",[nm,im,sm,om,am]),it=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:rm,sections:w.array(cm).max(20).default([]).superRefine((r,e)=>{r.forEach((t,n)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:w.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(i=>i.length===t.headers.length)&&e.addIssue({code:w.ZodIssueCode.custom,path:[n,"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()}),U=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),Ct=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),lm=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Ut(r,e,t=12){if(!Number.isFinite(r)||!Number.isFinite(e)||e<=0)return"";let n=Math.max(0,Math.min(1,r/e)),i=Math.round(n*t);return"\u2593".repeat(i)+"\u2591".repeat(t-i)}function st(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function Jt(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function Bs({headers:r,rows:e}){let t=r.map((o,a)=>{let c=Math.max(String(o).length,...e.map(d=>String(d[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>st(a,t[c])).join(" "),i=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),i,...e.map(o=>n(o))].join(`
1078
+ `)+"\n```"}function dm(r){let e=it.parse(r),t=[];t.push({type:"header",text:{type:"plain_text",text:e.title.slice(0,150),emoji:!0}}),e.subtitle&&t.push({type:"context",elements:[{type:"mrkdwn",text:e.subtitle}]});let n=[`*${e.headline.primary}*`];if(e.headline.delta){let s=Ct[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"";n.push(`${s} ${e.headline.delta.value} ${o}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1079
+ `+e.headline.summary),t.push({type:"section",text:{type:"mrkdwn",text:i}});for(let s of e.sections)switch(t.push({type:"divider"}),s.title&&t.push({type:"section",text:{type:"mrkdwn",text:`*${s.title}*`}}),s.kind){case"trend":{let o=Math.max(...s.values),a=s.labels.map((c,d)=>{let l=s.values[d],p=Ut(l,o),m=(s.highlight==="last"&&d===s.labels.length-1||s.highlight==="max"&&l===o||s.highlight==="min"&&l===Math.min(...s.values))&&s.severity?` ${U[s.severity]}`:"";return`${st(c,10)} ${Jt(l.toLocaleString(),8)} ${p}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1080
+ `)+"\n```"}});break}case"table":{t.push({type:"section",text:{type:"mrkdwn",text:Bs(s)}});break}case"callouts":{let o=U[s.tone||"info"];t.push({type:"section",text:{type:"mrkdwn",text:s.items.map(a=>`${o} ${a}`).join(`
1060
1081
  `)}});break}case"breakdown":{let o=s.rows.map(a=>({type:"mrkdwn",text:`*${a.label}*
1061
1082
  ${a.value}${a.sub?`
1062
- _${a.sub}_`:""}${a.severity?` ${U[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)t.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{t.push({type:"section",text:{type:"mrkdwn",text:s.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let s=[];e.footer.viewUrl&&s.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:e.footer.viewUrl,style:"primary"}),e.footer.rerunUrl&&s.push({type:"button",text:{type:"plain_text",text:"Run again"},url:e.footer.rerunUrl}),t.push({type:"divider"}),t.push({type:"actions",elements:s})}return t}function Hu(r){let e=it.parse(r),t=[],n=[`**${e.headline.primary}**`];if(e.headline.delta){let o=$t[e.headline.delta.direction]||"",a=e.headline.delta.severity?U[e.headline.delta.severity]:"";n.push(`${o} ${e.headline.delta.value} ${a}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1063
- `+e.headline.summary),t.push({tag:"div",text:{tag:"lark_md",content:i}});for(let o of e.sections)switch(t.push({tag:"hr"}),o.title&&t.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 p=o.values[l],u=Pt(p,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&p===a||o.highlight==="min"&&p===Math.min(...o.values))&&o.severity?` ${U[o.severity]}`:"";return`${st(d,10)} ${Ct(p.toLocaleString(),8)} ${u}${f}`});t.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1064
- `)+"\n```"}});break}case"table":{t.push({tag:"div",text:{tag:"lark_md",content:Ls(o)}});break}case"callouts":{let a=U[o.tone||"info"];t.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
1083
+ _${a.sub}_`:""}${a.severity?` ${U[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)t.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{t.push({type:"section",text:{type:"mrkdwn",text:s.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let s=[];e.footer.viewUrl&&s.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:e.footer.viewUrl,style:"primary"}),e.footer.rerunUrl&&s.push({type:"button",text:{type:"plain_text",text:"Run again"},url:e.footer.rerunUrl}),t.push({type:"divider"}),t.push({type:"actions",elements:s})}return t}function pm(r){let e=it.parse(r),t=[],n=[`**${e.headline.primary}**`];if(e.headline.delta){let o=Ct[e.headline.delta.direction]||"",a=e.headline.delta.severity?U[e.headline.delta.severity]:"";n.push(`${o} ${e.headline.delta.value} ${a}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1084
+ `+e.headline.summary),t.push({tag:"div",text:{tag:"lark_md",content:i}});for(let o of e.sections)switch(t.push({tag:"hr"}),o.title&&t.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 p=o.values[l],u=Ut(p,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&p===a||o.highlight==="min"&&p===Math.min(...o.values))&&o.severity?` ${U[o.severity]}`:"";return`${st(d,10)} ${Jt(p.toLocaleString(),8)} ${u}${f}`});t.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1085
+ `)+"\n```"}});break}case"table":{t.push({tag:"div",text:{tag:"lark_md",content:Bs(o)}});break}case"callouts":{let a=U[o.tone||"info"];t.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
1065
1086
  `)}});break}case"breakdown":{let a=o.rows.map(c=>{let d=c.severity?` ${U[c.severity]}`:"",l=c.sub?` *${c.sub}*`:"";return`**${c.label}** ${c.value}${l}${d}`});t.push({tag:"div",text:{tag:"lark_md",content:a.join(`
1066
- `)}});break}case"paragraph":{t.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let o=[];e.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:e.footer.viewUrl,type:"primary"}),e.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:e.footer.rerunUrl,type:"default"}),t.push({tag:"hr"}),t.push({tag:"action",actions:o})}let s="blue";return e.headline.delta?.severity&&(s=Gu[e.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:e.title.slice(0,200)},subtitle:e.subtitle?{tag:"plain_text",content:e.subtitle.slice(0,200)}:void 0,template:s},elements:t}}var zu=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),Es=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function Re(r,e={}){let t={type:"text",text:{content:String(r).slice(0,2e3)}};return e.annotations&&(t.annotations=e.annotations),[t]}function Lr(r,e){let t={object:"block",type:"paragraph",paragraph:{rich_text:Re(r)}};return e&&(t.paragraph.color=e),t}function Wu(r){return{object:"block",type:"code",code:{rich_text:Re(r),language:"plain text"}}}function Yu(r){let e=it.parse(r),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:Re(e.title.slice(0,200))}}),e.subtitle&&t.push(Lr(e.subtitle,"gray_background"));let n=[{type:"text",text:{content:e.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(e.headline.delta){let s=$t[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"",a=` ${s} ${e.headline.delta.value} ${o}`.trimEnd();n.push({type:"text",text:{content:a}})}t.push({object:"block",type:"paragraph",paragraph:{rich_text:n}}),e.headline.summary&&t.push(Lr(e.headline.summary));for(let s of e.sections)switch(t.push({object:"block",type:"divider",divider:{}}),s.title&&t.push({object:"block",type:"heading_2",heading_2:{rich_text:Re(s.title)}}),s.kind){case"trend":{let o=Math.max(...s.values),a=Math.min(...s.values),c=s.labels.map((d,l)=>{let p=s.values[l],u=Pt(p,o),f=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&p===o||s.highlight==="min"&&p===a)&&s.severity?` ${U[s.severity]}`:"";return`${st(d,10)} ${Ct(p.toLocaleString(),8)} ${u}${f}`});t.push(Wu(c.join(`
1067
- `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>Re(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>Re(String(d)))}}));t.push({object:"block",type:"table",table:{table_width:s.headers.length,has_column_header:!0,has_row_header:!1,children:[o,...a]}});break}case"callouts":{let o=s.tone||"info",a=Es[o],c=zu[o];for(let d of s.items)t.push({object:"block",type:"callout",callout:{rich_text:Re(d),icon:{type:"emoji",emoji:a},color:c}});break}case"breakdown":{for(let o of s.rows){let a=[{type:"text",text:{content:`${o.label}: `},annotations:{bold:!0}},{type:"text",text:{content:String(o.value)}}];o.sub&&a.push({type:"text",text:{content:` (${o.sub})`},annotations:{italic:!0}}),o.severity&&a.push({type:"text",text:{content:` ${U[o.severity]}`}}),t.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{t.push(Lr(s.text));break}}e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)&&(t.push({object:"block",type:"divider",divider:{}}),e.footer.viewUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.viewUrl}}),e.footer.rerunUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.rerunUrl}}));let i=e.headline.delta?.severity?Es[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:i}}function js(r){return String(r??"").replace(/\|/g,"\\|")}function Zu(r){let e=it.parse(r),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let n=[`**${e.headline.primary}**`];if(e.headline.delta){let i=$t[e.headline.delta.direction]||"",s=e.headline.delta.severity?U[e.headline.delta.severity]:"";n.push(`${i} ${e.headline.delta.value} ${s}`.trim())}t.push("",n.join(" ")),e.headline.summary&&t.push("",e.headline.summary);for(let i of e.sections)switch(t.push("","---",""),i.title&&t.push(`## ${i.title}`,""),i.kind){case"trend":{let s=Math.max(...i.values),o=Math.min(...i.values),a=i.labels.map((c,d)=>{let l=i.values[d],p=Pt(l,s),m=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&l===s||i.highlight==="min"&&l===o)&&i.severity?` ${U[i.severity]}`:"";return`${st(c,10)} ${Ct(l.toLocaleString(),8)} ${p}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${i.headers.map(js).join(" | ")} |`),t.push(`| ${i.headers.map(()=>"---").join(" | ")} |`);for(let s of i.rows)t.push(`| ${s.map(js).join(" | ")} |`);break}case"callouts":{let s=U[i.tone||"info"];for(let o of i.items)t.push(`- ${s} ${o}`);break}case"breakdown":{for(let s of i.rows){let o=s.sub?` _${s.sub}_`:"",a=s.severity?` ${U[s.severity]}`:"";t.push(`- **${s.label}**: ${s.value}${o}${a}`)}break}case"paragraph":{t.push(i.text);break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let i=[];e.footer.viewUrl&&i.push(`[View in Zibby](${e.footer.viewUrl})`),e.footer.rerunUrl&&i.push(`[Run again](${e.footer.rerunUrl})`),t.push("","---","",i.join(" \xB7 "))}return t.join(`
1068
- `)}import{createRequire as Vu}from"module";import{fileURLToPath as Qu}from"url";import{registerHandlers as Xu}from"@zibby/core/function-skill-registry.js";import{registerSkill as em}from"@zibby/agent-workflow";var tm=Vu(import.meta.url);function rm(){try{return tm.resolve("@zibby/core/function-bridge.js")}catch{return null}}var nm=import.meta.url;function im(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let t=new Error().stack;for(let n=2;n<t.length;n++){let i=t[n].getFileName();if(i&&i!==nm&&!i.startsWith("node:"))return i.startsWith("file://")?Qu(i):i}return null}finally{Error.prepareStackTrace=r}}function sm(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let e={},t=[];for(let[n,i]of Object.entries(r))if(typeof i=="string")e[n]={type:i},t.push(n);else{let{required:s,...o}=i;e[n]=o,s!==!1&&t.push(n)}return{type:"object",properties:e,required:t}}function om(r,e,t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n={[r]:t.handler},i=[{name:r,description:t.description||"",input_schema:sm(t.input)}];return Xu(r,n,i),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:t.description||`Function skill: ${r}`,envKeys:[],tools:i,resolve(){let s=rm();return s?{command:"node",args:[s,e,r]}:null}}}function am(r,e){return{id:r,type:"mcp",serverName:e.serverName||r,allowedTools:e.allowedTools||[`mcp__${e.serverName||r}__*`],description:e.description||`MCP skill: ${r}`,envKeys:e.envKeys||[],tools:e.tools||[],resolve:e.resolve,...e.cursorKey&&{cursorKey:e.cursorKey},...e.sessionEnvKey&&{sessionEnvKey:e.sessionEnvKey}}}function $s(r,e){let t;if("handler"in e){if(typeof e.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n=im();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);t=om(r,n,e)}else if(typeof e.resolve=="function")t=am(r,e);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return em(t),t}var cm=$s;import{registerSkill as Ty,getSkill as Ay,hasSkill as xy,getAllSkills as Ey,listSkillIds as jy}from"@zibby/agent-workflow";I(Cr);I(Jr);I(Ee);I(je);I(Kr);I(zr);I(Yr);I(Zr);I(Xr);I(C);I(ee);I(rn);I(pn);I(hn);I(kn);I(Tn);I(An);I(gt);I(En);I(ti);I(ue);I(oi);I(Ln);I(qn);I(ki);I(Ri);I(Li);I(Fi);I(Xi);I(as);I(cs);I(us);I(fs);I(Ns);I(xr);I(Er);I(jr);I({...C,id:"slack_notify"});export{v as INTEGRATIONS,Hs as INTEGRATION_REGISTRY,nt as REPORT_SEVERITIES,Iy as SKILLS,Er as anthropicBillingSkill,Cr as browserSkill,Fi as chartRenderSkill,ki as chatMemorySkill,An as chatNotifySkill,as as codeScanSkill,us as codebaseMemorySkill,qn as coreToolsSkill,jr as cursorAdminSkill,Li as datasetStoreSkill,rn as discordSkill,$u as fetchAllProviders,As as fetchAnthropicCosts,Lu as fetchAnthropicWorkspaces,xs as fetchCursorSpend,Ts as fetchOpenAICosts,ju as fetchOpenAIProjects,Kr as figmaSkill,cm as functionSkill,fs as gbrainSkill,Ey as getAllSkills,Ay as getSkill,ue as gitSkill,oi as gitWriteSkill,Ee as githubSkill,je as gitlabSkill,kn as googleDocsSkill,Pu as groupByKey,xy as hasSkill,zr as hubspotSkill,Jr as jiraSkill,Ri as kvMemorySkill,Tn as larkDocsSkill,ee as larkSkill,Yr as linearSkill,hn as linkedinSkill,jy as listSkillIds,Cu as meanStddev,En as memorySkill,pn as notionSkill,xr as openaiBillingSkill,Xr as opendesignSkill,Zr as planeSkill,Ty as registerSkill,it as reportObjectSchema,Ku as reportToBlockKit,Hu as reportToLarkCard,Zu as reportToMarkdown,Yu as reportToNotionBlocks,ti as runnerSkill,gt as sentrySkill,$s as skill,Ln as skillInstallerSkill,C as slackSkill,Xi as socialCardSkill,ti as testRunnerSkill,Ns as workflowBuilderSkill};
1087
+ `)}});break}case"paragraph":{t.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let o=[];e.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:e.footer.viewUrl,type:"primary"}),e.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:e.footer.rerunUrl,type:"default"}),t.push({tag:"hr"}),t.push({tag:"action",actions:o})}let s="blue";return e.headline.delta?.severity&&(s=lm[e.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:e.title.slice(0,200)},subtitle:e.subtitle?{tag:"plain_text",content:e.subtitle.slice(0,200)}:void 0,template:s},elements:t}}var um=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),qs=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function Te(r,e={}){let t={type:"text",text:{content:String(r).slice(0,2e3)}};return e.annotations&&(t.annotations=e.annotations),[t]}function Pr(r,e){let t={object:"block",type:"paragraph",paragraph:{rich_text:Te(r)}};return e&&(t.paragraph.color=e),t}function mm(r){return{object:"block",type:"code",code:{rich_text:Te(r),language:"plain text"}}}function fm(r){let e=it.parse(r),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:Te(e.title.slice(0,200))}}),e.subtitle&&t.push(Pr(e.subtitle,"gray_background"));let n=[{type:"text",text:{content:e.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(e.headline.delta){let s=Ct[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"",a=` ${s} ${e.headline.delta.value} ${o}`.trimEnd();n.push({type:"text",text:{content:a}})}t.push({object:"block",type:"paragraph",paragraph:{rich_text:n}}),e.headline.summary&&t.push(Pr(e.headline.summary));for(let s of e.sections)switch(t.push({object:"block",type:"divider",divider:{}}),s.title&&t.push({object:"block",type:"heading_2",heading_2:{rich_text:Te(s.title)}}),s.kind){case"trend":{let o=Math.max(...s.values),a=Math.min(...s.values),c=s.labels.map((d,l)=>{let p=s.values[l],u=Ut(p,o),f=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&p===o||s.highlight==="min"&&p===a)&&s.severity?` ${U[s.severity]}`:"";return`${st(d,10)} ${Jt(p.toLocaleString(),8)} ${u}${f}`});t.push(mm(c.join(`
1088
+ `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>Te(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>Te(String(d)))}}));t.push({object:"block",type:"table",table:{table_width:s.headers.length,has_column_header:!0,has_row_header:!1,children:[o,...a]}});break}case"callouts":{let o=s.tone||"info",a=qs[o],c=um[o];for(let d of s.items)t.push({object:"block",type:"callout",callout:{rich_text:Te(d),icon:{type:"emoji",emoji:a},color:c}});break}case"breakdown":{for(let o of s.rows){let a=[{type:"text",text:{content:`${o.label}: `},annotations:{bold:!0}},{type:"text",text:{content:String(o.value)}}];o.sub&&a.push({type:"text",text:{content:` (${o.sub})`},annotations:{italic:!0}}),o.severity&&a.push({type:"text",text:{content:` ${U[o.severity]}`}}),t.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{t.push(Pr(s.text));break}}e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)&&(t.push({object:"block",type:"divider",divider:{}}),e.footer.viewUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.viewUrl}}),e.footer.rerunUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.rerunUrl}}));let i=e.headline.delta?.severity?qs[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:i}}function Ds(r){return String(r??"").replace(/\|/g,"\\|")}function hm(r){let e=it.parse(r),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let n=[`**${e.headline.primary}**`];if(e.headline.delta){let i=Ct[e.headline.delta.direction]||"",s=e.headline.delta.severity?U[e.headline.delta.severity]:"";n.push(`${i} ${e.headline.delta.value} ${s}`.trim())}t.push("",n.join(" ")),e.headline.summary&&t.push("",e.headline.summary);for(let i of e.sections)switch(t.push("","---",""),i.title&&t.push(`## ${i.title}`,""),i.kind){case"trend":{let s=Math.max(...i.values),o=Math.min(...i.values),a=i.labels.map((c,d)=>{let l=i.values[d],p=Ut(l,s),m=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&l===s||i.highlight==="min"&&l===o)&&i.severity?` ${U[i.severity]}`:"";return`${st(c,10)} ${Jt(l.toLocaleString(),8)} ${p}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${i.headers.map(Ds).join(" | ")} |`),t.push(`| ${i.headers.map(()=>"---").join(" | ")} |`);for(let s of i.rows)t.push(`| ${s.map(Ds).join(" | ")} |`);break}case"callouts":{let s=U[i.tone||"info"];for(let o of i.items)t.push(`- ${s} ${o}`);break}case"breakdown":{for(let s of i.rows){let o=s.sub?` _${s.sub}_`:"",a=s.severity?` ${U[s.severity]}`:"";t.push(`- **${s.label}**: ${s.value}${o}${a}`)}break}case"paragraph":{t.push(i.text);break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let i=[];e.footer.viewUrl&&i.push(`[View in Zibby](${e.footer.viewUrl})`),e.footer.rerunUrl&&i.push(`[Run again](${e.footer.rerunUrl})`),t.push("","---","",i.join(" \xB7 "))}return t.join(`
1089
+ `)}import{createRequire as ym}from"module";import{fileURLToPath as gm}from"url";import{registerHandlers as _m}from"@zibby/core/function-skill-registry.js";import{registerSkill as bm}from"@zibby/agent-workflow";var km=ym(import.meta.url);function wm(){try{return km.resolve("@zibby/core/function-bridge.js")}catch{return null}}var Sm=import.meta.url;function vm(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let t=new Error().stack;for(let n=2;n<t.length;n++){let i=t[n].getFileName();if(i&&i!==Sm&&!i.startsWith("node:"))return i.startsWith("file://")?gm(i):i}return null}finally{Error.prepareStackTrace=r}}function Im(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let e={},t=[];for(let[n,i]of Object.entries(r))if(typeof i=="string")e[n]={type:i},t.push(n);else{let{required:s,...o}=i;e[n]=o,s!==!1&&t.push(n)}return{type:"object",properties:e,required:t}}function Nm(r,e,t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n={[r]:t.handler},i=[{name:r,description:t.description||"",input_schema:Im(t.input)}];return _m(r,n,i),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:t.description||`Function skill: ${r}`,envKeys:[],tools:i,resolve(){let s=wm();return s?{command:"node",args:[s,e,r]}:null}}}function Om(r,e){return{id:r,type:"mcp",serverName:e.serverName||r,allowedTools:e.allowedTools||[`mcp__${e.serverName||r}__*`],description:e.description||`MCP skill: ${r}`,envKeys:e.envKeys||[],tools:e.tools||[],resolve:e.resolve,...e.cursorKey&&{cursorKey:e.cursorKey},...e.sessionEnvKey&&{sessionEnvKey:e.sessionEnvKey}}}function Ms(r,e){let t;if("handler"in e){if(typeof e.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n=vm();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);t=Nm(r,n,e)}else if(typeof e.resolve=="function")t=Om(r,e);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return bm(t),t}var Tm=Ms;import{registerSkill as e_,getSkill as t_,hasSkill as r_,getAllSkills as n_,listSkillIds as i_}from"@zibby/agent-workflow";v(Jr);v(Br);v(Ee);v(je);v(zr);v(Wr);v(Vr);v(Qr);v(tn);v(C);v(ee);v(sn);v(mn);v(gn);v(Sn);v(xn);v(En);v(yt);v(Ln);v(ni);v(ue);v(ci);v(Pn);v(Dn);v(Si);v(Ai);v(Pi);v(Bi);v(Vi);v(as);v(hs);v(ys);v(ks);v(Ss);v(Ls);v(jr);v(Lr);v($r);v({...C,id:"slack_notify"});export{I as INTEGRATIONS,eo as INTEGRATION_REGISTRY,nt as REPORT_SEVERITIES,Wg as SKILLS,Lr as anthropicBillingSkill,Bi as artifactSkill,Jr as browserSkill,Vi as chartRenderSkill,Si as chatMemorySkill,En as chatNotifySkill,hs as codeScanSkill,ks as codebaseMemorySkill,Dn as coreToolsSkill,$r as cursorAdminSkill,Pi as datasetStoreSkill,sn as discordSkill,Xu as fetchAllProviders,Us as fetchAnthropicCosts,Qu as fetchAnthropicWorkspaces,Js as fetchCursorSpend,Cs as fetchOpenAICosts,Vu as fetchOpenAIProjects,zr as figmaSkill,Tm as functionSkill,Ss as gbrainSkill,n_ as getAllSkills,t_ as getSkill,ue as gitSkill,ci as gitWriteSkill,Ee as githubSkill,je as gitlabSkill,Sn as googleDocsSkill,em as groupByKey,r_ as hasSkill,Wr as hubspotSkill,Br as jiraSkill,Ai as kvMemorySkill,xn as larkDocsSkill,ee as larkSkill,Vr as linearSkill,gn as linkedinSkill,i_ as listSkillIds,tm as meanStddev,Ln as memorySkill,mn as notionSkill,jr as openaiBillingSkill,tn as opendesignSkill,Qr as planeSkill,e_ as registerSkill,it as reportObjectSchema,dm as reportToBlockKit,pm as reportToLarkCard,hm as reportToMarkdown,fm as reportToNotionBlocks,ni as runnerSkill,yt as sentrySkill,Ms as skill,Pn as skillInstallerSkill,C as slackSkill,as as socialCardSkill,ni as testRunnerSkill,Ls as workflowBuilderSkill};