@zibby/skills 0.1.73 → 0.1.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,27 +1,27 @@
1
- import{registerSkill as N}from"@zibby/agent-workflow";import{createRequire as Ts}from"module";import{join as As}from"path";var Es=Ts(import.meta.url);function xs(){if(process.env.MCP_BROWSER_PATH)return process.env.MCP_BROWSER_PATH;try{return Es.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js")}catch{return null}}var Ls="1280x720",$s="1280x720";function js({headless:n}={}){if(n===!0)return!0;if(n===!1)return!1;let e=process.env.ZIBBY_HEADLESS;return e==="1"||String(e).toLowerCase()==="true"}function Ps(n,e){let t=(n||[]).filter(r=>r!=="--headless");return e?[...t,"--headless"]:t}var Qt={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 ns}from"module";import{join as is}from"path";var ss=ns(import.meta.url);function os(){if(process.env.MCP_BROWSER_PATH)return process.env.MCP_BROWSER_PATH;try{return ss.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js")}catch{return null}}var as="1280x720",cs="1280x720";function ls({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 ds(r,e){let t=(r||[]).filter(n=>n!=="--headless");return e?[...t,"--headless"]:t}var hr={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:n,workspace:e,nodeName:t,headless:r}={}){let s=xs(),i=n&&t?As(n,t):null,o=i||n||e||"test-results",a=js({headless:r}),c={};if(i&&(c.ZIBBY_NODE_SESSION_PATH=i),n&&(c.ZIBBY_SESSION_PATH=n),!s)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=os(),s=r&&t?is(r,t):null,o=s||r||e||"test-results",a=ls({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:Ps([s,"--isolated",`--save-video=${Ls}`,`--viewport-size=${$s}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as Us}from"module";import{resolveIntegrationToken as qs,clearTokenCache as Ds}from"@zibby/core/backend-client.js";var v=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Cs=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var Js=Us(import.meta.url);function Bs(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return Js.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var Ms=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Gs(n,e){if(!e||!e.length)return n;let t=n;for(let r of e)r.type==="strong"?t=`**${t}**`:r.type==="em"?t=`_${t}_`:r.type==="code"?t=`\`${t}\``:r.type==="strike"?t=`~~${t}~~`:r.type==="link"&&r.attrs?.href&&(t=`[${t}](${r.attrs.href})`);return t}function Be(n,e=0){if(!Array.isArray(n))return"";let t=[];for(let r of n){if(r.type==="text"){t.push(Gs(r.text||"",r.marks));continue}if(r.type==="hardBreak"){t.push(`
7
- `);continue}if(r.type==="rule"){t.push(`
6
+ Override: set MCP_BROWSER_PATH to the path of mcp-browser-zibby.js.`);return{command:"node",args:ds([i,"--isolated",`--save-video=${as}`,`--viewport-size=${cs}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as ps}from"module";import{resolveIntegrationToken as ms,clearTokenCache as fs}from"@zibby/core/backend-client.js";var N=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),us=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var hs=ps(import.meta.url);function gs(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return hs.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var ys=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function _s(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 Qe(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(_s(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
7
+ `);continue}if(n.type==="rule"){t.push(`
8
8
  ---
9
- `);continue}let s=r.content?Be(r.content,e+1):"";if(r.type==="listItem")t.push(s);else if(r.type==="bulletList"){let i=(r.content||[]).map(o=>`- ${Be(o.content||[],e+1).trim()}`);t.push(`
10
- ${i.join(`
9
+ `);continue}let i=n.content?Qe(n.content,e+1):"";if(n.type==="listItem")t.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${Qe(o.content||[],e+1).trim()}`);t.push(`
10
+ ${s.join(`
11
11
  `)}
12
- `)}else if(r.type==="orderedList"){let i=(r.content||[]).map((o,a)=>`${a+1}. ${Be(o.content||[],e+1).trim()}`);t.push(`
13
- ${i.join(`
12
+ `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${Qe(o.content||[],e+1).trim()}`);t.push(`
13
+ ${s.join(`
14
14
  `)}
15
- `)}else if(r.type==="heading"){let i=r.attrs?.level||2;t.push(`
15
+ `)}else if(n.type==="heading"){let s=n.attrs?.level||2;t.push(`
16
16
 
17
- ${"#".repeat(i)} ${s.trim()}
17
+ ${"#".repeat(s)} ${i.trim()}
18
18
 
19
- `)}else Ms.has(r.type)?t.push(`
19
+ `)}else ys.has(n.type)?t.push(`
20
20
 
21
- ${s}
22
- `):t.push(s)}return t.join("").replace(/\n{3,}/g,`
21
+ ${i}
22
+ `):t.push(i)}return t.join("").replace(/\n{3,}/g,`
23
23
 
24
- `)}function fe(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function ht(n){return fe(n).replace(/[a-z0-9]+/g,"")}function Me(n,e){let t=fe(n),r=fe(e);if(!t||!r)return 0;if(t===r)return 1;if(t.length===1||r.length===1)return t===r?1:0;let s=l=>{let u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},i=s(t),o=s(r),a=0,c=0,d=0;for(let l of i.values())c+=l;for(let l of o.values())d+=l;for(let[l,u]of i.entries()){let p=o.get(l)||0;a+=Math.min(u,p)}return 2*a/Math.max(1,c+d)}function te(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ks(n,e=[]){let t=Array.isArray(e)?e:[];if(t.length===0)return{requested:n||null,resolved:null,strategy:"none"};let r=t.filter(a=>!a.subtask),s=r.length>0?r:t,i=te(n);if(i){let a=s.find(l=>te(l.name)===i);if(a)return{requested:n,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(p=>te(p)===i))continue;let u=s.find(p=>l.some(m=>te(m)===te(p.name)));if(u)return{requested:n,resolved:u,strategy:"alias"}}let d=s.map(l=>({t:l,score:Me(n,l.name)})).sort((l,u)=>u.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:n,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=s.find(d=>te(d.name)===a);if(c)return{requested:n||null,resolved:c,strategy:"default-preferred"}}return{requested:n||null,resolved:s[0],strategy:"default-first"}}async function Xt(n){let e=`projectKeys=${encodeURIComponent(n)}&expand=projects.issuetypes`,t=await E(`/rest/api/3/issue/createmeta?${e}`),r=Array.isArray(t?.projects)?t.projects:[],i=r.find(a=>String(a?.key||"").toUpperCase()===String(n||"").toUpperCase())||r[0]||null;return(Array.isArray(i?.issuetypes)?i.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function er(n,e){if(!n)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 r=`project = ${n} AND ${t} ORDER BY updated DESC`,s=`jql=${encodeURIComponent(r)}&maxResults=100&fields=customfield_10020`,i=await E(`/rest/api/3/search/jql?${s}`),o=new Map;for(let a of i.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let d={active:0,future:1,closed:2},l=(d[a.state]??3)-(d[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function Fs(n,{sprintId:e,sprintName:t,target:r}={}){let s=Array.isArray(n)?n:[];if(!s.length)return{sprint:null,selectedBy:"none"};if(e!=null&&String(e).trim()!=="")return{sprint:s.find(a=>String(a.id)===String(e))||null,selectedBy:"id"};if(t&&String(t).trim()){let o=String(t).trim(),a=s.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=s.map(d=>({s:d,score:Me(o,d.name||"")})).sort((d,l)=>l.score-d.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let i=String(r||"current").trim().toLowerCase();return i==="active"||i==="current"||i==="latest"?{sprint:s[0],selectedBy:i}:{sprint:s[0],selectedBy:"default"}}function Hs(n,e){let t=n?.fields?.customfield_10020;return Array.isArray(t)?t.some(r=>String(r?.id)===String(e)):!1}async function zs({issueKey:n,projectKey:e,sprintId:t,attempts:r=3,delayMs:s=450}){let i=[];for(let o=0;o<r;o++){try{let a=`project = ${e} AND key = ${n} 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 i.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:i};let u=await E(`/rest/api/3/issue/${n}?fields=customfield_10020,status`),p=Hs(u,t);if(i.push({attempt:o+1,jql:!1,issueField:p}),p)return{ok:!0,method:"issue_field",traces:i}}catch(a){i.push({attempt:o+1,error:String(a?.message||a)})}o<r-1&&await new Promise(a=>setTimeout(a,s))}return{ok:!1,method:"none",traces:i}}async function yt({issueKey:n,projectKey:e,sprintId:t,sprintName:r,target:s}){if(!n)return{ok:!1,error:"issueKey is required"};let i=e;if(!i&&(i=(await E(`/rest/api/3/issue/${n}?fields=project`))?.fields?.project?.key||null,!i))return{ok:!1,error:`Could not resolve project for ${n}`};let o=await er(i,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${i}`};let{sprint:a,selectedBy:c}=Fs(o,{sprintId:t,sprintName:r,target:s});if(!a)return{ok:!1,error:`No matching sprint found in ${i}`,requested:{sprintId:t??null,sprintName:r??null,target:s??"current"},availableSprints:o.map(u=>({id:u.id,name:u.name,state:u.state}))};await E(`/rest/api/3/issue/${n}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await zs({issueKey:n,projectKey:i,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:n,projectKey:i,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:d.method,verified:l,verificationTrace:d.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${n} in sprint ${a.id}`}}async function E(n,e={}){let t=async()=>{let{token:r,cloudId:s}=await qs("jira");if(typeof r!="string"||!r)throw new Error(`Invalid jira token type: ${typeof r}`);if(!s)throw new Error("Invalid jira cloudId: missing");let i=`https://api.atlassian.com/ex/jira/${s}${n}`,o=await fetch(i,{method:e.method||"GET",headers:{Authorization:`Bearer ${r}`,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(r){let s=String(r?.message||r||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("403")||s.includes("substring")))throw r;return Ds("jira"),t()}}var tr={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 Ie(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ot(r){return Ie(r).replace(/[a-z0-9]+/g,"")}function Xe(r,e){let t=Ie(r),n=Ie(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 u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},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,u]of s.entries()){let p=o.get(l)||0;a+=Math.min(u,p)}return 2*a/Math.max(1,c+d)}function se(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function bs(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=se(r);if(s){let a=i.find(l=>se(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(p=>se(p)===s))continue;let u=i.find(p=>l.some(m=>se(m)===se(p.name)));if(u)return{requested:r,resolved:u,strategy:"alias"}}let d=i.map(l=>({t:l,score:Xe(r,l.name)})).sort((l,u)=>u.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=>se(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 gr(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 yr(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 ks(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:Xe(o,d.name||"")})).sort((d,l)=>l.score-d.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let s=String(n||"current").trim().toLowerCase();return s==="active"||s==="current"||s==="latest"?{sprint:i[0],selectedBy:s}:{sprint:i[0],selectedBy:"default"}}function ws(r,e){let t=r?.fields?.customfield_10020;return Array.isArray(t)?t.some(n=>String(n?.id)===String(e)):!1}async function Ss({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 u=await E(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),p=ws(u,t);if(s.push({attempt:o+1,jql:!1,issueField:p}),p)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 Rt({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 yr(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=ks(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(u=>({id:u.id,name:u.name,state:u.state}))};await E(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await Ss({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 ms("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 fs("jira"),t()}}var _r={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:N.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 n=Bs();if(!n)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return process.env.ATLASSIAN_INSTANCE_URL&&(e.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{command:"node",args:[n],env:e,description:this.description}},async handleToolCall(n,e){try{switch(n){case"jira_list_projects":{let t=await E("/rest/api/3/project"),r=(Array.isArray(t)?t:[]).map(s=>({id:s.id,key:s.key,name:s.name,style:s.style}));return JSON.stringify({count:r.length,projects:r})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let i=await E(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(i)?i:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let r=await E("/rest/api/3/status"),s=(Array.isArray(r)?r:[]).map(i=>({id:i.id,name:i.name,category:i.statusCategory?.name||null})).sort((i,o)=>String(i.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:s.length,statuses:s})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let r=await Xt(t);return JSON.stringify({projectKey:t,count:r.length,issueTypes:r})}case"jira_search":{let t=e.jql||"",r=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let i=`jql=${encodeURIComponent(t)}&maxResults=${r}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await E(`/rest/api/3/search/jql?${i}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let r=await E(`/rest/api/3/issue/${t}`);return JSON.stringify({key:r.key,project:r.fields?.project?.key,summary:r.fields?.summary,description:r.fields?.description,status:r.fields?.status?.name,assignee:r.fields?.assignee?.displayName||"Unassigned",priority:r.fields?.priority?.name,type:r.fields?.issuetype?.name,labels:r.fields?.labels,created:r.fields?.created,updated:r.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:r,issueType:s,description:i,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:u,sprintName:p,target:m}=e;if(!t||!r)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:s||null,resolved:null,strategy:"none"},h=[];try{h=await Xt(t),f=Ks(s,h)}catch{}let _={project:{key:t},summary:r,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:s||"Task"}};i&&(_.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:i}]}]}),o&&(_.priority={name:o}),a?.length&&(_.labels=a),c&&(_.assignee={id:c});let g=await E("/rest/api/3/issue",{method:"POST",body:{fields:_}}),b={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&te(f.requested)!==te(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 yt({issueKey:g.key,projectKey:t,sprintId:u,sprintName:p,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:t,state:r}=e,s=await er(t,r);return JSON.stringify({count:s.length,sprints:s})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:r,sprintId:s,sprintName:i,target:o}=e||{},a=await yt({issueKey:t,projectKey:r,sprintId:s,sprintName:i,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:r,sprintId:s,sprintName:i,target:o}=e||{},a=await yt({issueKey:t,projectKey:r,sprintId:s,sprintName:i,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:r,projectKey:s,status:i,maxResults:o}=e;if(!t&&!r)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=r?`sprint = ${r}`:`sprint = "${t}"`,d=s?`project = ${s} AND `:"",l=i?` AND status = "${i}"`:"",u=`${d}${c}${l} ORDER BY status ASC, priority DESC`,p=`jql=${encodeURIComponent(u)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await E(`/rest/api/3/search/jql?${p}`),f=(m.issues||[]).map(_=>({key:_.key,project:_.fields?.project?.key,summary:_.fields?.summary,status:_.fields?.status?.name,assignee:_.fields?.assignee?.displayName||"Unassigned",priority:_.fields?.priority?.name,type:_.fields?.issuetype?.name})),h={};for(let _ of f)h[_.status]=(h[_.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:t,maxResults:r}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let i=await E(`/rest/api/3/issue/${t}/comment?maxResults=${r||50}&orderBy=-created`),o=(i.comments||[]).map(a=>{let c="";return a.body?.content&&(c=Be(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:i.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:r}=e;return!t||!r?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:r}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:r}=e;return!t||!r?JSON.stringify({error:"issueKey and fields are required"}):(await E(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:r}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:r,toStatus:s,statusName:i,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(s||i||o||"").trim();if(!r&&!a){let u=((await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(p=>({id:p.id,name:p.name,to:p.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:u})}let c=r;if(!c){let u=(await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[],p=fe(a),m=u.find(f=>fe(f?.name||"")===p||fe(f?.to?.name||"")===p);if(!m){let f=ht(a);f.length>=2&&(m=u.find(h=>{let _=ht(h?.name||""),g=ht(h?.to?.name||""),b=_.length>=2&&(_.includes(f)||f.includes(_)),y=g.length>=2&&(g.includes(f)||f.includes(g));return b||y}))}if(!m){let f=u.map(b=>{let y=Me(a,b?.name||""),w=Me(a,b?.to?.name||"");return{t:b,score:Math.max(y,w)}}).sort((b,y)=>y.score-b.score),h=f[0],_=f[1];h&&h.score>=.45&&(!_||h.score-_.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:u.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: ${n}`})}}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 Ys}from"fs";import{fileURLToPath as Ws}from"url";import{dirname as Zs,resolve as Vs}from"path";import{resolveIntegrationToken as rr}from"@zibby/core/backend-client.js";function Qs(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Zs(Ws(import.meta.url)),e=Vs(n,"..","bin","mcp-skill.mjs");return Ys(e)?e:null}async function I(n,e={}){let{token:t}=await rr("github"),r=n.startsWith("https://")?n:`https://api.github.com${n}`,s={Authorization:`Bearer ${t}`,Accept:e.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...e.body?{"Content-Type":"application/json"}:{}},i=await fetch(r,{method:e.method||"GET",headers:s,body:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`GitHub API ${i.status}: ${o.slice(0,300)}`)}return e.raw?i.text():i.json()}var he={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)
74
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=gs();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return process.env.ATLASSIAN_INSTANCE_URL&&(e.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{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 gr(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:u,sprintName:p,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 gr(t),f=bs(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&&se(f.requested)!==se(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 Rt({issueKey:_.key,projectKey:t,sprintId:u,sprintName:p,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,i=await yr(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 Rt({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 Rt({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}"`:"",u=`${d}${c}${l} ORDER BY status ASC, priority DESC`,p=`jql=${encodeURIComponent(u)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await E(`/rest/api/3/search/jql?${p}`),f=(m.issues||[]).map(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=Qe(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 u=((await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(p=>({id:p.id,name:p.name,to:p.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:u})}let c=n;if(!c){let u=(await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[],p=Ie(a),m=u.find(f=>Ie(f?.name||"")===p||Ie(f?.to?.name||"")===p);if(!m){let f=Ot(a);f.length>=2&&(m=u.find(h=>{let y=Ot(h?.name||""),_=Ot(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=u.map(b=>{let g=Xe(a,b?.name||""),w=Xe(a,b?.to?.name||"");return{t:b,score:Math.max(g,w)}}).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:u.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 Is}from"fs";import{fileURLToPath as vs}from"url";import{dirname as Ns,resolve as Os}from"path";import{resolveIntegrationToken as br}from"@zibby/core/backend-client.js";function Rs(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ns(vs(import.meta.url)),e=Os(r,"..","bin","mcp-skill.mjs");return Is(e)?e:null}async function I(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 ve={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:N.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
75
75
  You have access to the user's GitHub repositories. Available tools:
76
76
 
77
77
  ### Discovery
@@ -114,9 +114,9 @@ When user says "check out repo-name" or "clone repo-name":
114
114
  3. STOP. Do not offer to inspect files or ask what to do next.
115
115
 
116
116
  When user just wants to "look at" or "read" files (not clone):
117
- - Use github_get_file to read individual files via API`,resolve(){let n=Qs();if(!n)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:[n,"../dist/github.js","githubSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"github_search_issues":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let r=await I(`/search/issues?q=${encodeURIComponent(t)}&per_page=${e.limit||20}`),s=(r.items||[]).map(i=>({number:i.number,title:i.title,state:i.state,repo:i.repository_url?.split("/").slice(-2).join("/"),url:i.html_url,user:i.user?.login,isPR:!!i.pull_request,labels:(i.labels||[]).map(o=>o.name),createdAt:i.created_at}));return JSON.stringify({total:r.total_count,items:s})}case"github_search_code":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let r=e.repo?`+repo:${e.repo}`:"",s=e.language?`+language:${e.language}`:"",i=await I(`/search/code?q=${encodeURIComponent(t)}${r}${s}&per_page=${e.limit||15}`),o=(i.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:i.total_count,items:o})}case"github_get_pr":{let{owner:t,repo:r,number:s}=e;if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${t}/${r}/pulls/${s}`);return JSON.stringify({number:i.number,title:i.title,state:i.state,merged:i.merged,body:i.body?.slice(0,5e3),user:i.user?.login,branch:i.head?.ref,headSha:i.head?.sha,base:i.base?.ref,changedFiles:i.changed_files,additions:i.additions,deletions:i.deletions,createdAt:i.created_at,mergedAt:i.merged_at,url:i.html_url,labels:(i.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:t,repo:r,number:s}=e;if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${t}/${r}/pulls/${s}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=i.length>15e3;return JSON.stringify({number:s,diff:o?i.slice(0,15e3):i,truncated:o,totalLength:i.length})}case"github_list_pr_files":{let{owner:t,repo:r,number:s}=e;if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${t}/${r}/pulls/${s}/files?per_page=100`);return JSON.stringify({total:i.length,files:i.map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:r,number:s}=e;if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${t}/${r}/pulls/${s}/comments?per_page=50`),o=await I(`/repos/${t}/${r}/issues/${s}/comments?per_page=50`),a=[...i.map(c=>({type:"review",user:c.user?.login,body:c.body?.slice(0,1e3),path:c.path,line:c.line,createdAt:c.created_at})),...o.map(c=>({type:"issue",user:c.user?.login,body:c.body?.slice(0,1e3),createdAt:c.created_at}))].sort((c,d)=>new Date(c.createdAt)-new Date(d.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:t,repo:r,number:s,commentId:i}=e||{};if(!t||!r||!s||!i)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await I(`/repos/${t}/${r}/pulls/comments/${i}`),a=o.in_reply_to_id||o.id,c=[];try{c=await I(`/repos/${t}/${r}/pulls/${s}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let d=c.filter(p=>p.id===a||p.in_reply_to_id===a).sort((p,m)=>new Date(p.created_at)-new Date(m.created_at)),l=d.length?d:[o],u=l.find(p=>p.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:u.path,line:u.line??u.original_line??null,side:u.side||"RIGHT",diffHunk:typeof u.diff_hunk=="string"?u.diff_hunk.slice(0,3e3):null,commitId:u.commit_id||u.original_commit_id||null,notes:l.map(p=>({id:p.id,user:p.user?.login,body:(p.body||"").slice(0,4e3),createdAt:p.created_at,isRoot:p.id===a,url:p.html_url}))})}case"github_reply_review_thread":{let{owner:t,repo:r,number:s,commentId:i,body:o}=e||{};if(!t||!r||!s||!i||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await I(`/repos/${t}/${r}/pulls/${s}/comments/${i}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:t,repo:r,number:s,body:i}=e||{};if(!t||!r||!s||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await I(`/repos/${t}/${r}/issues/${s}/comments`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:t,repo:r,number:s,body:i,event:o,comments:a}=e||{};if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let c=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(c))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let d=Array.isArray(a)?a.filter(p=>p&&p.path&&p.body&&(p.line!=null||p.position!=null)).map(p=>{let m={path:p.path,body:String(p.body)};return p.line!=null?(m.line=Number(p.line),m.side=p.side==="LEFT"?"LEFT":"RIGHT"):m.position=Number(p.position),m}):[];if(c!=="APPROVE"&&!i&&d.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l={event:c};i&&(l.body=String(i)),d.length>0&&(l.comments=d);let u=await I(`/repos/${t}/${r}/pulls/${s}/reviews`,{method:"POST",body:l});return JSON.stringify({ok:!0,id:u.id,state:u.state,event:c,commentsPosted:d.length,url:u.html_url})}case"github_list_commits":{let{owner:t,repo:r,branch:s,path:i,limit:o}=e;if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let a=`/repos/${t}/${r}/commits?per_page=${o||20}`;s&&(a+=`&sha=${encodeURIComponent(s)}`),i&&(a+=`&path=${encodeURIComponent(i)}`);let c=await I(a);return JSON.stringify({total:c.length,commits:c.map(d=>({sha:d.sha?.slice(0,8),fullSha:d.sha,message:d.commit?.message?.slice(0,300),author:d.commit?.author?.name,date:d.commit?.author?.date,url:d.html_url}))})}case"github_get_commit":{let{owner:t,repo:r,sha:s}=e;if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and sha are required"});let i=await I(`/repos/${t}/${r}/commits/${s}`);return JSON.stringify({sha:i.sha?.slice(0,8),message:i.commit?.message,author:i.commit?.author?.name,date:i.commit?.author?.date,stats:i.stats,files:(i.files||[]).map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_get_file":{let{owner:t,repo:r,path:s,ref:i}=e;if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${t}/${r}/contents/${encodeURIComponent(s)}`;i&&(o+=`?ref=${encodeURIComponent(i)}`);let a=await I(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:s,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 I("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let r=t.repositories[0],s=r.owner.login,i=r.owner.type,o=i==="Organization"?`/orgs/${s}`:`/users/${s}`,a=await I(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:i,isOrg:i==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(t){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${t.message})`})}case"github_list_orgs":try{let r=(await I("/installation/repositories?per_page=100")).repositories||[],s=new Map;for(let o of r)o.owner.type==="Organization"&&(s.has(o.owner.login)||s.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let i=Array.from(s.values());return JSON.stringify({count:i.length,orgs:i,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(g){let b=g.replace(/^~(?=$|\/|\\)/,m);return a(b)},{owner:t,repo:r,destination:s}=e;if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let{execSync:i}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:d}=await import("fs"),{homedir:l,platform:u}=await import("os"),{token:p}=await rr("github"),m=l(),h=s?f(s):o(m,"zibby-repos"),_=o(h,r);if(d(h,{recursive:!0}),c(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});try{let g=`https://x-access-token:${p}@github.com/${t}/${r}.git`;i(`git clone ${g} "${_}"`,{stdio:"pipe"});let b=u()==="win32",y;return b?y=i(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):y=i(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${t}/${r} to ${_}`,contents:y.split(`
117
+ - Use github_get_file to read individual files via API`,resolve(){let r=Rs();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 I(`/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 I(`/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 I(`/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 I(`/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 I(`/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 I(`/repos/${t}/${n}/pulls/${i}/comments?per_page=50`),o=await I(`/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 I(`/repos/${t}/${n}/pulls/comments/${s}`),a=o.in_reply_to_id||o.id,c=[];try{c=await I(`/repos/${t}/${n}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let d=c.filter(p=>p.id===a||p.in_reply_to_id===a).sort((p,m)=>new Date(p.created_at)-new Date(m.created_at)),l=d.length?d:[o],u=l.find(p=>p.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:u.path,line:u.line??u.original_line??null,side:u.side||"RIGHT",diffHunk:typeof u.diff_hunk=="string"?u.diff_hunk.slice(0,3e3):null,commitId:u.commit_id||u.original_commit_id||null,notes:l.map(p=>({id:p.id,user:p.user?.login,body:(p.body||"").slice(0,4e3),createdAt:p.created_at,isRoot:p.id===a,url:p.html_url}))})}case"github_reply_review_thread":{let{owner: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 I(`/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 I(`/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(p=>p&&p.path&&p.body&&(p.line!=null||p.position!=null)).map(p=>{let m={path:p.path,body:String(p.body)};return p.line!=null?(m.line=Number(p.line),m.side=p.side==="LEFT"?"LEFT":"RIGHT"):m.position=Number(p.position),m}):[];if(c!=="APPROVE"&&!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 u=await I(`/repos/${t}/${n}/pulls/${i}/reviews`,{method:"POST",body:l});return JSON.stringify({ok:!0,id:u.id,state:u.state,event:c,commentsPosted:d.length,url:u.html_url})}case"github_list_commits":{let{owner: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 I(a);return JSON.stringify({total:c.length,commits:c.map(d=>({sha:d.sha?.slice(0,8),fullSha:d.sha,message:d.commit?.message?.slice(0,300),author:d.commit?.author?.name,date:d.commit?.author?.date,url:d.html_url}))})}case"github_get_commit":{let{owner:t,repo:n,sha:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let s=await I(`/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 I(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 I("/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 I(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 I("/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(_){let b=_.replace(/^~(?=$|\/|\\)/,m);return a(b)},{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:u}=await import("os"),{token:p}=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});try{let _=`https://x-access-token:${p}@github.com/${t}/${n}.git`;s(`git clone ${_} "${y}"`,{stdio:"pipe"});let b=u()==="win32",g;return b?g=s(`dir "${y}"`,{encoding:"utf-8",shell:"cmd.exe"}):g=s(`ls -la "${y}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:y,message:`Cloned ${t}/${n} to ${y}`,contents:g.split(`
118
118
  `).slice(0,30).join(`
119
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(g){return JSON.stringify({error:`Clone failed: ${g.message}`})}}case"github_search_repos":{let{query:t,limit:r}=e;if(!t)return JSON.stringify({error:"query is required"});let s=await this.handleToolCall("github_list_repos",{limit:200},{}),i=JSON.parse(s);if(i.error)return JSON.stringify(i);let o=t.toLowerCase(),a=i.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:t,count:a.length,repos:a.slice(0,r||20)})}case"github_list_repos":{let{owner:t,type:r,sort:s,direction:i,limit:o,query:a}=e,c=100,d=o||200,l=[],u=y=>({name:y.name,fullName:y.full_name,private:y.private,description:y.description,language:y.language,defaultBranch:y.default_branch,updatedAt:y.updated_at,stars:y.stargazers_count,url:y.html_url,fullPath:y.full_name,webUrl:y.html_url,visibility:y.visibility||(y.private?"private":"public")}),p=y=>{if(!a)return!0;let w=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(w)||y.fullName&&y.fullName.toLowerCase().includes(w)||y.description&&y.description.toLowerCase().includes(w)};if(!t){let y=1,w=!0;for(;w&&l.length<d;){let B=`/installation/repositories?per_page=${c}&page=${y}`,ft=(await I(B)).repositories||[];if(ft.length===0)break;l=l.concat(ft),w=ft.length===c,y++}let A=l.map(u).filter(p),ee=A.slice(0,d),mt=A.length>ee.length,T=ee.filter(B=>B.private).length,O=ee.filter(B=>!B.private).length;return JSON.stringify({count:ee.length,repos:ee,truncated:mt,privateCount:T,publicCount:O,message:`Found ${T} private and ${O} public repos`})}let m=await I(`/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=${r||"all"}&sort=${s||"updated"}&direction=${i||"desc"}`:y=`/users/${t}/repos?per_page=${c}&page=${f}&type=${r||"all"}&sort=${s||"updated"}&direction=${i||"desc"}`;let w=await I(y),A=Array.isArray(w)?w:[];if(A.length===0)break;l=l.concat(A),h=A.length===c,f++}let _=l.map(u).filter(p),g=_.slice(0,d),b=_.length>g.length;return JSON.stringify({count:g.length,repos:g,truncated:b})}case"github_create_pr":{let{owner:t,repo:r,head:s,title:i}=e||{};if(!t||!r||!s||!i)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=e.base;if(!o)try{o=(await I(`/repos/${t}/${r}`)).default_branch||"main"}catch{o="main"}let a={title:String(i),head:String(s),base:String(o),body:e.body?String(e.body):"",draft:!!e.draft};try{let c=await I(`/repos/${t}/${r}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:s,base:o,repo:`${t}/${r}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let d=String(c.message||c);if(/GitHub API 422/.test(d))return JSON.stringify({success:!1,branch:s,base:o,repo:`${t}/${r}`,provider:"github",skippedReason:d});throw c}}case"github_merge_pr":{let{owner:t,repo:r,number:s}=e||{};if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=e.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(i))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${i})`});let o={merge_method:i};e.commitTitle&&(o.commit_title=String(e.commitTitle)),e.commitMessage&&(o.commit_message=String(e.commitMessage));try{let a=await I(`/repos/${t}/${r}/pulls/${s}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:s,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:s,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:t,repo:r,title:s,body:i}=e;if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and title are required"});let o=await I(`/repos/${t}/${r}/issues`,{method:"POST",body:{title:s,body:i||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:t,repo:r,state:s,labels:i,since:o,assignee:a,sort:c,direction:d,limit:l}=e||{};if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let u=new URLSearchParams;u.set("state",s||"open"),u.set("per_page",String(l||30)),u.set("sort",c||"updated"),u.set("direction",d||"desc"),i&&u.set("labels",Array.isArray(i)?i.join(","):i),o&&u.set("since",o),a&&u.set("assignee",a);let p=await I(`/repos/${t}/${r}/issues?${u.toString()}`),m=(Array.isArray(p)?p:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:t,repo:r,number:s}=e||{};if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${t}/${r}/issues/${s}`);return i.pull_request?JSON.stringify({error:`#${s} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:i.number,title:i.title,body:i.body||"",state:i.state,stateReason:i.state_reason||null,labels:(i.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:i.assignee?.login||null,assignees:(i.assignees||[]).map(o=>o.login),user:i.user?.login,milestone:i.milestone?.title||null,comments:i.comments,url:i.html_url,createdAt:i.created_at,updatedAt:i.updated_at,closedAt:i.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:r,number:s,limit:i}=e||{};if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let o=await I(`/repos/${t}/${r}/issues/${s}/comments?per_page=${i||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:t,repo:r,number:s,body:i}=e||{};if(!t||!r||!s||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await I(`/repos/${t}/${r}/issues/${s}/comments`,{method:"POST",body:{body:i}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:t,repo:r,number:s,stateReason:i}=e||{};if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};i&&(o.state_reason=i);let a=await I(`/repos/${t}/${r}/issues/${s}`,{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:r,number:s}=e||{};if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await I(`/repos/${t}/${r}/issues/${s}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:i.number,state:i.state,url:i.html_url})}case"github_label_issue":{let{owner:t,repo:r,number:s,labels:i,mode:o}=e||{};if(!t||!r||!s)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(i)?i:i?[i]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await I(`/repos/${t}/${r}/issues/${s}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(u=>typeof u=="string"?u:u.name)})}if(c==="remove"){for(let u of a)await I(`/repos/${t}/${r}/issues/${s}/labels/${encodeURIComponent(u)}`,{method:"DELETE"});let l=await I(`/repos/${t}/${r}/issues/${s}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(u=>typeof u=="string"?u:u.name)})}let d=await I(`/repos/${t}/${r}/issues/${s}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:s,labels:(Array.isArray(d)?d:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 Xs}from"fs";import{fileURLToPath as ei}from"url";import{dirname as ti,resolve as ri}from"path";function ni(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=ti(ei(import.meta.url)),e=ri(n,"..","bin","mcp-skill.mjs");return Xs(e)?e:null}function si(){let n=process.env.GITLAB_API_URL;if(n)return n.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 ii(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let n=process.env.GITLAB_TOKEN;if(!n)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":n}}async function x(n,e={}){let t=/^https?:\/\//.test(n)?n:`${si()}${n}`,r={Accept:"application/json","User-Agent":"Zibby-App",...ii(),...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(t,{method:e.method||"GET",headers:r,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`GitLab API ${s.status}: ${i.slice(0,300)}`)}return e.raw?s.text():s.json()}function nr(){let n=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(n?n.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function oi(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function $(n){let e=String(n);return/^\d+$/.test(e)?e:encodeURIComponent(e)}var ye={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)
119
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(_){return JSON.stringify({error:`Clone failed: ${_.message}`})}}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=[],u=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")}),p=g=>{if(!a)return!0;let w=String(a).toLowerCase();return g.name&&g.name.toLowerCase().includes(w)||g.fullName&&g.fullName.toLowerCase().includes(w)||g.description&&g.description.toLowerCase().includes(w)};if(!t){let g=1,w=!0;for(;w&&l.length<d;){let D=`/installation/repositories?per_page=${c}&page=${g}`,de=(await I(D)).repositories||[];if(de.length===0)break;l=l.concat(de),w=de.length===c,g++}let T=l.map(u).filter(p),G=T.slice(0,d),we=T.length>G.length,R=G.filter(D=>D.private).length,O=G.filter(D=>!D.private).length;return JSON.stringify({count:G.length,repos:G,truncated:we,privateCount:R,publicCount:O,message:`Found ${R} private and ${O} public repos`})}let m=await I(`/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 w=await I(g),T=Array.isArray(w)?w:[];if(T.length===0)break;l=l.concat(T),h=T.length===c,f++}let y=l.map(u).filter(p),_=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 I(`/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 I(`/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 I(`/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 I(`/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 u=new URLSearchParams;u.set("state",i||"open"),u.set("per_page",String(l||30)),u.set("sort",c||"updated"),u.set("direction",d||"desc"),s&&u.set("labels",Array.isArray(s)?s.join(","):s),o&&u.set("since",o),a&&u.set("assignee",a);let p=await I(`/repos/${t}/${n}/issues?${u.toString()}`),m=(Array.isArray(p)?p:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await I(`/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 I(`/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 I(`/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 I(`/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 I(`/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 I(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(u=>typeof u=="string"?u:u.name)})}if(c==="remove"){for(let u of a)await I(`/repos/${t}/${n}/issues/${i}/labels/${encodeURIComponent(u)}`,{method:"DELETE"});let l=await I(`/repos/${t}/${n}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(u=>typeof u=="string"?u:u.name)})}let d=await I(`/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 Ts}from"fs";import{fileURLToPath as As}from"url";import{dirname as xs,resolve as Es}from"path";function Ls(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=xs(As(import.meta.url)),e=Es(r,"..","bin","mcp-skill.mjs");return Ts(e)?e:null}function $s(){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 js(){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 L(r,e={}){let t=/^https?:\/\//.test(r)?r:`${$s()}${r}`,n={Accept:"application/json","User-Agent":"Zibby-App",...js(),...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 kr(){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 Ps(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function j(r){let e=String(r);return/^\d+$/.test(e)?e:encodeURIComponent(e)}var Ne={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:N.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab (connected)
120
120
  You have access to the user's GitLab projects via the REST API (cloud gitlab.com OR self-hosted). A "merge request" (MR) is GitLab's pull request. An MR is addressed by a PROJECT (numeric id OR full path like "group/repo") and an \`iid\` (the per-project MR number shown in the URL). For projects, prefer the full path form ("group/subgroup/repo") \u2014 it's what users have. Available tools:
121
121
 
122
122
  ### Discovery
@@ -142,9 +142,9 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
142
142
 
143
143
  ### Notes
144
144
  - A code-review flow is: gitlab_get_mr (context + diff_refs) \u2192 gitlab_get_mr_changes (the diff) \u2192 gitlab_post_mr_discussion per inline finding \u2192 gitlab_post_mr_note for the summary.
145
- - If an inline position is rejected by GitLab (bad line anchor), fall back to gitlab_post_mr_note with the file/line in the text.`,resolve(){let n=ni();if(!n)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:[n,"../dist/gitlab.js","gitlabSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"gitlab_clone":{let{projectPath:t,projectId:r,destination:s,branch:i}=e||{},o=t&&String(t).trim();if(!o&&r!=null&&(/^\d+$/.test(String(r))?o=(await x(`/projects/${$(r)}`))?.path_with_namespace:o=String(r).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=oi();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:d,resolve:l}=await import("path"),{existsSync:u,mkdirSync:p}=await import("fs"),m=s?l(s):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(p(m,{recursive:!0}),u(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let _=nr().replace(/^https?:\/\//,""),b=`${nr().startsWith("http://")?"http":"https"}://oauth2:${a}@${_}/${o}.git`,y=i?`--branch "${String(i).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${y}${b} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let w=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:w.split(`
145
+ - If an inline position is rejected by GitLab (bad line anchor), fall back to gitlab_post_mr_note with the file/line in the text.`,resolve(){let r=Ls();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 L(`/projects/${j(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=Ps();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:d,resolve:l}=await import("path"),{existsSync:u,mkdirSync:p}=await import("fs"),m=i?l(i):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(p(m,{recursive:!0}),u(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let y=kr().replace(/^https?:\/\//,""),b=`${kr().startsWith("http://")?"http":"https"}://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 w=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:w.split(`
146
146
  `).slice(0,30).join(`
147
- `)})}catch(w){let A=String(w.message||w).split(a).join("***");return JSON.stringify({error:`Clone failed: ${A}`})}}case"gitlab_create_mr":{let t=e?.project??e?.projectId,r=e?.source_branch??e?.sourceBranch,{title:s}=e||{};if(!t||!r||!s)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let i=$(t),o=e?.target_branch??e?.targetBranch;if(!o)try{o=(await x(`/projects/${i}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(r),target_branch:String(o),title:String(s),description:e?.description?String(e.description):""};try{let c=await x(`/projects/${i}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(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:r}=e||{};if(!t||!r)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let s=$(t),i={};e.squash!=null&&(i.squash=!!e.squash),e.mergeCommitMessage&&(i.merge_commit_message=String(e.mergeCommitMessage)),e.mergeWhenPipelineSucceeds!=null&&(i.merge_when_pipeline_succeeds=!!e.mergeWhenPipelineSucceeds);try{let o=await x(`/projects/${s}/merge_requests/${r}/merge`,{method:"PUT",body:i});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??r,project:String(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:r,project:String(t),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:t,iid:r}=e||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let s=await x(`/projects/${$(t)}/merge_requests/${r}`);return JSON.stringify({iid:s.iid,projectId:s.project_id,title:s.title,description:(s.description||"").slice(0,5e3),state:s.state,author:s.author?.username,sourceBranch:s.source_branch,targetBranch:s.target_branch,draft:s.draft??s.work_in_progress??!1,mergeStatus:s.merge_status,changesCount:s.changes_count,labels:Array.isArray(s.labels)?s.labels:[],webUrl:s.web_url,createdAt:s.created_at,updatedAt:s.updated_at,mergedAt:s.merged_at,diffRefs:s.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:t,iid:r}=e||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let s=await x(`/projects/${$(t)}/merge_requests/${r}/changes`),i=Array.isArray(s.changes)?s.changes:[];return JSON.stringify({iid:s.iid,total:i.length,diffRefs:s.diff_refs||null,files:i.map(o=>({oldPath:o.old_path,newPath:o.new_path,newFile:!!o.new_file,deletedFile:!!o.deleted_file,renamedFile:!!o.renamed_file,diff:typeof o.diff=="string"?o.diff.slice(0,3e3):""}))})}case"gitlab_list_mrs":{let{projectId:t,state:r,targetBranch:s,sourceBranch:i,authorUsername:o,labels:a,search:c,sort:d,orderBy:l,limit:u}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",r||"opened"),p.set("per_page",String(u||20)),p.set("order_by",l||"updated_at"),p.set("sort",d||"desc"),s&&p.set("target_branch",s),i&&p.set("source_branch",i),o&&p.set("author_username",o),a&&p.set("labels",Array.isArray(a)?a.join(","):a),c&&p.set("search",c);let m=await x(`/projects/${$(t)}/merge_requests?${p.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:t,iid:r,limit:s}=e||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await x(`/projects/${$(t)}/merge_requests/${r}/notes?per_page=${s||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(i)?i.length:0,notes:(Array.isArray(i)?i:[]).map(o=>({id:o.id,author:o.author?.username,body:(o.body||"").slice(0,1e3),system:!!o.system,createdAt:o.created_at}))})}case"gitlab_post_mr_note":{let{projectId:t,iid:r,body:s}=e||{};if(!t||!r||!s)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await x(`/projects/${$(t)}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:r,path:s,oldPath:i,newLine:o,oldLine:a,body:c}=e||{};if(!t||!r||!s||!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=$(t),l=e.diffRefs||null;if(l||(l=(await x(`/projects/${d}/merge_requests/${r}`)).diff_refs||null),!l||!l.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let u={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:s,old_path:i||s};o!=null&&(u.new_line=Number(o)),a!=null&&(u.old_line=Number(a));try{let p=await x(`/projects/${d}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(c),position:u}});return JSON.stringify({ok:!0,discussionId:p.id})}catch(p){return JSON.stringify({ok:!1,error:`inline anchor rejected (${p.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:t,iid:r,body:s,comments:i}=e||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let o=$(t),a=Array.isArray(i)?i.filter(p=>p&&p.path&&p.body&&(p.newLine!=null||p.oldLine!=null)):[];if(!s&&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 x(`/projects/${o}/merge_requests/${r}`)).diff_refs||null);let d=!1;s&&(await x(`/projects/${o}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(s)}}),d=!0);let l=0,u=[];if(a.length>0&&c)for(let p of a){let m={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:p.path,old_path:p.oldPath||p.path};p.newLine!=null&&(m.new_line=Number(p.newLine)),p.oldLine!=null&&(m.old_line=Number(p.oldLine));try{await x(`/projects/${o}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(p.body),position:m}}),l+=1}catch(f){u.push(`${p.path}:${p.newLine??p.oldLine} \u2014 ${f.message}`)}}else a.length>0&&!c&&u.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:d,inlinePosted:l,inlineErrors:u.length?u:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:r,discussionId:s}=e||{};if(!t||!r||!s)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let i=await x(`/projects/${$(t)}/merge_requests/${r}/discussions/${encodeURIComponent(s)}`),o=Array.isArray(i.notes)?i.notes:[],a=o.find(d=>d.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:i.id,individualNote:!!i.individual_note,path:c&&(c.new_path||c.old_path)||null,newLine:c?c.new_line??null:null,oldLine:c?c.old_line??null:null,diffRefs:c?{base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha}:null,notes:o.map(d=>({id:d.id,author:d.author?.username,body:(d.body||"").slice(0,4e3),system:!!d.system,createdAt:d.created_at}))})}case"gitlab_reply_discussion":{let{projectId:t,iid:r,discussionId:s,body:i}=e||{};if(!t||!r||!s||!i)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await x(`/projects/${$(t)}/merge_requests/${r}/discussions/${encodeURIComponent(s)}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:t,limit:r}=e||{},s=Math.min(Number(r)>0?Number(r):50,200),i=new URLSearchParams;i.set("membership","true"),i.set("simple","true"),i.set("order_by","last_activity_at"),i.set("sort","desc"),i.set("per_page",String(Math.min(s+1,100))),t&&i.set("search",String(t));let o=await x(`/projects?${i.toString()}`),a=Array.isArray(o)?o:[],c=a.length>s,d=a.slice(0,s).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:r,labels:s,assigneeUsername:i,authorUsername:o,updatedAfter:a,search:c,sort:d,orderBy:l,limit:u}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",r||"opened"),p.set("per_page",String(u||30)),p.set("order_by",l||"updated_at"),p.set("sort",d||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),i&&p.set("assignee_username",i),o&&p.set("author_username",o),a&&p.set("updated_after",a),c&&p.set("search",c);let m=await x(`/projects/${$(t)}/issues?${p.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(_=>_.username),userNotesCount:h.user_notes_count,webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,issues:f})}case"gitlab_get_issue":{let{projectId:t,iid:r}=e||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let s=await x(`/projects/${$(t)}/issues/${r}`);return JSON.stringify({iid:s.iid,projectId:s.project_id,title:s.title,description:(s.description||"").slice(0,5e3),state:s.state,labels:Array.isArray(s.labels)?s.labels:[],author:s.author?.username,assignees:(s.assignees||[]).map(i=>i.username),milestone:s.milestone?.title||null,webUrl:s.web_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"gitlab_add_issue_comment":{let{projectId:t,iid:r,body:s}=e||{};if(!t||!r||!s)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await x(`/projects/${$(t)}/issues/${r}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 ai}from"fs";import{fileURLToPath as ci}from"url";import{dirname as li,resolve as di}from"path";import{resolveIntegrationToken as ui}from"@zibby/core/backend-client.js";function pi(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=li(ci(import.meta.url)),e=di(n,"..","bin","mcp-skill.mjs");return ai(e)?e:null}async function ve(n,e={}){let{token:t}=await ui("figma"),r=n.startsWith("https://")?n:`https://api.figma.com${n}`,s={"X-Figma-Token":t,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},i=await fetch(r,{method:e.method||"GET",headers:s,body:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Figma API ${i.status}: ${o.slice(0,300)}`)}return i.json()}var sr={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:v.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes, comments, and render frames as PNGs",promptFragment:`## Figma (connected)
147
+ `)})}catch(w){let T=String(w.message||w).split(a).join("***");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=j(t),o=e?.target_branch??e?.targetBranch;if(!o)try{o=(await L(`/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 L(`/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=j(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 L(`/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 L(`/projects/${j(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 L(`/projects/${j(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:u}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",n||"opened"),p.set("per_page",String(u||20)),p.set("order_by",l||"updated_at"),p.set("sort",d||"desc"),i&&p.set("target_branch",i),s&&p.set("source_branch",s),o&&p.set("author_username",o),a&&p.set("labels",Array.isArray(a)?a.join(","):a),c&&p.set("search",c);let m=await L(`/projects/${j(t)}/merge_requests?${p.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:t,iid:n,limit:i}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await L(`/projects/${j(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 L(`/projects/${j(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=j(t),l=e.diffRefs||null;if(l||(l=(await L(`/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 u={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&&(u.new_line=Number(o)),a!=null&&(u.old_line=Number(a));try{let p=await L(`/projects/${d}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(c),position:u}});return JSON.stringify({ok:!0,discussionId:p.id})}catch(p){return JSON.stringify({ok:!1,error:`inline anchor rejected (${p.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:t,iid:n,body:i,comments:s}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let o=j(t),a=Array.isArray(s)?s.filter(p=>p&&p.path&&p.body&&(p.newLine!=null||p.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 L(`/projects/${o}/merge_requests/${n}`)).diff_refs||null);let d=!1;i&&(await L(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:String(i)}}),d=!0);let l=0,u=[];if(a.length>0&&c)for(let p of a){let m={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:p.path,old_path:p.oldPath||p.path};p.newLine!=null&&(m.new_line=Number(p.newLine)),p.oldLine!=null&&(m.old_line=Number(p.oldLine));try{await L(`/projects/${o}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(p.body),position:m}}),l+=1}catch(f){u.push(`${p.path}:${p.newLine??p.oldLine} \u2014 ${f.message}`)}}else a.length>0&&!c&&u.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:d,inlinePosted:l,inlineErrors:u.length?u:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:n,discussionId:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let s=await L(`/projects/${j(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 L(`/projects/${j(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 L(`/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:u}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",n||"opened"),p.set("per_page",String(u||30)),p.set("order_by",l||"updated_at"),p.set("sort",d||"desc"),i&&p.set("labels",Array.isArray(i)?i.join(","):i),s&&p.set("assignee_username",s),o&&p.set("author_username",o),a&&p.set("updated_after",a),c&&p.set("search",c);let m=await L(`/projects/${j(t)}/issues?${p.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(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 L(`/projects/${j(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 L(`/projects/${j(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 Cs}from"fs";import{fileURLToPath as Us}from"url";import{dirname as Ds,resolve as qs}from"path";import{resolveIntegrationToken as Js}from"@zibby/core/backend-client.js";function Bs(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ds(Us(import.meta.url)),e=qs(r,"..","bin","mcp-skill.mjs");return Cs(e)?e:null}async function Pe(r,e={}){let{token:t}=await Js("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()}var wr={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:N.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes, comments, and render frames as PNGs",promptFragment:`## Figma (connected)
148
148
  You have read access to the user's Figma files via the Figma REST API. Tools:
149
149
 
150
150
  ### Identity
@@ -162,7 +162,7 @@ You have read access to the user's Figma files via the Figma REST API. Tools:
162
162
 
163
163
  ### Notes
164
164
  - The fileKey is NOT the file name \u2014 it's the opaque id segment in the URL.
165
- - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes output.`,resolve(){let n=pi();if(!n)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:[n,"../dist/figma.js","figmaSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"figma_get_me":{let t=await ve("/v1/me");return JSON.stringify({id:t.id,handle:t.handle,email:t.email,imgUrl:t.img_url})}case"figma_get_file":{let{fileKey:t,depth:r}=e||{};if(!t)return JSON.stringify({error:"fileKey is required"});let s=`/v1/files/${encodeURIComponent(t)}`;if(r!=null){let a=Number(r);!Number.isNaN(a)&&a>0&&(s+=`?depth=${a}`)}let i=await ve(s),o=(i.document?.children||[]).map(a=>({id:a.id,name:a.name,type:a.type,childCount:Array.isArray(a.children)?a.children.length:0,children:(a.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:i.name,lastModified:i.lastModified,version:i.version,editorType:i.editorType,role:i.role,pages:o})}case"figma_get_nodes":{let{fileKey:t,ids:r,depth:s}=e||{};if(!t)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;if(a.set("ids",o.join(",")),s!=null){let l=Number(s);!Number.isNaN(l)&&l>0&&a.set("depth",String(l))}let c=await ve(`/v1/files/${encodeURIComponent(t)}/nodes?${a.toString()}`),d={};for(let[l,u]of Object.entries(c.nodes||{}))d[l]=u?.document?{id:u.document.id,name:u.document.name,type:u.document.type,document:u.document}:u;return JSON.stringify({name:c.name,nodes:d})}case"figma_render_png":{let{fileKey:t,ids:r,scale:s}=e||{};if(!t)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;a.set("ids",o.join(",")),a.set("format","png");let c=Number(s);(Number.isNaN(c)||c<=0)&&(c=1),c=Math.min(4,Math.max(.01,c)),a.set("scale",String(c));let d=await ve(`/v1/images/${encodeURIComponent(t)}?${a.toString()}`);return d.err?JSON.stringify({error:`Figma render error: ${d.err}`}):JSON.stringify({scale:c,format:"png",images:d.images||{}})}case"figma_get_comments":{let{fileKey:t}=e||{};if(!t)return JSON.stringify({error:"fileKey is required"});let s=((await ve(`/v1/files/${encodeURIComponent(t)}/comments`)).comments||[]).map(i=>({id:i.id,message:i.message,user:i.user?.handle,createdAt:i.created_at,resolvedAt:i.resolved_at||null,parentId:i.parent_id||null}));return JSON.stringify({count:s.length,comments:s})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 by fileKey (the opaque id segment in a figma.com/file/<fileKey>/ or /design/<fileKey>/ URL \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'The file key from the Figma URL (e.g. "aBcD1234" in figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch (e.g. ["1:23","4:56"]). A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to PNG and return the image URLs (a map of nodeId \u2192 URL). Use this to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (e.g. ["1:23"]). A comma-separated string is also accepted.'},scale:{type:"number",description:"Render scale, 0.01\u20134 (default 1). 2 for retina/hi-dpi."}},required:["fileKey","ids"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"}},required:["fileKey"]}}]};import{existsSync as mi}from"fs";import{fileURLToPath as fi}from"url";import{dirname as hi,resolve as yi}from"path";function gi(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=hi(fi(import.meta.url)),e=yi(n,"..","bin","mcp-skill.mjs");return mi(e)?e:null}var _i=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function bi(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let n=process.env.LINEAR_API_KEY;if(!n)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return n}async function M(n,e={}){let t=await fetch(_i,{method:"POST",headers:{Authorization:bi(),"Content-Type":"application/json"},body:JSON.stringify({query:n,variables:e})});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Linear API ${t.status}: ${s.slice(0,300)}`)}let r=await t.json().catch(()=>null);if(!r)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(r.errors)&&r.errors.length){let s=r.errors.map(i=>i?.message||String(i)).join("; ");throw new Error(`Linear GraphQL error: ${s.slice(0,300)}`)}return r.data}function Oe(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function ki(n,e){let t=Oe(n),r=Oe(e);if(!t||!r)return 0;if(t===r)return 1;if(t.length===1||r.length===1)return t===r?1:0;let s=l=>{let u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},i=s(t),o=s(r),a=0,c=0,d=0;for(let l of i.values())c+=l;for(let l of o.values())d+=l;for(let[l,u]of i.entries())a+=Math.min(u,o.get(l)||0);return 2*a/Math.max(1,c+d)}function wi(n,e){let t=Array.isArray(n)?n:[];if(!t.length)return{state:null,strategy:"no-states"};let r=Oe(e);if(!r)return{state:null,strategy:"no-target"};let s=t.find(a=>Oe(a.name)===r);if(s)return{state:s,strategy:"exact"};let i={backlog:["backlog"],unstarted:["todo","unstarted","open"],started:["inprogress","started","doing","wip"],completed:["done","completed","closed","resolved","fixed"],canceled:["canceled","cancelled","wontfix","won'tfix"],triage:["triage"]};for(let[a,c]of Object.entries(i)){if(!c.some(l=>Oe(l)===r))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:ki(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 Si=`
165
+ - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes output.`,resolve(){let r=Bs();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 Pe("/v1/me");return JSON.stringify({id:t.id,handle:t.handle,email:t.email,imgUrl:t.img_url})}case"figma_get_file":{let{fileKey:t,depth:n}=e||{};if(!t)return JSON.stringify({error:"fileKey is required"});let i=`/v1/files/${encodeURIComponent(t)}`;if(n!=null){let a=Number(n);!Number.isNaN(a)&&a>0&&(i+=`?depth=${a}`)}let s=await Pe(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{fileKey:t,ids:n,depth:i}=e||{};if(!t)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(n)?n:n?String(n).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;if(a.set("ids",o.join(",")),i!=null){let l=Number(i);!Number.isNaN(l)&&l>0&&a.set("depth",String(l))}let c=await Pe(`/v1/files/${encodeURIComponent(t)}/nodes?${a.toString()}`),d={};for(let[l,u]of Object.entries(c.nodes||{}))d[l]=u?.document?{id:u.document.id,name:u.document.name,type:u.document.type,document:u.document}:u;return JSON.stringify({name:c.name,nodes:d})}case"figma_render_png":{let{fileKey:t,ids:n,scale:i}=e||{};if(!t)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(n)?n:n?String(n).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;a.set("ids",o.join(",")),a.set("format","png");let c=Number(i);(Number.isNaN(c)||c<=0)&&(c=1),c=Math.min(4,Math.max(.01,c)),a.set("scale",String(c));let d=await Pe(`/v1/images/${encodeURIComponent(t)}?${a.toString()}`);return d.err?JSON.stringify({error:`Figma render error: ${d.err}`}):JSON.stringify({scale:c,format:"png",images:d.images||{}})}case"figma_get_comments":{let{fileKey:t}=e||{};if(!t)return JSON.stringify({error:"fileKey is required"});let i=((await Pe(`/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})}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 by fileKey (the opaque id segment in a figma.com/file/<fileKey>/ or /design/<fileKey>/ URL \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'The file key from the Figma URL (e.g. "aBcD1234" in figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch (e.g. ["1:23","4:56"]). A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to PNG and return the image URLs (a map of nodeId \u2192 URL). Use this to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (e.g. ["1:23"]). A comma-separated string is also accepted.'},scale:{type:"number",description:"Render scale, 0.01\u20134 (default 1). 2 for retina/hi-dpi."}},required:["fileKey","ids"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"}},required:["fileKey"]}}]};import{existsSync as Ms}from"fs";import{fileURLToPath as Gs}from"url";import{dirname as Ks,resolve as Fs}from"path";function Hs(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ks(Gs(import.meta.url)),e=Fs(r,"..","bin","mcp-skill.mjs");return Ms(e)?e:null}var zs=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Ys(){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 F(r,e={}){let t=await fetch(zs,{method:"POST",headers:{Authorization:Ys(),"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 Ue(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ws(r,e){let t=Ue(r),n=Ue(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 u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},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,u]of s.entries())a+=Math.min(u,o.get(l)||0);return 2*a/Math.max(1,c+d)}function Zs(r,e){let t=Array.isArray(r)?r:[];if(!t.length)return{state:null,strategy:"no-states"};let n=Ue(e);if(!n)return{state:null,strategy:"no-target"};let i=t.find(a=>Ue(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=>Ue(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:Ws(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 Vs=`
166
166
  id
167
167
  identifier
168
168
  number
@@ -176,7 +176,7 @@ You have read access to the user's Figma files via the Figma REST API. Tools:
176
176
  assignee { id name displayName email }
177
177
  labels { nodes { id name color } }
178
178
  team { id key name }
179
- `,or={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)
179
+ `,Ir={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:N.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear (connected)
180
180
  You have direct access to the user's Linear workspace (GraphQL API). Tools:
181
181
 
182
182
  ### Discovery
@@ -194,32 +194,32 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
194
194
 
195
195
  ### Notes
196
196
  - Always resolve a team first when you need states or want to create/move issues by state name \u2014 states only make sense within their team.
197
- - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let n={};for(let t of this.envKeys)process.env[t]&&(n[t]=process.env[t]);process.env.LINEAR_API_URL&&(n.LINEAR_API_URL=process.env.LINEAR_API_URL);let e=gi();return e?{type:"stdio",command:"node",args:[e,"../dist/linear.js","linearSkill"],env:n,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:n,description:this.description}},async handleToolCall(n,e){try{switch(n){case"linear_list_teams":{let r=(await M(`
197
+ - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let 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=Hs();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 F(`
198
198
  query Teams($first: Int) {
199
199
  teams(first: $first) {
200
200
  nodes { id key name description }
201
201
  }
202
202
  }
203
- `,{first:e?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:r.length,teams:r})}case"linear_list_states":{let{teamId:t,teamKey:r}=e||{},s=t;if(!s&&r&&(s=await ir(r)),s){let c=(await M(`
203
+ `,{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 Sr(n)),i){let c=(await F(`
204
204
  query States($teamId: String!) {
205
205
  team(id: $teamId) {
206
206
  id key name
207
207
  states { nodes { id name type color position } }
208
208
  }
209
209
  }
210
- `,{teamId:s}))?.team,d=(c?.states?.nodes||[]).slice().sort((l,u)=>(l.position||0)-(u.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:d.length,states:d})}let o=(await M(`
210
+ `,{teamId:i}))?.team,d=(c?.states?.nodes||[]).slice().sort((l,u)=>(l.position||0)-(u.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:d.length,states:d})}let o=(await F(`
211
211
  query AllStates($first: Int) {
212
212
  workflowStates(first: $first) {
213
213
  nodes { id name type color team { id key name } }
214
214
  }
215
215
  }
216
- `,{first:e?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:t}=e||{},s=(await M(`
216
+ `,{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 F(`
217
217
  query Labels($first: Int, $filter: IssueLabelFilter) {
218
218
  issueLabels(first: $first, filter: $filter) {
219
219
  nodes { id name color team { id key } }
220
220
  }
221
221
  }
222
- `,{first:e?.limit||100,filter:t?{team:{id:{eq:t}}}:void 0}))?.issueLabels?.nodes||[];return JSON.stringify({count:s.length,labels:s})}case"linear_list_issues":{let{teamId:t,teamKey:r,stateId:s,stateName:i,label:o,assigneeId:a,updatedAfter:c,limit:d}=e||{},l={},u=t;!u&&r&&(u=await ir(r)),u&&(l.team={id:{eq:u}}),s?l.state={id:{eq:s}}:i&&(l.state={name:{eqIgnoreCase:i}}),o&&(l.labels={name:{eqIgnoreCase:o}}),a&&(l.assignee={id:{eq:a}}),c&&(l.updatedAt={gt:c});let m=((await M(`
222
+ `,{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={},u=t;!u&&n&&(u=await Sr(n)),u&&(l.team={id:{eq:u}}),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 F(`
223
223
  query Issues($first: Int, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
224
224
  issues(first: $first, filter: $filter, orderBy: $orderBy) {
225
225
  nodes {
@@ -231,57 +231,57 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
231
231
  }
232
232
  }
233
233
  }
234
- `,{first:d||30,filter:Object.keys(l).length?l:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(f=>({id:f.id,identifier:f.identifier,number:f.number,title:f.title,url:f.url,priority:f.priority,state:f.state?.name,stateType:f.state?.type,assignee:f.assignee?.displayName||null,labels:(f.labels?.nodes||[]).map(h=>h.name),team:f.team?.key,createdAt:f.createdAt,updatedAt:f.updatedAt}));return JSON.stringify({count:m.length,issues:m})}case"linear_get_issue":{let t=e?.issueId||e?.identifier||e?.issueKey;if(!t)return JSON.stringify({error:"issueId or identifier is required"});let r=await Ne(t);return JSON.stringify(r?{id:r.id,identifier:r.identifier,number:r.number,title:r.title,description:r.description||"",url:r.url,priority:r.priority,state:r.state?.name,stateId:r.state?.id,stateType:r.state?.type,assignee:r.assignee?.displayName||r.assignee?.name||null,assigneeId:r.assignee?.id||null,labels:(r.labels?.nodes||[]).map(s=>s.name),team:r.team?{id:r.team.id,key:r.team.key,name:r.team.name}:null,createdAt:r.createdAt,updatedAt:r.updatedAt}:{error:`Issue not found: ${t}`})}case"linear_get_comments":{let t=e?.issueId||e?.identifier||e?.issueKey;if(!t)return JSON.stringify({error:"issueId or identifier is required"});let r=await Ne(t,`
234
+ `,{first:d||30,filter:Object.keys(l).length?l:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(f=>({id:f.id,identifier:f.identifier,number:f.number,title:f.title,url:f.url,priority:f.priority,state:f.state?.name,stateType:f.state?.type,assignee:f.assignee?.displayName||null,labels:(f.labels?.nodes||[]).map(h=>h.name),team:f.team?.key,createdAt:f.createdAt,updatedAt:f.updatedAt}));return JSON.stringify({count:m.length,issues:m})}case"linear_get_issue":{let t=e?.issueId||e?.identifier||e?.issueKey;if(!t)return JSON.stringify({error:"issueId or identifier is required"});let n=await Ce(t);return JSON.stringify(n?{id:n.id,identifier:n.identifier,number:n.number,title:n.title,description:n.description||"",url:n.url,priority:n.priority,state:n.state?.name,stateId:n.state?.id,stateType:n.state?.type,assignee:n.assignee?.displayName||n.assignee?.name||null,assigneeId:n.assignee?.id||null,labels:(n.labels?.nodes||[]).map(i=>i.name),team:n.team?{id:n.team.id,key:n.team.key,name:n.team.name}:null,createdAt:n.createdAt,updatedAt:n.updatedAt}:{error:`Issue not found: ${t}`})}case"linear_get_comments":{let t=e?.issueId||e?.identifier||e?.issueKey;if(!t)return JSON.stringify({error:"issueId or identifier is required"});let n=await Ce(t,`
235
235
  id identifier
236
236
  comments(first: ${Number(e?.limit)||50}) {
237
237
  nodes { id body createdAt updatedAt user { id name displayName } }
238
238
  }
239
- `);if(!r)return JSON.stringify({error:`Issue not found: ${t}`});let s=(r.comments?.nodes||[]).map(i=>({id:i.id,author:i.user?.displayName||i.user?.name||"Unknown",body:i.body||"",createdAt:i.createdAt,updatedAt:i.updatedAt})).sort((i,o)=>String(o.createdAt).localeCompare(String(i.createdAt)));return JSON.stringify({count:s.length,issue:r.identifier,comments:s})}case"linear_add_comment":{let t=e?.issueId||e?.identifier||e?.issueKey,r=e?.body;if(!t||!r)return JSON.stringify({error:"issueId/identifier and body are required"});let s=await Ne(t,"id identifier");if(!s)return JSON.stringify({error:`Issue not found: ${t}`});let o=(await M(`
239
+ `);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 Ce(t,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${t}`});let o=(await F(`
240
240
  mutation AddComment($input: CommentCreateInput!) {
241
241
  commentCreate(input: $input) {
242
242
  success
243
243
  comment { id url createdAt }
244
244
  }
245
245
  }
246
- `,{input:{issueId:s.id,body:r}}))?.commentCreate;return JSON.stringify({ok:!!o?.success,commentId:o?.comment?.id,url:o?.comment?.url})}case"linear_update_state":{let t=e?.issueId||e?.identifier||e?.issueKey,{stateId:r,stateName:s,toStatus:i,status:o}=e||{};if(!t)return JSON.stringify({error:"issueId or identifier is required"});let a=await Ne(t,`
246
+ `,{input:{issueId:i.id,body:n}}))?.commentCreate;return JSON.stringify({ok:!!o?.success,commentId:o?.comment?.id,url:o?.comment?.url})}case"linear_update_state":{let t=e?.issueId||e?.identifier||e?.issueKey,{stateId:n,stateName:i,toStatus:s,status:o}=e||{};if(!t)return JSON.stringify({error:"issueId or identifier is required"});let a=await Ce(t,`
247
247
  id identifier
248
248
  state { id name type }
249
249
  team { id key states { nodes { id name type position } } }
250
- `);if(!a)return JSON.stringify({error:`Issue not found: ${t}`});let c=r,d=r?{strategy:"explicit-id"}:null;if(!c){let p=String(s||i||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((h,_)=>(h.position||0)-(_.position||0));if(!p)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});let f=wi(m,p);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${p}" in team ${a.team?.key}`,issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});c=f.state.id,d={strategy:f.strategy,matchedName:f.state.name}}let u=(await M(`
250
+ `);if(!a)return JSON.stringify({error:`Issue not found: ${t}`});let c=n,d=n?{strategy:"explicit-id"}:null;if(!c){let p=String(i||s||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((h,y)=>(h.position||0)-(y.position||0));if(!p)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});let f=Zs(m,p);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${p}" in team ${a.team?.key}`,issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});c=f.state.id,d={strategy:f.strategy,matchedName:f.state.name}}let u=(await F(`
251
251
  mutation MoveIssue($id: String!, $input: IssueUpdateInput!) {
252
252
  issueUpdate(id: $id, input: $input) {
253
253
  success
254
254
  issue { id identifier state { id name type } }
255
255
  }
256
256
  }
257
- `,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!u?.success,issue:u?.issue?.identifier||a.identifier,stateAfter:u?.issue?.state?.name||null,stateTypeAfter:u?.issue?.state?.type||null,resolution:d})}case"linear_link_attachment":{let t=e?.issueId||e?.identifier||e?.issueKey,{url:r,title:s,subtitle:i}=e||{};if(!t||!r)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await Ne(t,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${t}`});let c=(await M(`
257
+ `,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!u?.success,issue:u?.issue?.identifier||a.identifier,stateAfter:u?.issue?.state?.name||null,stateTypeAfter:u?.issue?.state?.type||null,resolution:d})}case"linear_link_attachment":{let 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 Ce(t,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${t}`});let c=(await F(`
258
258
  mutation LinkAttachment($input: AttachmentCreateInput!) {
259
259
  attachmentCreate(input: $input) {
260
260
  success
261
261
  attachment { id url title }
262
262
  }
263
263
  }
264
- `,{input:{issueId:o.id,url:r,title:s||r,subtitle:i||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 ir(n){return(await M(`
264
+ `,{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 Sr(r){return(await F(`
265
265
  query TeamByKey($filter: TeamFilter) {
266
266
  teams(first: 1, filter: $filter) { nodes { id key } }
267
267
  }
268
- `,{filter:{key:{eq:n}}}))?.teams?.nodes?.[0]?.id||null}async function Ne(n,e=Si){let t=String(n).trim(),r=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(t);if(r){let i=r[1].toUpperCase(),o=Number(r[2]);return(await M(`
268
+ `,{filter:{key:{eq:r}}}))?.teams?.nodes?.[0]?.id||null}async function Ce(r,e=Vs){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 F(`
269
269
  query IssueByIdentifier($filter: IssueFilter) {
270
270
  issues(first: 1, filter: $filter) {
271
271
  nodes { ${e} }
272
272
  }
273
273
  }
274
- `,{filter:{number:{eq:o},team:{key:{eq:i}}}}))?.issues?.nodes?.[0]||null}return(await M(`
274
+ `,{filter:{number:{eq:o},team:{key:{eq:s}}}}))?.issues?.nodes?.[0]||null}return(await F(`
275
275
  query IssueById($id: String!) {
276
276
  issue(id: $id) { ${e} }
277
277
  }
278
- `,{id:t}))?.issue||null}var ar={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)
278
+ `,{id:t}))?.issue||null}var vr={id:"plane",serverName:"plane",allowedTools:["mcp__plane__*"],requiresIntegration:N.PLANE,envKeys:["PLANE_API_KEY","PLANE_WORKSPACE_SLUG","PLANE_BASE_URL"],description:"Plane \u2014 projects, work items, cycles, modules, epics, comments (official MCP, API key)",tools:[],promptFragment:`## Plane (connected)
279
279
  You have direct access to the user's Plane workspace via the official Plane MCP server. All Plane tools are available under the mcp__plane__* namespace \u2014 use them proactively to read and write projects, work items (issues), cycles, modules, epics, sub-issues, comments, labels, states, pages, and workspace data.
280
280
 
281
281
  - List/get projects and work items, then create/update/delete or search work items as needed.
282
282
  - For status changes, read the project's available states first, then set the work item's state.
283
283
  - Cycles and modules group work items \u2014 list them to scope queries before drilling into items.
284
- - Always operate within the connected workspace; the workspace slug and base URL are pre-configured (Plane Cloud, self-hosted, or Zibby-hosted all work transparently).`,resolve(){let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);return{type:"stdio",command:"uvx",args:["plane-mcp-server","stdio"],env:n,description:this.description}}};import{existsSync as Ii}from"fs";import{fileURLToPath as vi}from"url";import{dirname as Ni,resolve as Oi}from"path";import{resolveIntegrationToken as Ri}from"@zibby/core/backend-client.js";function Ti(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Ni(vi(import.meta.url)),e=Oi(n,"..","bin","mcp-skill.mjs");return Ii(e)?e:null}async function cr(){let n=await Ri(v.OPEN_DESIGN),e=n?.token,t=n?.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 r=t.replace(/\/+$/,"");return{token:e,baseUrl:r}}async function re(n,e={}){let{token:t,baseUrl:r}=await cr(),s=`${r}/api${n}`;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&&(s+=(s.includes("?")?"&":"?")+c)}let i={Authorization:`Bearer ${t}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},o=await fetch(s,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});return lr(o,"OpenDesign")}async function lr(n,e){if(!n.ok){let r=await n.text().catch(()=>""),s=r.slice(0,300);try{let i=JSON.parse(r),o=i?.code||i?.error?.code,a=i?.message||i?.error?.message||i?.error;(o||a)&&(s=[o?`[${o}]`:null,a].filter(Boolean).join(" ")||s)}catch{}throw new Error(`${e} API ${n.status}: ${s}`)}let t=await n.text().catch(()=>"");if(!t)return{};try{return JSON.parse(t)}catch{return{raw:t}}}var dr={id:"open-design",serverName:"opendesign",allowedTools:["mcp__opendesign__*"],envKeys:[],description:"OpenDesign \u2014 list projects/designs, run the design agent, and export decks to PDF/HTML",promptFragment:`## OpenDesign (optional)
284
+ - Always operate within the connected workspace; the workspace slug and base URL are pre-configured (Plane Cloud, self-hosted, or Zibby-hosted all work transparently).`,resolve(){let 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 Qs}from"fs";import{fileURLToPath as Xs}from"url";import{dirname as eo,resolve as to}from"path";import{resolveIntegrationToken as ro}from"@zibby/core/backend-client.js";function no(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=eo(Xs(import.meta.url)),e=to(r,"..","bin","mcp-skill.mjs");return Qs(e)?e:null}async function Nr(){let r=await ro(N.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 oe(r,e={}){let{token:t,baseUrl:n}=await Nr(),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 Or(o,"OpenDesign")}async function Or(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 Rr={id:"open-design",serverName:"opendesign",allowedTools:["mcp__opendesign__*"],envKeys:[],description:"OpenDesign \u2014 list projects/designs, run the design agent, and export decks to PDF/HTML",promptFragment:`## OpenDesign (optional)
285
285
  You may have access to the user's OpenDesign workspace (the Zibby-managed design/deck app) via its REST API. These tools are OPTIONAL \u2014 if OpenDesign is not connected they will return a "not connected" error; reach for them only when the task involves OpenDesign projects, designs, or exports. Tools (mcp__opendesign__*):
286
286
 
287
287
  ### Connectivity
@@ -303,30 +303,30 @@ You may have access to the user's OpenDesign workspace (the Zibby-managed design
303
303
 
304
304
  ### Notes
305
305
  - A design artifact lookup ALWAYS needs its projectId (it scopes the query).
306
- - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let n=Ti();if(!n)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:[n,"../dist/opendesign.js","opendesignSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"opendesign_health":{let{baseUrl:t}=await cr(),r=await fetch(`${t}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),s=await lr(r,"OpenDesign");return JSON.stringify({ok:!0,health:s})}case"opendesign_list_projects":{let t=await re("/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 r=await re(`/projects/${encodeURIComponent(t)}`);return JSON.stringify(r)}case"opendesign_list_designs":{let t=e?.projectId;if(!t)return JSON.stringify({error:"projectId is required"});let r=await re("/live-artifacts",{query:{projectId:t}});return JSON.stringify(r)}case"opendesign_get_design":{let t=e?.id,r=e?.projectId;if(!t)return JSON.stringify({error:"id is required"});if(!r)return JSON.stringify({error:"projectId is required"});let s=await re(`/live-artifacts/${encodeURIComponent(t)}`,{query:{projectId:r}});return JSON.stringify(s)}case"opendesign_export_pdf":{let t=e?.projectId||e?.id,{fileName:r,title:s,deck:i}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"fileName is required"});let o={fileName:r};s!==void 0&&(o.title=s),i!==void 0&&(o.deck=i);let a=await re(`/projects/${encodeURIComponent(t)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(a)}case"opendesign_export_html":{let t=e?.projectId||e?.id,r=e?.path;if(!t)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"path is required (the export sub-path)"});let i=String(r).replace(/^\/+/,"").split("/").map(a=>encodeURIComponent(a)).join("/"),o=await re(`/projects/${encodeURIComponent(t)}/export/${i}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:t,message:r,projectId:s,conversationId:i,model:o}=e||{};if(!t)return JSON.stringify({error:"agentId is required"});if(!r)return JSON.stringify({error:"message is required"});let a={agentId:t,message:r};s!==void 0&&(a.projectId=s),i!==void 0&&(a.conversationId=i),o!==void 0&&(a.model=o);let c=await re("/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 r=await re(`/runs/${encodeURIComponent(t)}`);return JSON.stringify(r)}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 Ai}from"fs";import{fileURLToPath as Ei}from"url";import{dirname as xi,resolve as Li}from"path";import{resolveIntegrationToken as $i}from"@zibby/core/backend-client.js";function ji(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let n=xi(Ei(import.meta.url)),e=Li(n,"..","bin","mcp-slack.mjs");return Ai(e)?e:null}async function J(n,e={}){let{token:t}=await $i("slack"),r=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(n),s=`https://slack.com/api/${n}`,i={Authorization:`Bearer ${t}`},o;if(r){let d=new URLSearchParams(e).toString();d&&(s+=`?${d}`)}else i["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(e);let c=await(await fetch(s,{method:r?"GET":"POST",headers:i,body:o})).json();if(!c.ok)throw new Error(`Slack API error: ${c.error}`);return c}var j={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:v.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
306
+ - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let r=no();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 Nr(),n=await fetch(`${t}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),i=await Or(n,"OpenDesign");return JSON.stringify({ok:!0,health:i})}case"opendesign_list_projects":{let t=await oe("/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 oe(`/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 oe("/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 oe(`/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 oe(`/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 oe(`/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 oe("/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 oe(`/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 io}from"fs";import{fileURLToPath as so}from"url";import{dirname as oo,resolve as ao}from"path";import{resolveIntegrationToken as co}from"@zibby/core/backend-client.js";function lo(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let r=oo(so(import.meta.url)),e=ao(r,"..","bin","mcp-slack.mjs");return io(e)?e:null}async function M(r,e={}){let{token:t}=await co("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 P={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:N.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
307
307
  You have access to the user's Slack workspace. Use these tools:
308
308
  - slack_list_channels, slack_post_message, slack_reply_to_thread
309
309
  - slack_add_reaction, slack_get_channel_history, slack_get_thread_replies
310
310
  - slack_get_users, slack_get_user_profile
311
311
  - slack_lookup_user_by_email (precise email\u2192user_id, prefer this over scanning slack_get_users)
312
- - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let n=ji();if(!n)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:[n],env:e,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"slack_list_channels":{let t=await J("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(t.channels||[]).map(r=>({id:r.id,name:r.name,topic:r.topic?.value}))})}case"slack_post_message":{if(!e.channel||!e.text)return JSON.stringify({error:"channel and text are required"});let t=await J("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 J("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 J("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 J("conversations.history",{channel:e.channel,limit:e.limit||20});return JSON.stringify({messages:(t.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.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 J("conversations.replies",{channel:e.channel,ts:e.thread_ts});return JSON.stringify({messages:(t.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.ts}))})}case"slack_get_users":{let t=await J("users.list",{limit:100});return JSON.stringify({users:(t.members||[]).filter(r=>!r.is_bot&&!r.deleted).map(r=>({id:r.id,name:r.real_name||r.name}))})}case"slack_get_user_profile":{if(!e.user_id)return JSON.stringify({error:"user_id is required"});let t=await J("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 J("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 J("usergroups.list",{});return JSON.stringify({usergroups:(t.usergroups||[]).map(r=>({id:r.id,handle:r.handle,name:r.name,description:r.description||"",user_count:Number(r.user_count||0)}))})}case"slack_get_usergroup_members":{if(!e.usergroup)return JSON.stringify({error:"usergroup id is required"});let t=await J("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 r=Math.max(1,Math.min(Number(e.limit)||5,25)),s=[],i,o=5;for(let c=0;c<o;c+=1){let d={limit:200};i&&(d.cursor=i);let l=await J("users.list",d);for(let u of l.members||[])u.deleted||u.is_bot||s.push(u);if(i=l.response_metadata?.next_cursor,!i)break}let a=[];for(let c of s){let d=(c.real_name||"").toLowerCase(),l=(c.profile?.display_name||"").toLowerCase(),u=(c.name||"").toLowerCase(),p=0;d.includes(t)&&(p+=100-Math.abs(d.length-t.length)),l.includes(t)&&(p+=60-Math.abs(l.length-t.length)),u.includes(t)&&(p+=30-Math.abs(u.length-t.length)),(d===t||l===t)&&(p+=200),p>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:p})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,r).map(({_score:c,...d})=>d),scanned:s.length})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 Pi}from"fs";import{fileURLToPath as Ci}from"url";import{dirname as Ui,resolve as qi}from"path";import{resolveIntegrationToken as Di}from"@zibby/core/backend-client.js";function Ji(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let n=Ui(Ci(import.meta.url)),e=qi(n,"..","bin","mcp-lark.mjs");return Pi(e)?e:null}var Bi=6e3*1e3,Re=null;async function Mi(){let{appId:n,appSecret:e,host:t}=await Di("lark");if(Re&&Re.appId===n&&Re.expiresAt>Date.now())return{token:Re.token,host:t};let s=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:n,app_secret:e})})).json();if(s.code!==0)throw new Error(`Lark tenant_access_token failed: ${s.msg||s.code}`);return Re={token:s.tenant_access_token,expiresAt:Date.now()+Bi,appId:n},{token:s.tenant_access_token,host:t}}async function oe(n,e,t={}){let{token:r,host:s}=await Mi(),i=`${s}${e}`,o={method:n,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}};n!=="GET"&&(o.body=JSON.stringify(t));let c=await(await fetch(i,o)).json();if(c.code!==0)throw new Error(`Lark API ${e} error: ${c.msg||c.code}`);return c.data||{}}function ur(n){return JSON.stringify({text:n})}function Gi(n){return!n||typeof n!="string"||n.startsWith("oc_")?"chat_id":n.startsWith("ou_")?"open_id":n.startsWith("on_")?"union_id":n.startsWith("cli_")?"app_id":n.includes("@")?"email":"chat_id"}var K={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:v.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
312
+ - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=lo();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 M("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 M("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 M("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 M("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 M("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 M("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 M("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 M("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 M("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 M("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 M("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 M("users.list",d);for(let u of l.members||[])u.deleted||u.is_bot||i.push(u);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(),u=(c.name||"").toLowerCase(),p=0;d.includes(t)&&(p+=100-Math.abs(d.length-t.length)),l.includes(t)&&(p+=60-Math.abs(l.length-t.length)),u.includes(t)&&(p+=30-Math.abs(u.length-t.length)),(d===t||l===t)&&(p+=200),p>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:p})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,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 uo}from"fs";import{fileURLToPath as po}from"url";import{dirname as mo,resolve as fo}from"path";import{resolveIntegrationToken as ho}from"@zibby/core/backend-client.js";function go(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=mo(po(import.meta.url)),e=fo(r,"..","bin","mcp-lark.mjs");return uo(e)?e:null}var yo=6e3*1e3,De=null;async function _o(){let{appId:r,appSecret:e,host:t}=await ho("lark");if(De&&De.appId===r&&De.expiresAt>Date.now())return{token:De.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 De={token:i.tenant_access_token,expiresAt:Date.now()+yo,appId:r},{token:i.tenant_access_token,host:t}}async function ue(r,e,t={}){let{token:n,host:i}=await _o(),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 Tr(r){return JSON.stringify({text:r})}function bo(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 z={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:N.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
313
313
  You can send messages and replies on Lark. Use:
314
314
  - lark_send_message: post a message to a chat, user, or DM
315
315
  - lark_reply: reply to an existing message (threaded)
316
316
  - lark_list_chats: list chats the bot is a member of
317
317
  - lark_get_chat_history: fetch recent messages in a chat
318
318
  - lark_lookup_user_by_email: resolve an email \u2192 open_id for direct DM (prefer this over emailing through lark_send_message when the agent has a user_id already)
319
- When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let n=Ji();if(!n)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:[n],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(n,e){try{switch(n){case"lark_send_message":{if(!e.receive_id||!e.text)return JSON.stringify({error:"receive_id and text are required"});let t=Gi(e.receive_id),r=await oe("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:ur(e.text)});return JSON.stringify({ok:!0,message_id:r.message_id})}case"lark_reply":{if(!e.message_id||!e.text)return JSON.stringify({error:"message_id and text are required"});let t=await oe("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:ur(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,s=((await oe("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(i=>({chat_id:i.chat_id,name:i.name,description:i.description,owner_id:i.owner_id,chat_mode:i.chat_mode}));return JSON.stringify({chats:s})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,s=((await oe("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(i=>({message_id:i.message_id,sender_id:i.sender?.id,sender_type:i.sender?.sender_type,msg_type:i.msg_type,content:i.body?.content,create_time:i.create_time}));return JSON.stringify({messages:s})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let r=((await oe("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(s=>s.email===e.email&&s.user_id);return JSON.stringify(r?{ok:!0,user:{open_id:r.user_id,email:r.email,name:r.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!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 r=Math.max(1,Math.min(Number(e.limit)||5,25)),s=200,o=((await oe("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>=s)break;try{let u=await oe("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let p of u.items||[])if(!(!p.member_id||a.has(p.member_id))&&(a.add(p.member_id),c.push({open_id:p.member_id,name:p.name||""}),c.length>=s))break}catch(u){console.warn(`[lark] member scan failed for ${l}: ${u.message}`)}}let d=[];for(let l of c){let u=(l.name||"").toLowerCase();if(!u)continue;let p=0;u.includes(t)&&(p+=100-Math.abs(u.length-t.length)),u===t&&(p+=200),p>0&&d.push({open_id:l.open_id,name:l.name,_score:p})}return d.sort((l,u)=>u._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,r).map(({_score:l,...u})=>u),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}catch(t){return JSON.stringify({error:t.message})}}};import{existsSync as Ki}from"fs";import{fileURLToPath as Fi}from"url";import{dirname as Hi,resolve as zi}from"path";import{resolveIntegrationToken as Yi}from"@zibby/core/backend-client.js";function Wi(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Hi(Fi(import.meta.url)),e=zi(n,"..","bin","mcp-skill.mjs");return Ki(e)?e:null}var Zi=process.env.DISCORD_API_URL||"https://discord.com/api/v10",Vi=2e3;function Qi(n,e=Vi){let t=String(n??"");if(!t.trim())return[];if(t.length<=e)return[t];let r=[],s=t;for(;s.length>e;){let o=s.slice(0,e).lastIndexOf(`
320
- `),a=o>e/2?o+1:e;r.push(s.slice(0,a)),s=s.slice(a)}return s&&r.push(s),r}async function pr(){let n=(process.env.DISCORD_BOT_TOKEN||"").trim();if(n)return{token:n,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await Yi(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(n,e,{token:t,body:r}={}){let s=t.startsWith("Bot ")?t:`Bot ${t}`,i=await fetch(`${Zi}${e}`,{method:n,headers:{Authorization:s,...r!==void 0?{"Content-Type":"application/json"}:{}},...r!==void 0?{body:JSON.stringify(r)}:{}}),o=await i.json().catch(()=>null);if(!i.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${i.status}`;throw new Error(`Discord API error (${i.status}): ${a}`)}return o}async function Xi({token:n,guildId:e},t){let r=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(r)return r;let s=await gt("GET","/users/@me/guilds",{token:n}),i=Array.isArray(s)?s:[];if(i.length===1)return i[0].id;if(i.length===0)throw new Error("The bot is not in any Discord server \u2014 invite it to a server first.");let o=i.slice(0,10).map(a=>`${a.name} (${a.id})`).join(", ");throw new Error(`The bot is in ${i.length} servers \u2014 pass guildId explicitly. Servers: ${o}`)}var mr={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)
319
+ When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=go();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=bo(e.receive_id),n=await ue("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:Tr(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 ue("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:Tr(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,i=((await ue("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 ue("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 ue("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 ue("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 u=await ue("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let p of u.items||[])if(!(!p.member_id||a.has(p.member_id))&&(a.add(p.member_id),c.push({open_id:p.member_id,name:p.name||""}),c.length>=i))break}catch(u){console.warn(`[lark] member scan failed for ${l}: ${u.message}`)}}let d=[];for(let l of c){let u=(l.name||"").toLowerCase();if(!u)continue;let p=0;u.includes(t)&&(p+=100-Math.abs(u.length-t.length)),u===t&&(p+=200),p>0&&d.push({open_id:l.open_id,name:l.name,_score:p})}return d.sort((l,u)=>u._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,n).map(({_score:l,...u})=>u),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}}};import{existsSync as ko}from"fs";import{fileURLToPath as wo}from"url";import{dirname as So,resolve as Io}from"path";import{resolveIntegrationToken as vo}from"@zibby/core/backend-client.js";function No(){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}var Oo=process.env.DISCORD_API_URL||"https://discord.com/api/v10",Ro=2e3;function To(r,e=Ro){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(`
320
+ `),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 Ar(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await vo(N.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 Tt(r,e,{token:t,body:n}={}){let i=t.startsWith("Bot ")?t:`Bot ${t}`,s=await fetch(`${Oo}${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 Ao({token:r,guildId:e},t){let n=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(n)return n;let i=await Tt("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 xr={id:"discord",serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:N.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord (connected)
321
321
  You can post to the user's Discord server as their bot. Tools:
322
322
  - discord_send_message(channelId, text) \u2014 post a message to a channel (long text is auto-chunked to Discord's 2000-char limit)
323
- - discord_list_channels(guildId?) \u2014 list the server's text channels (id + name) to find where to post; guildId is optional when the bot is in one server`,resolve(){let n={};for(let t of this.envKeys)process.env[t]&&(n[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]&&(n[t]=process.env[t]);let e=Wi();return e?{type:"stdio",command:"node",args:[e,"../dist/discord.js","discordSkill"],env:n,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:n,description:this.description}},async handleToolCall(n,e={}){try{switch(n){case"discord_send_message":{let t=String(e.channelId||"").trim(),r=String(e.text||"");if(!t||!r.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let s=await pr(),i=Qi(r),o=[];for(let a of i){let c=await gt("POST",`/channels/${encodeURIComponent(t)}/messages`,{token:s.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:t,messageIds:o,chunks:i.length})}case"discord_list_channels":{let t=await pr(),r=await Xi(t,e.guildId),s=await gt("GET",`/guilds/${encodeURIComponent(r)}/channels`,{token:t.token}),i=(Array.isArray(s)?s:[]).filter(o=>o&&(o.type===0||o.type===5)).map(o=>({id:o.id,name:o.name,type:o.type===5?"announcement":"text",...o.topic?{topic:o.topic}:{}}));return JSON.stringify({ok:!0,guildId:r,channels:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${n}`})}}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 br,statSync as eo,readFileSync as to}from"fs";import{fileURLToPath as ro}from"url";import{basename as no,dirname as so,resolve as io}from"path";import{resolveIntegrationToken as oo,clearTokenCache as ao}from"@zibby/core/backend-client.js";function co(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=so(ro(import.meta.url)),e=io(n,"..","bin","mcp-skill.mjs");return br(e)?e:null}var lo="2022-06-28",uo="https://api.notion.com/v1",Ge=2e4,fr=25,po=25,Ke=100,hr=500,mo=20*1024*1024;function V(n){if(!n||typeof n!="string")return null;let t=n.trim().split(/[?#]/)[0],r=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(r)return r[0].toLowerCase();let s=t.match(/[0-9a-fA-F]{32}/g);if(s&&s.length){let i=s[s.length-1].toLowerCase();return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}return null}async function F(n,e={}){let t=async()=>{let{token:r}=await oo("notion");if(typeof r!="string"||!r)throw new Error(`Invalid notion token type: ${typeof r}`);let s=await fetch(`${uo}${n}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${r}`,"Notion-Version":lo,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(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Notion API ${s.status}: ${o.slice(0,300)}`)}let i=await s.text().catch(()=>"");if(!i||!i.trim())return{};try{return JSON.parse(i)}catch{return{raw:i}}};try{return await t()}catch(r){let s=String(r?.message||r||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw r;return ao("notion"),t()}}function ge(n){if(!Array.isArray(n))return"";let e="";for(let t of n){let r=t?.plain_text??t?.text?.content??"";if(!r)continue;let s=t.annotations||{};s.code&&(r=`\`${r}\``),s.bold&&(r=`**${r}**`),s.italic&&(r=`_${r}_`),s.strikethrough&&(r=`~~${r}~~`);let i=t?.href||t?.text?.link?.url;i&&(r=`[${r}](${i})`),e+=r}return e}function fo(n,e,t){let r=n?.type,s=n?.[r]||{},i=" ".repeat(Math.max(0,e)),o=(d="rich_text")=>ge(s[d]),a;switch(r){case"paragraph":a=o();break;case"heading_1":a=`# ${o()}`;break;case"heading_2":a=`## ${o()}`;break;case"heading_3":a=`### ${o()}`;break;case"bulleted_list_item":a=`${i}- ${o()}`;break;case"numbered_list_item":a=`${i}1. ${o()}`;break;case"to_do":a=`${i}- [${s.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${i}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${s.icon?.emoji?`${s.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${s.language||""}
323
+ - discord_list_channels(guildId?) \u2014 list the server's text channels (id + name) to find where to post; guildId is optional when the bot is in one server`,resolve(){let 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=No();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 Ar(),s=To(n),o=[];for(let a of s){let c=await Tt("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 Ar(),n=await Ao(t,e.guildId),i=await Tt("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 Cr,statSync as xo,readFileSync as Eo}from"fs";import{fileURLToPath as Lo}from"url";import{basename as $o,dirname as jo,resolve as Po}from"path";import{resolveIntegrationToken as Co,clearTokenCache as Uo}from"@zibby/core/backend-client.js";function Do(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=jo(Lo(import.meta.url)),e=Po(r,"..","bin","mcp-skill.mjs");return Cr(e)?e:null}var qo="2022-06-28",Jo="https://api.notion.com/v1",et=2e4,Er=25,Bo=25,tt=100,Lr=500,Mo=20*1024*1024;function te(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 Y(r,e={}){let t=async()=>{let{token:n}=await Co("notion");if(typeof n!="string"||!n)throw new Error(`Invalid notion token type: ${typeof n}`);let i=await fetch(`${Jo}${r}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"Notion-Version":qo,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 Uo("notion"),t()}}function Oe(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 Go(r,e,t){let n=r?.type,i=r?.[n]||{},s=" ".repeat(Math.max(0,e)),o=(d="rich_text")=>Oe(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||""}
324
324
  ${o()}
325
- \`\`\``;break}case"divider":a="---";break;case"child_page":a=`[child page: ${s.title||""}]`;break;case"child_database":a=`[child database: ${s.title||""}]`;break;case"bookmark":case"embed":case"link_preview":a=s.url?`<${s.url}>`:"";break;case"equation":a=s.expression?`$${s.expression}$`:"";break;case"table":case"column_list":case"column":a="";break;case"table_row":{let d=(s.cells||[]).map(l=>ge(l).trim());a=`${i}| ${d.join(" | ")} |`;break}default:a=o();break}let c=[];return a&&a.trim()&&c.push(a),t&&t.trim()&&c.push(t),c.join(`
326
- `)}async function kr(n,e,t){let r=[],s,i=0;do{if(t.used>=Ge)break;let o=new URLSearchParams({page_size:"100"});s&&o.set("start_cursor",s);let a=await F(`/blocks/${n}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await kr(d.id,e+1,t));let u=fo(d,e,l);if(u&&(r.push(u),t.used+=u.length+1),t.used>=Ge)break}s=a.has_more?a.next_cursor:void 0,i+=1}while(s&&i<po);return r.join(`
327
- `)}function yr(n){let e=n?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let r=ge(t.title).trim();if(r)return r}return""}function Te(n){let e=String(n??"");if(!e)return[{type:"text",text:{content:""}}];let t=[];for(let r=0;r<e.length;r+=2e3)t.push({type:"text",text:{content:e.slice(r,r+2e3)}});return t}function ho(n){return{id:n?.id||"",discussionId:n?.discussion_id||"",text:ge(n?.rich_text).trim(),author:n?.created_by?.id||"",createdTime:n?.created_time||""}}function yo(n){if(!n||!n.type)return"";switch(n.type){case"title":return ge(n.title).trim();case"rich_text":return ge(n.rich_text).trim();case"number":return n.number==null?"":String(n.number);case"select":return n.select?.name||"";case"status":return n.status?.name||"";case"multi_select":return(n.multi_select||[]).map(t=>t.name).join(", ");case"checkbox":return n.checkbox?"true":"false";case"url":return n.url||"";case"email":return n.email||"";case"phone_number":return n.phone_number||"";case"date":return n.date?.start||"";case"people":return(n.people||[]).map(t=>t.name||t.id).join(", ");default:return""}}function _t(n){return`https://www.notion.so/${String(n||"").replace(/-/g,"")}`}function go(n){let e=String(n??"").replace(/\r\n/g,`
328
- `),t=[];for(let r of e.split(`
329
- `)){let s=r.replace(/\s+$/,"");if(!s.trim())continue;let i=/^(#{1,3})\s+(.*)$/.exec(s),o=/^\s*[-*]\s+(.*)$/.exec(s),a=/^\s*\d+[.)]\s+(.*)$/.exec(s),c,d;i?(c=`heading_${i[1].length}`,d=i[2]):o?(c="bulleted_list_item",d=o[1]):a?(c="numbered_list_item",d=a[1]):(c="paragraph",d=s),t.push({object:"block",type:c,[c]:{rich_text:Te(d)}})}return t}function gr(n){return Array.isArray(n?.blocks)&&n.blocks.length?n.blocks.slice(0,hr):typeof n?.markdown=="string"&&n.markdown.trim()?go(n.markdown).slice(0,hr):null}async function _r(n,e){for(let t=0;t<e.length;t+=Ke)await F(`/blocks/${n}/children`,{method:"PATCH",body:{children:e.slice(t,t+Ke)}})}function _o(n){let e=typeof n=="string"?n.trim():"";if(!e)throw new Error("imagePath is required");if(!br(e)||!eo(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=to(e);if(t.length>mo)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return t}async function bo(n){let e=_o(n),t=no(n.trim()),r=/\.png$/i.test(t)?"image/png":"image/jpeg",i=(await F("/file_uploads",{method:"POST",body:{mode:"single_part",filename:t}}))?.id;if(!i)throw new Error("Notion file upload create returned no id");let o=new FormData;return o.set("file",new Blob([e],{type:r}),t),await F(`/file_uploads/${i}/send`,{method:"POST",formData:o}),i}var wr={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)
325
+ \`\`\``;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=>Oe(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(`
326
+ `)}async function Ur(r,e,t){let n=[],i,s=0;do{if(t.used>=et)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let a=await Y(`/blocks/${r}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await Ur(d.id,e+1,t));let u=Go(d,e,l);if(u&&(n.push(u),t.used+=u.length+1),t.used>=et)break}i=a.has_more?a.next_cursor:void 0,s+=1}while(i&&s<Bo);return n.join(`
327
+ `)}function $r(r){let e=r?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let n=Oe(t.title).trim();if(n)return n}return""}function qe(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 Ko(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:Oe(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function Fo(r){if(!r||!r.type)return"";switch(r.type){case"title":return Oe(r.title).trim();case"rich_text":return Oe(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 At(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function Ho(r){let e=String(r??"").replace(/\r\n/g,`
328
+ `),t=[];for(let n of e.split(`
329
+ `)){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:qe(d)}})}return t}function jr(r){return Array.isArray(r?.blocks)&&r.blocks.length?r.blocks.slice(0,Lr):typeof r?.markdown=="string"&&r.markdown.trim()?Ho(r.markdown).slice(0,Lr):null}async function Pr(r,e){for(let t=0;t<e.length;t+=tt)await Y(`/blocks/${r}/children`,{method:"PATCH",body:{children:e.slice(t,t+tt)}})}function zo(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Cr(e)||!xo(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=Eo(e);if(t.length>Mo)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return t}async function Yo(r){let e=zo(r),t=$o(r.trim()),n=/\.png$/i.test(t)?"image/png":"image/jpeg",s=(await Y("/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 Y(`/file_uploads/${s}/send`,{method:"POST",formData:o}),s}var Dr={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:N.NOTION,description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion (connected)
330
330
  You can read Notion content as context AND write to Notion (create pages, append blocks, insert images).
331
331
  - 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.
332
332
  - 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.
@@ -335,7 +335,7 @@ You can read Notion content as context AND write to Notion (create pages, append
335
335
  - 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 }.
336
336
  - 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.
337
337
  - 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.
338
- 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 n=co();return n?{type:"stdio",command:"node",args:[n,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(n,e){try{switch(n){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,r=V(t);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let s=await F(`/pages/${r}`),i=yr(s),o=s?.url||`https://www.notion.so/${r.replace(/-/g,"")}`,c=await kr(r,0,{used:0}),d=!1;return c.length>Ge&&(c=c.slice(0,Ge),d=!0),JSON.stringify({ok:!0,id:r,title:i,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,r=V(t);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let i={page_size:Math.max(1,Math.min(Number(e?.maxResults)||fr,fr))};e?.filter&&typeof e.filter=="object"&&(i.filter=e.filter);let o=await F(`/databases/${r}/query`,{method:"POST",body:i}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[u,p]of Object.entries(d.properties||{})){let m=yo(p);m&&(l[u]=m)}return{id:d.id,title:yr(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:r,count:c.length,hasMore:!!o.has_more,rows:c})}case"notion_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 r=e?.databaseId?V(e.databaseId):null,s=e?.parentPageId?V(e.parentPageId):V(e?.parent||e?.pageId);if(!r&&!s)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let i=r?{database_id:r}:{page_id:s},o={title:{title:Te(t)}},a=gr(e)||[],c=a.slice(0,Ke),d=await F("/pages",{method:"POST",body:{parent:i,properties:o,...c.length?{children:c}:{}}}),l=d?.id;if(!l)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let u=a.slice(Ke);return u.length&&await _r(l,u),JSON.stringify({ok:!0,pageId:l,url:d?.url||_t(l)})}case"notion_append_blocks":{let t=V(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 r=gr(e);return!r||!r.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await _r(t,r),JSON.stringify({ok:!0,pageId:t,url:_t(t)}))}case"notion_insert_image":{let t=V(e?.pageId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let r=typeof e?.caption=="string"&&e.caption.trim()?Te(e.caption.trim()):null,s,i;if(typeof e?.imagePath=="string"&&e.imagePath.trim())i=await bo(e.imagePath),s={type:"file_upload",file_upload:{id:i}};else if(typeof e?.imageUrl=="string"&&e.imageUrl.trim())s={type:"external",external:{url:e.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return r&&(s.caption=r),await F(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:s}]}}),JSON.stringify({ok:!0,pageId:t,url:_t(t),...i?{fileUploadId:i}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,r=V(t);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let s=new URLSearchParams({block_id:r,page_size:"100"}),i=await F(`/comments?${s.toString()}`),a=(Array.isArray(i.results)?i.results:[]).map(ho);return JSON.stringify({ok:!0,id:r,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 r=e?.discussionId||e?.discussion_id||null,s;if(r)s={discussion_id:String(r),rich_text:Te(t)};else{let o=e?.pageId||e?.page||e?.url||e?.id,a=V(o);if(!a)return JSON.stringify({ok:!1,error:"Either discussionId (to reply) or a valid pageId (to start a comment) is required"});s={parent:{page_id:a},rich_text:Te(t)}}let i=await F("/comments",{method:"POST",body:s});return JSON.stringify({ok:!0,id:i?.id||"",discussionId:i?.discussion_id||r||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${n}`})}}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 ko}from"fs";import{fileURLToPath as wo}from"url";import{dirname as So,resolve as Io}from"path";import{resolveIntegrationToken as vr,clearTokenCache as vo}from"@zibby/core/backend-client.js";function No(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=So(wo(import.meta.url)),e=Io(n,"..","bin","mcp-skill.mjs");return ko(e)?e:null}function Oo(){let n=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!n)return null;let e=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:n,memberId:e}}function Ro(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function To(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var Ao="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 Nr(){let n=Oo();if(n)return n;if(Ro()||To())throw new Error(Ao);return null}var Eo="202506",xo="https://api.linkedin.com";function Sr(n){if(n==null)return null;let e=String(n).trim();if(!e)return null;let t=e.match(/urn:li:organization:(\d+)/i);return t?t[1]:/^\d+$/.test(e)?e:null}function Ir(n){if(!n)return"";if(n.localizedName)return String(n.localizedName);let e=n.name&&n.name.localized;if(e&&typeof e=="object"){let t=Object.values(e)[0];if(t)return String(t)}return""}function Fe(n,e){return n?typeof n.get=="function"?n.get(e):n[e]||n[e.toLowerCase()]||null:null}async function _e(n,e={},t="linkedin_business"){let r=async()=>{let s;if(t==="linkedin_personal"){let d=Nr();d&&(s=d.token)}if(s||({token:s}=await vr(t)),typeof s!="string"||!s)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let i=n.startsWith("https://")?n:`${xo}${n}`,o=await fetch(i,{method:e.method||"GET",headers:{Authorization:`Bearer ${s}`,"LinkedIn-Version":Eo,"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 r()}catch(s){let i=String(s?.message||s||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw s;return vo(t),r()}}var Or={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)
338
+ 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=Do();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=te(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await Y(`/pages/${n}`),s=$r(i),o=i?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,c=await Ur(n,0,{used:0}),d=!1;return c.length>et&&(c=c.slice(0,et),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=te(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)||Er,Er))};e?.filter&&typeof e.filter=="object"&&(s.filter=e.filter);let o=await Y(`/databases/${n}/query`,{method:"POST",body:s}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[u,p]of Object.entries(d.properties||{})){let m=Fo(p);m&&(l[u]=m)}return{id:d.id,title:$r(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?te(e.databaseId):null,i=e?.parentPageId?te(e.parentPageId):te(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:qe(t)}},a=jr(e)||[],c=a.slice(0,tt),d=await Y("/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 u=a.slice(tt);return u.length&&await Pr(l,u),JSON.stringify({ok:!0,pageId:l,url:d?.url||At(l)})}case"notion_append_blocks":{let t=te(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=jr(e);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await Pr(t,n),JSON.stringify({ok:!0,pageId:t,url:At(t)}))}case"notion_insert_image":{let t=te(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()?qe(e.caption.trim()):null,i,s;if(typeof e?.imagePath=="string"&&e.imagePath.trim())s=await Yo(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 Y(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:i}]}}),JSON.stringify({ok:!0,pageId:t,url:At(t),...s?{fileUploadId:s}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,n=te(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 Y(`/comments?${i.toString()}`),a=(Array.isArray(s.results)?s.results:[]).map(Ko);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:qe(t)};else{let o=e?.pageId||e?.page||e?.url||e?.id,a=te(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:qe(t)}}let s=await Y("/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 Wo,readFileSync as Zo}from"fs";import{fileURLToPath as Vo}from"url";import{dirname as Qo,resolve as Xo}from"path";import{resolveIntegrationToken as xt,clearTokenCache as ea}from"@zibby/core/backend-client.js";function ta(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Qo(Vo(import.meta.url)),e=Xo(r,"..","bin","mcp-skill.mjs");return Wo(e)?e:null}function ra(){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 na(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function ia(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var sa="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 Et(){let r=ra();if(r)return r;if(na()||ia())throw new Error(sa);return null}var oa="202506",aa="https://api.linkedin.com";function qr(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 Jr(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 rt(r,e){return r?typeof r.get=="function"?r.get(e):r[e]||r[e.toLowerCase()]||null:null}async function pe(r,e={},t="linkedin_business"){let n=async()=>{let i;if(t==="linkedin_personal"){let d=Et();d&&(i=d.token)}if(i||({token:i}=await xt(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:`${aa}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,"LinkedIn-Version":oa,"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 ea(t),n()}}async function ca(r){let e;if(r==="linkedin_personal"){let t=Et();t&&(e=t.token)}if(e||({token:e}=await xt(r)),typeof e!="string"||!e)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return e}function la(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 Br(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 pe("/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=Zo(t),c=await ca(r),d=await fetch(s,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":n||la(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 Mr={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)
339
339
  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.
340
340
 
341
341
  Business (company Page) \u2014 DRAFT only:
@@ -345,22 +345,25 @@ Business (company Page) \u2014 DRAFT only:
345
345
  Personal (your own profile) \u2014 PUBLISHES IMMEDIATELY:
346
346
  - linkedin_publish_post: PUBLISH a post to your OWN member profile feed. Pass text (the post body) + optional visibility ('PUBLIC' default, or 'CONNECTIONS'). UNLIKE the org draft tool, this PUBLISHES the post immediately \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns { postUrn }. Set dry_run:true to VALIDATE which member profile the post would publish to (and preview the text) WITHOUT publishing \u2014 nothing is posted; returns { dryRun, target, wouldPostAs, textPreview }. Use this to confirm the identity before an approved publish. (needs LinkedIn Personal connected)
347
347
 
348
+ Attaching an image (optional, both tools):
349
+ - Both linkedin_create_draft_post and linkedin_publish_post accept imagePath (a LOCAL image file path, e.g. a PNG returned by social_card_render) + optional imageAltText. When imagePath is set, the image is uploaded to LinkedIn's Images API (same connected account/token as the post) and attached to the post as its media. On a dry_run nothing is uploaded \u2014 the result just reports imageWouldAttach:true.
350
+
348
351
  Notes:
349
352
  - Org-page posts are ALWAYS created as a DRAFT; personal-profile posts are ALWAYS published live \u2014 choose the tool accordingly.
350
353
  - 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.
351
- - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let n=No();if(!n)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:[n,"../dist/linkedin.js","linkedinSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"linkedin_list_organizations":{let{body:t}=await _e("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),r=Array.isArray(t.elements)?t.elements:[],s=[];for(let i of r){let o=i.organizationalTarget||i["organizationalTarget~"]||i.organization,a=Sr(o);if(!a)continue;let c="",d="";try{let l=(await _e(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=Ir(l),d=l.vanityName||""}catch{}s.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:s.length,organizations:s})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,r=Sr(t);if(!r)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let s=e?.text;if(typeof s!="string"||!s.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let i=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${r}`;if(e?.dry_run===!0)try{let l="";try{let u=(await _e(`/rest/organizations/${r}`,{},"linkedin_business")).body;l=Ir(u)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:l,id:r,urn:o},visibility:i,textPreview:s,note:"DRY RUN \u2014 nothing was posted"})}catch(l){return JSON.stringify({dryRun:!0,ok:!1,error:l.message})}let c=await _e("/rest/posts",{method:"POST",body:{author:o,commentary:s,visibility:i,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1}},"linkedin_business"),d=Fe(c.headers,"x-restli-id")||Fe(c.headers,"x-linkedin-id")||c.body?.id||null;return JSON.stringify({ok:!0,postUrn:d,author:o,lifecycleState:"DRAFT",visibility:i,status:c.status})}case"linkedin_publish_post":{let t=Nr(),r=t?t.memberId:(await vr("linkedin_personal")).memberId;if(!r)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let s=e?.text;if(typeof s!="string"||!s.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let i=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${r}`;if(e?.dry_run===!0)try{let l=(await _e("/v2/userinfo",{},"linkedin_personal")).body,u=l?.name||[l?.given_name,l?.family_name].filter(Boolean).join(" ")||"",p=l?.sub?String(l.sub):r;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:u,id:p,urn:`urn:li:person:${p}`},visibility:i,textPreview:s,note:"DRY RUN \u2014 nothing was posted"})}catch(l){return JSON.stringify({dryRun:!0,ok:!1,error:l.message})}let c=await _e("/rest/posts",{method:"POST",body:{author:o,commentary:s,visibility:i,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}},"linkedin_personal"),d=Fe(c.headers,"x-restli-id")||Fe(c.headers,"x-linkedin-id")||c.body?.id||null;return JSON.stringify({ok:!0,postUrn:d,author:o,lifecycleState:"PUBLISHED",visibility:i,status:c.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${n}`})}}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. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}}]};import{existsSync as Er,statSync as Lo,readFileSync as $o}from"fs";import{fileURLToPath as jo}from"url";import{basename as Po,dirname as Co,resolve as Uo}from"path";import{resolveIntegrationToken as qo,clearTokenCache as Do}from"@zibby/core/backend-client.js";function Jo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Co(jo(import.meta.url)),e=Uo(n,"..","bin","mcp-skill.mjs");return Er(e)?e:null}var ae="https://docs.googleapis.com/v1",Rr="https://www.googleapis.com/drive/v3",Bo="https://www.googleapis.com/upload/drive/v3",Mo=5*1024*1024;function Go(){let n=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!n)return null;let e=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:n,email:e}}function Ko(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Fo(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Ho="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.",kt=2e4,zo=25;function bt(n){if(!n||typeof n!="string")return null;let e=n.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 Yo(){let n,e=Go();if(e)n=e.token;else{if(Fo()||Ko())throw new Error(Ho);({token:n}=await qo("google"))}if(typeof n!="string"||!n)throw new Error(`Invalid google token type: ${typeof n}`);return n}async function H(n,e={}){let t=async()=>{let r=await Yo(),s=await fetch(n,{method:e.method||"GET",headers:{Authorization:`Bearer ${r}`,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(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Google API ${s.status}: ${o.slice(0,300)}`)}let i=await s.text().catch(()=>"");if(!i||!i.trim())return{};try{return JSON.parse(i)}catch{return{raw:i}}};try{return await t()}catch(r){let s=String(r?.message||r||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw r;return Do("google"),t()}}function Wo(n){let e=[],t="",r=0;for(;r<n.length;){let s=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(n.slice(r));if(s){e.push({start:t.length,end:t.length+s[1].length,link:s[2]}),t+=s[1],r+=s[0].length;continue}let i=/^\*\*([^*]+)\*\*/.exec(n.slice(r));if(i){e.push({start:t.length,end:t.length+i[1].length,bold:!0}),t+=i[1],r+=i[0].length;continue}let o=/^`([^`]+)`/.exec(n.slice(r));if(o){e.push({start:t.length,end:t.length+o[1].length,code:!0}),t+=o[1],r+=o[0].length;continue}t+=n[r],r+=1}return{text:t,styles:e}}function Tr(n,e){let t=String(n??"").replace(/\r\n/g,`
352
- `);if(!t.trim())return{requests:[],endIndex:e};let r=t.split(`
353
- `),s="",i=[],o=[];for(let l of r){let u=l,p=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(u),h=/^\s*[-*]\s+(.*)$/.exec(u),_=/^\s*\d+[.)]\s+(.*)$/.exec(u);f?(p=`HEADING_${f[1].length}`,u=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",u=h[1]):_&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",u=_[1]);let{text:g,styles:b}=Wo(u),y=e+s.length;for(let w of b)o.push({...w,start:y+w.start,end:y+w.end});s+=`${g}
354
- `,i.push({start:y,end:e+s.length,named:p,bullet:m})}if(!s)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:s}}];for(let l of i)l.named&&a.push({updateParagraphStyle:{range:{startIndex:l.start,endIndex:l.end},paragraphStyle:{namedStyleType:l.named},fields:"namedStyleType"}});let c=null,d=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let l of i)l.bullet?c&&c.preset===l.bullet?c.end=l.end:(d(),c={start:l.start,end:l.end,preset:l.bullet}):d();d();for(let l of o)l.end<=l.start||(l.bold?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{bold:!0},fields:"bold"}}):l.link?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{link:{url:l.link}},fields:"link"}}):l.code&&a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:e+s.length}}function Zo(n){let e="",t=r=>{for(let s of Array.isArray(r)?r:[]){if(e.length>=kt)return;if(s.paragraph)for(let i of s.paragraph.elements||[])e+=i?.textRun?.content||"";else if(s.table)for(let i of s.table.tableRows||[])for(let o of i.tableCells||[])t(o.content);else s.tableOfContents&&t(s.tableOfContents.content)}};return t(n?.content),e.slice(0,kt)}var Ae=n=>`https://docs.google.com/document/d/${n}/edit`;function Vo(n){let e=typeof n=="string"?n.trim():"";if(!e)throw new Error("imagePath is required");if(!Er(e)||!Lo(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=$o(e);if(t.length>Mo)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:Po(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Qo(n,e,t){let r=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${r}\r
354
+ - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=ta();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 pe("/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=qr(o);if(!a)continue;let c="",d="";try{let l=(await pe(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=Jr(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=qr(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 p="";try{let m=(await pe(`/rest/organizations/${n}`,{},"linkedin_business")).body;p=Jr(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:p,id:n,urn:o},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(p){return JSON.stringify({dryRun:!0,ok:!1,error:p.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let p=await Br("linkedin_business",o,a);d.content={media:{id:p,altText:c||""}}}let l=await pe("/rest/posts",{method:"POST",body:d},"linkedin_business"),u=rt(l.headers,"x-restli-id")||rt(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:u,author:o,lifecycleState:"DRAFT",visibility:s,status:l.status})}case"linkedin_publish_post":{let t=Et(),n=t?t.memberId:(await xt("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 p=(await pe("/v2/userinfo",{},"linkedin_personal")).body,m=p?.name||[p?.given_name,p?.family_name].filter(Boolean).join(" ")||"",f=p?.sub?String(p.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(p){return JSON.stringify({dryRun:!0,ok:!1,error:p.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let p=await Br("linkedin_personal",o,a);d.content={media:{id:p,altText:c||""}}}let l=await pe("/rest/posts",{method:"POST",body:d},"linkedin_personal"),u=rt(l.headers,"x-restli-id")||rt(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:u,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 Hr,statSync as da,readFileSync as ua}from"fs";import{fileURLToPath as pa}from"url";import{basename as ma,dirname as fa,resolve as ha}from"path";import{resolveIntegrationToken as ga,clearTokenCache as ya}from"@zibby/core/backend-client.js";function _a(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=fa(pa(import.meta.url)),e=ha(r,"..","bin","mcp-skill.mjs");return Hr(e)?e:null}var me="https://docs.googleapis.com/v1",Gr="https://www.googleapis.com/drive/v3",ba="https://www.googleapis.com/upload/drive/v3",ka=5*1024*1024;function wa(){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 Sa(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Ia(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var va="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.",$t=2e4,Na=25;function Lt(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 Oa(){let r,e=wa();if(e)r=e.token;else{if(Ia()||Sa())throw new Error(va);({token:r}=await ga("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function W(r,e={}){let t=async()=>{let n=await Oa(),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 ya("google"),t()}}function Ra(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 Kr(r,e){let t=String(r??"").replace(/\r\n/g,`
355
+ `);if(!t.trim())return{requests:[],endIndex:e};let n=t.split(`
356
+ `),i="",s=[],o=[];for(let l of n){let u=l,p=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(u),h=/^\s*[-*]\s+(.*)$/.exec(u),y=/^\s*\d+[.)]\s+(.*)$/.exec(u);f?(p=`HEADING_${f[1].length}`,u=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",u=h[1]):y&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",u=y[1]);let{text:_,styles:b}=Ra(u),g=e+i.length;for(let w of b)o.push({...w,start:g+w.start,end:g+w.end});i+=`${_}
357
+ `,s.push({start:g,end:e+i.length,named:p,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 Ta(r){let e="",t=n=>{for(let i of Array.isArray(n)?n:[]){if(e.length>=$t)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,$t)}var Je=r=>`https://docs.google.com/document/d/${r}/edit`;function Aa(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Hr(e)||!da(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>ka)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:ma(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function xa(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
355
358
  Content-Type: application/json; charset=UTF-8\r
356
359
  \r
357
- ${JSON.stringify(n)}\r
358
- --${r}\r
360
+ ${JSON.stringify(r)}\r
361
+ --${n}\r
359
362
  Content-Type: ${t}\r
360
363
  \r
361
364
  `,"utf8"),e,Buffer.from(`\r
362
- --${r}--\r
363
- `,"utf8")]),contentType:`multipart/related; boundary=${r}`}}var Ar=n=>{let e=typeof n?.markdown=="string"?n.markdown:null,t=typeof n?.text=="string"?n.text:null;return e??t},xr={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)
365
+ --${n}--\r
366
+ `,"utf8")]),contentType:`multipart/related; boundary=${n}`}}var Fr=r=>{let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t},zr={id:"google-docs",serverName:"gdocs",allowedTools:["mcp__gdocs__*"],requiresIntegration:N.GOOGLE,description:"Google Docs \u2014 create, append to, insert images into, and read Google Docs (drive.file scoped)",promptFragment:`## Google Docs (connected)
364
367
  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.
365
368
  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.
366
369
  - 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.
@@ -368,10 +371,10 @@ Docs access is PER-USER: each teammate connects their OWN Google account (Integr
368
371
  - 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 }.
369
372
  - gdocs_get: read a doc back as plain text (works for app-created/user-picked docs; arbitrary docs need the extended documents.readonly connection).
370
373
  - gdocs_list_created: list the Google Docs visible to this app (drive.file \u2192 only docs it created or the user picked).
371
- 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 n=Jo();if(!n)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:[n,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){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 s=(await H(`${ae}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!s)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let i=Ar(e);if(i&&i.trim()){let{requests:o}=Tr(i,1);o.length&&await H(`${ae}/documents/${s}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:s,title:t,url:Ae(s)})}case"gdocs_append":{let t=bt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let r=Ar(e);if(!r||!r.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let i=(await H(`${ae}/documents/${t}`))?.body,o=Array.isArray(i?.content)?i.content:[],a=o.length&&o[o.length-1].endIndex||2,c=Math.max(1,a-1),d=[],l=c;c>1&&(d.push({insertText:{location:{index:c},text:`
372
- `}}),l=c+1);let u=Tr(r,l);return d.push(...u.requests),await H(`${ae}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:Ae(t)})}case"gdocs_insert_image":{let t=bt(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:r,fileName:s,mimeType:i}=Vo(e.imagePath),{rawBody:o,contentType:a}=Qo({name:s,mimeType:i},r,i),d=(await H(`${Bo}/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 H(`${Rr}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await H(`${ae}/documents/${t}`),u=Array.isArray(l?.body?.content)?l.body.content:[],p=u.length&&u[u.length-1].endIndex||2,f={location:{index:Math.max(1,p-1)},uri:`https://drive.google.com/uc?export=download&id=${d}`},h=Number(e?.width),_=Number(e?.height);return(Number.isFinite(h)&&h>0||Number.isFinite(_)&&_>0)&&(f.objectSize={...Number.isFinite(h)&&h>0?{width:{magnitude:h,unit:"PT"}}:{},...Number.isFinite(_)&&_>0?{height:{magnitude:_,unit:"PT"}}:{}}),await H(`${ae}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:Ae(t)})}case"gdocs_get":{let t=bt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let r=await H(`${ae}/documents/${t}`),s=Zo(r?.body);return JSON.stringify({ok:!0,documentId:t,title:r?.title||"",url:Ae(t),text:s,...s.length>=kt?{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(zo),orderBy:"modifiedTime desc"}),r=await H(`${Rr}/files?${t.toString()}`),s=(Array.isArray(r?.files)?r.files:[]).map(i=>({documentId:i.id,title:i.name,modifiedTime:i.modifiedTime,url:i.webViewLink||Ae(i.id)}));return JSON.stringify({ok:!0,count:s.length,files:s})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${n}`})}}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 Ur,statSync as Xo,readFileSync as ea}from"fs";import{fileURLToPath as ta}from"url";import{basename as ra,dirname as na,resolve as sa}from"path";import{resolveIntegrationToken as ia}from"@zibby/core/backend-client.js";function oa(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=na(ta(import.meta.url)),e=sa(n,"..","bin","mcp-skill.mjs");return Ur(e)?e:null}var Lr=2e4,$r=50,aa=10*1024*1024,ca=6e3*1e3,Ee=null;async function qr(){let{appId:n,appSecret:e,host:t}=await ia("lark");if(Ee&&Ee.appId===n&&Ee.expiresAt>Date.now())return{token:Ee.token,host:t};let s=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:n,app_secret:e})})).json();if(s.code!==0)throw new Error(`Lark tenant_access_token failed: ${s.msg||s.code}`);return Ee={token:s.tenant_access_token,expiresAt:Date.now()+ca,appId:n},{token:s.tenant_access_token,host:t}}async function z(n,e,t){let{token:r,host:s}=await qr(),i={method:n,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}};n!=="GET"&&t!==void 0&&(i.body=JSON.stringify(t));let a=await(await fetch(`${s}${e}`,i)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:s}}function He(n,e){return String(n||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function ce(n){if(!n||typeof n!="string")return null;let e=n.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 be(n){let e=typeof n=="string"?ce(n):n;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 z("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),r=t?.node||{};if(r.obj_type!=="docx"||!r.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${r.obj_type||"unknown"})`);return r.obj_token}function jr(n){let e=String(n??"").replace(/\r\n/g,`
373
- `),t=[];for(let r of e.split(`
374
- `)){let s=r.replace(/\s+$/,"");if(!s.trim())continue;let i=/^(#{1,3})\s+(.*)$/.exec(s),o=/^\s*[-*]\s+(.*)$/.exec(s),a=/^\s*\d+[.)]\s+(.*)$/.exec(s),c,d,l;if(i){let u=i[1].length;c=`heading${u}`,d=2+u,l=i[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=s);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function ze(n){let e=typeof n?.markdown=="string"?n.markdown:null,t=typeof n?.text=="string"?n.text:null;return e??t}async function Pr(n,e){let t;for(let r=0;r<e.length;r+=$r){let s=e.slice(r,r+$r);t=(await z("POST",`/open-apis/docx/v1/documents/${n}/blocks/${n}/children?document_revision_id=-1`,{children:s})).host}return t}function la(n){let e=typeof n=="string"?n.trim():"";if(!e)throw new Error("imagePath is required");if(!Ur(e)||!Xo(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=ea(e);if(t.length>aa)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function da({fileName:n,parentNode:e,bytes:t}){let{token:r,host:s}=await qr(),i=new FormData;i.set("file_name",n),i.set("parent_type","docx_image"),i.set("parent_node",e),i.set("size",String(t.length)),i.set("file",new Blob([t]),n);let a=await(await fetch(`${s}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:i})).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 ua="docx",pa=50;function Cr(n){return[{type:"text_run",text_run:{text:String(n??"")}}]}function ma(n){return Array.isArray(n)?n.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function fa(n){let e=Array.isArray(n?.reply_list?.replies)?n.reply_list.replies:[];return{commentId:n?.comment_id||"",resolved:!!n?.is_solved,replies:e.map(t=>({replyId:t?.reply_id||"",author:t?.user_id||"",text:ma(t?.content?.elements),createTime:t?.create_time||""}))}}function wt(n){return typeof n?.fileType=="string"&&n.fileType.trim()?n.fileType.trim():ua}var Dr={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)
374
+ 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=_a();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 W(`${me}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!i)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=Fr(e);if(s&&s.trim()){let{requests:o}=Kr(s,1);o.length&&await W(`${me}/documents/${i}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:i,title:t,url:Je(i)})}case"gdocs_append":{let t=Lt(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=Fr(e);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await W(`${me}/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:`
375
+ `}}),l=c+1);let u=Kr(n,l);return d.push(...u.requests),await W(`${me}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:Je(t)})}case"gdocs_insert_image":{let t=Lt(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}=Aa(e.imagePath),{rawBody:o,contentType:a}=xa({name:i,mimeType:s},n,s),d=(await W(`${ba}/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 W(`${Gr}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await W(`${me}/documents/${t}`),u=Array.isArray(l?.body?.content)?l.body.content:[],p=u.length&&u[u.length-1].endIndex||2,f={location:{index:Math.max(1,p-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 W(`${me}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:Je(t)})}case"gdocs_get":{let t=Lt(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 W(`${me}/documents/${t}`),i=Ta(n?.body);return JSON.stringify({ok:!0,documentId:t,title:n?.title||"",url:Je(t),text:i,...i.length>=$t?{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(Na),orderBy:"modifiedTime desc"}),n=await W(`${Gr}/files?${t.toString()}`),i=(Array.isArray(n?.files)?n.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||Je(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 Xr,statSync as Ea,readFileSync as La}from"fs";import{fileURLToPath as $a}from"url";import{basename as ja,dirname as Pa,resolve as Ca}from"path";import{resolveIntegrationToken as Ua}from"@zibby/core/backend-client.js";function Da(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Pa($a(import.meta.url)),e=Ca(r,"..","bin","mcp-skill.mjs");return Xr(e)?e:null}var Yr=2e4,Wr=50,qa=10*1024*1024,Ja=6e3*1e3,Be=null;async function en(){let{appId:r,appSecret:e,host:t}=await Ua("lark");if(Be&&Be.appId===r&&Be.expiresAt>Date.now())return{token:Be.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 Be={token:i.tenant_access_token,expiresAt:Date.now()+Ja,appId:r},{token:i.tenant_access_token,host:t}}async function Z(r,e,t){let{token:n,host:i}=await en(),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 nt(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function fe(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 Re(r){let e=typeof r=="string"?fe(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 Z("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 Zr(r){let e=String(r??"").replace(/\r\n/g,`
376
+ `),t=[];for(let n of e.split(`
377
+ `)){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 u=s[1].length;c=`heading${u}`,d=2+u,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 it(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function Vr(r,e){let t;for(let n=0;n<e.length;n+=Wr){let i=e.slice(n,n+Wr);t=(await Z("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:i})).host}return t}function Ba(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Xr(e)||!Ea(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=La(e);if(t.length>qa)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function Ma({fileName:r,parentNode:e,bytes:t}){let{token:n,host:i}=await en(),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 Ga="docx",Ka=50;function Qr(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function Fa(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function Ha(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:Fa(t?.content?.elements),createTime:t?.create_time||""}))}}function jt(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():Ga}var tn={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:N.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs (connected)
375
378
  You can read, create, and append Lark/Feishu documents (docx). This reuses the same connected Lark app as messaging.
376
379
  - 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.
377
380
  - larkdoc_create: create a new doc from a title + markdown/text (#/##/### headings, - bullets, 1. ordered supported); returns { ok, documentId, url }. Share the url.
@@ -380,14 +383,14 @@ You can read, create, and append Lark/Feishu documents (docx). This reuses the s
380
383
  - 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.
381
384
  - 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).
382
385
  - larkdoc_add_comment: post a NEW top-level comment on a doc \u2014 pass { documentId, text }.
383
- 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 n=oa();return n?{type:"stdio",command:"node",args:[n,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(n,e){try{switch(n){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,r=ce(t);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=await be(r),i="";try{i=(await z("GET",`/open-apis/docx/v1/documents/${s}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await z("GET",`/open-apis/docx/v1/documents/${s}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>Lr&&(c=c.slice(0,Lr),d=!0),JSON.stringify({ok:!0,documentId:s,title:i,url:He(a,s),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:r,host:s}=await z("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),i=r?.document?.document_id;if(!i)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let o=ze(e);if(o&&o.trim()){let a=jr(o);a.length&&await Pr(i,a)}return JSON.stringify({ok:!0,documentId:i,title:t,url:He(s,i)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,r=ce(t);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=ze(e);if(!s||!s.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let i=await be(r),o=jr(s);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await Pr(i,o);return JSON.stringify({ok:!0,documentId:i,url:He(a,i)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,r=ce(t);if(!r)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 s=await be(r),i=e.imagePath.trim(),o=la(i),a=ra(i),d=(await z("POST",`/open-apis/docx/v1/documents/${s}/blocks/${s}/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 da({fileName:a,parentNode:d,bytes:o}),u={token:l},p=Number(e?.width),m=Number(e?.height);Number.isFinite(p)&&p>0&&(u.width=Math.round(p)),Number.isFinite(m)&&m>0&&(u.height=Math.round(m));let{host:f}=await z("PATCH",`/open-apis/docx/v1/documents/${s}/blocks/${d}?document_revision_id=-1`,{replace_image:u});return JSON.stringify({ok:!0,documentId:s,blockId:d,fileToken:l,url:He(f,s)})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,r=ce(t);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=await be(r),i=wt(e),o=new URLSearchParams({file_type:i,page_size:String(pa)}),{data:a}=await z("GET",`/open-apis/drive/v1/files/${s}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(fa);return JSON.stringify({ok:!0,documentId:s,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,r=ce(t);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=ze({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let i=await be(r),o=wt(e),{data:a}=await z("POST",`/open-apis/drive/v1/files/${i}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:Cr(s)}}]}});return JSON.stringify({ok:!0,documentId:i,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,r=ce(t);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=e?.commentId||e?.comment_id;if(!s)return JSON.stringify({ok:!1,error:"commentId is required"});let i=ze({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await be(r),a=wt(e),{data:c}=await z("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(s)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:Cr(i)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(s),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${n}`})}}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 Jr={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:[...j.envKeys||[],...K.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return j.serverName;if(process.env.LARK_RECEIVE_ID)return K.serverName;if(process.env.SLACK_BOT_TOKEN)return j.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?j.allowedTools||[]:process.env.LARK_RECEIVE_ID?K.allowedTools||[]:process.env.SLACK_BOT_TOKEN?j.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
386
+ 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=Da();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=fe(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Re(n),s="";try{s=(await Z("GET",`/open-apis/docx/v1/documents/${i}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await Z("GET",`/open-apis/docx/v1/documents/${i}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>Yr&&(c=c.slice(0,Yr),d=!0),JSON.stringify({ok:!0,documentId:i,title:s,url:nt(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 Z("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=it(e);if(o&&o.trim()){let a=Zr(o);a.length&&await Vr(s,a)}return JSON.stringify({ok:!0,documentId:s,title:t,url:nt(i,s)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,n=fe(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=it(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Re(n),o=Zr(i);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await Vr(s,o);return JSON.stringify({ok:!0,documentId:s,url:nt(a,s)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,n=fe(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 Re(n),s=e.imagePath.trim(),o=Ba(s),a=ja(s),d=(await Z("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 Ma({fileName:a,parentNode:d,bytes:o}),u={token:l},p=Number(e?.width),m=Number(e?.height);Number.isFinite(p)&&p>0&&(u.width=Math.round(p)),Number.isFinite(m)&&m>0&&(u.height=Math.round(m));let{host:f}=await Z("PATCH",`/open-apis/docx/v1/documents/${i}/blocks/${d}?document_revision_id=-1`,{replace_image:u});return JSON.stringify({ok:!0,documentId:i,blockId:d,fileToken:l,url:nt(f,i)})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=fe(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Re(n),s=jt(e),o=new URLSearchParams({file_type:s,page_size:String(Ka)}),{data:a}=await Z("GET",`/open-apis/drive/v1/files/${i}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(Ha);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=fe(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=it({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Re(n),o=jt(e),{data:a}=await Z("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:Qr(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=fe(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=it({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Re(n),a=jt(e),{data:c}=await Z("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(i)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:Qr(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 rn={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:[...P.envKeys||[],...z.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return P.serverName;if(process.env.LARK_RECEIVE_ID)return z.serverName;if(process.env.SLACK_BOT_TOKEN)return P.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?P.allowedTools||[]:process.env.LARK_RECEIVE_ID?z.allowedTools||[]:process.env.SLACK_BOT_TOKEN?P.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
384
387
  You can post chat messages via:
385
388
  - slack_post_message (channel, text[, blocks]) \u2014 Slack. The \`channel\` is REQUIRED on every call.
386
389
  - lark_send_message (receive_id, text) \u2014 Lark.
387
390
  Where to post:
388
391
  - If SLACK_CHANNEL / LARK_RECEIVE_ID is set, that is the default destination \u2014 use it.
389
392
  - 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).
390
- - If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(n){return process.env.SLACK_CHANNEL&&typeof j.resolve=="function"?j.resolve(n):process.env.LARK_RECEIVE_ID&&typeof K.resolve=="function"?K.resolve(n):process.env.SLACK_BOT_TOKEN&&typeof j.resolve=="function"?j.resolve(n):null},async handleToolCall(n,e,t){return typeof n=="string"&&n.startsWith("slack_")?j.handleToolCall(n,e,t):typeof n=="string"&&n.startsWith("lark_")?K.handleToolCall(n,e,t):JSON.stringify({error:`chat_notify: unknown tool "${n}". Expected slack_* or lark_*.`})},get tools(){return[...j.tools||[],...K.tools||[]]}};import{createRequire as ha}from"module";import{execFileSync as ya}from"child_process";import{join as Br}from"path";import{existsSync as ga}from"fs";var _a=ha(import.meta.url);function ba(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return _a.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var Mr={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:n}=await import("@zibby/ui-memory");return n()}catch{return null}},promptFragment:`BEFORE executing browser actions:
393
+ - 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 P.resolve=="function"?P.resolve(r):process.env.LARK_RECEIVE_ID&&typeof z.resolve=="function"?z.resolve(r):process.env.SLACK_BOT_TOKEN&&typeof P.resolve=="function"?P.resolve(r):null},async handleToolCall(r,e,t){return typeof r=="string"&&r.startsWith("slack_")?P.handleToolCall(r,e,t):typeof r=="string"&&r.startsWith("lark_")?z.handleToolCall(r,e,t):JSON.stringify({error:`chat_notify: unknown tool "${r}". Expected slack_* or lark_*.`})},get tools(){return[...P.tools||[],...z.tools||[]]}};import{createRequire as za}from"module";import{execFileSync as Ya}from"child_process";import{join as nn}from"path";import{existsSync as Wa}from"fs";var Za=za(import.meta.url);function Va(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return Za.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var sn={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:
391
394
  - Review any test memory/history above. Prefer selectors proven to work.
392
395
  - If a previous run failed, avoid the same approach.
393
396
  - After setup/login completes, navigate directly to the target page instead of clicking through menus.
@@ -399,7 +402,7 @@ DURING execution \u2014 when a selector fails and you switch to a fallback:
399
402
  AFTER completing the test, you MUST call memory_save_insight at least once:
400
403
  - Save any useful finding: reliable selectors, timing quirks, navigation patterns, workarounds.
401
404
  - Category: selector_tip | timing | navigation | workaround | flaky | general
402
- - Be specific \u2014 future runs will read your insights.`,resolve(){let n=ba();if(!n)return console.warn("[memory] @zibby/ui-memory not found \u2014 memory tools disabled for this run"),null;let e=Br(process.cwd(),".zibby","memory");if(!ga(Br(e,".dolt")))return console.warn("[memory] DB/dolt unavailable \u2014 memory tools disabled for this run"),null;try{let t=ya("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:e,encoding:"utf-8",timeout:5e3}),r=JSON.parse(t.trim()).rows||[];if(!r[0]||r[0].cnt===0)return console.log("[memory] Database empty \u2014 memory tools activate after first completed run"),null}catch(t){return console.warn(`[memory] DB/dolt unavailable \u2014 memory tools disabled for this run (${t.message})`),null}return{command:"node",args:[n,"--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 ka,readFileSync as wa}from"fs";import{homedir as Sa}from"os";import{join as Ia}from"path";import{spawn as va}from"child_process";var le={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
405
+ - Be specific \u2014 future runs will read your insights.`,resolve(){let r=Va();if(!r)return console.warn("[memory] @zibby/ui-memory not found \u2014 memory tools disabled for this run"),null;let e=nn(process.cwd(),".zibby","memory");if(!Wa(nn(e,".dolt")))return console.warn("[memory] DB/dolt unavailable \u2014 memory tools disabled for this run"),null;try{let t=Ya("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 Qa,readFileSync as Xa}from"fs";import{homedir as ec}from"os";import{join as tc}from"path";import{spawn as rc}from"child_process";var he={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
403
406
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
404
407
  2. Click "Connect Jira" and authorize via Atlassian OAuth
405
408
  3. After OAuth completes, ask me to install Jira again`},github:{description:"GitHub issues, PRs, repository management",integrationProvider:"github",envKeys:[],setupInstructions:`To connect GitHub:
@@ -411,17 +414,17 @@ AFTER completing the test, you MUST call memory_save_insight at least once:
411
414
  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:
412
415
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
413
416
  2. Click "Connect Sentry" and authorize
414
- 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 Na(){let n=["## Available Skills"];for(let[e,t]of Object.entries(le)){let r=t.integrationProvider?`integration: ${t.integrationProvider}`:"ready";n.push(`- ${e}: ${t.description} [${r}]`)}return n.push(""),n.push("Use the install_skill / uninstall_skill / list_available_skills tools to manage skills."),n.push(`Zibby third party Integration settings page: ${St()}`),n.push(""),n.push("## Tool-First Policy (mandatory)"),n.push("CRITICAL RULES \u2014 follow these strictly:"),n.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."),n.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.`),n.push("3. If install_skill reports needsIntegration, tell the user to connect via the integration URL and try again after."),n.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."),n.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."),n.join(`
415
- `)}function Oa(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let n=Ia(Sa(),".zibby","config.json");return ka(n)&&JSON.parse(wa(n,"utf-8")).sessionToken||null}catch{return null}}function Ra(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function St(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function Ta(n){try{let e=process.platform;return va(e==="darwin"?"open":e==="win32"?"cmd":"xdg-open",e==="win32"?["/c","start","",n]:[n],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}async function Aa(){let n=Oa();if(!n)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${Ra()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${n}`}});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 Gr(n,e){if(!e||!n)return{connected:null};let t=n[e];return!t||typeof t.connected!="boolean"?{connected:null,details:t||null}:{connected:t.connected,details:t}}var Kr={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:le,promptFragment:Na,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(n,e,t){let{activeSkills:r}=t,s=await Aa();if(n==="list_available_skills"){let i=Object.entries(le).map(([o,a])=>{let c=r.includes(o),d=Gr(s.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:d.connected,setupInstructions:d.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:i})}if(n==="install_skill"){let{skillId:i}=e;if(!i)return JSON.stringify({ok:!1,error:"skillId is required"});if(r.includes(i)){let l=le[i],{getSkill:u}=await import("@zibby/agent-workflow"),m=(u(i)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:i,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?St():void 0,hint:`${i} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!le[i])return JSON.stringify({ok:!1,error:`Unknown skill "${i}". Available: ${Object.keys(le).join(", ")}`});let o=le[i];if(o.integrationProvider){let l=Gr(s.statuses,o.integrationProvider),u=St();if(s.checked&&l.connected===!1){let p=Ta(u);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:u,openedBrowser:p,setupInstructions:`Please connect ${o.integrationProvider} first at ${u}. After you finish OAuth, ask me to install ${i} again.`})}}r.push(i);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(i)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:i,description:o.description,availableTools:d,hint:`${i} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(n==="uninstall_skill"){let{skillId:i}=e;if(!i)return JSON.stringify({ok:!1,error:"skillId is required"});if(i==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=r.indexOf(i);return o===-1?JSON.stringify({ok:!1,error:`${i} is not installed`}):(r.splice(o,1),JSON.stringify({ok:!0,uninstalled:i}))}return JSON.stringify({error:`Unknown tool: ${n}`})},resolve(){return null}};import{readFileSync as Ea,readdirSync as xa,statSync as Hr,writeFileSync as La,mkdirSync as $a}from"fs";import{join as zr,resolve as ja,relative as Pa}from"path";import{execSync as Yr}from"child_process";var Fr=256*1024,Ca=64*1024,Wr={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(n,e,t){let r=t?.options?.workspace||process.cwd();try{switch(n){case"read_file":return Ua(e,r);case"write_file":return qa(e,r);case"list_directory":return Da(e,r);case"run_command":return Ja(e,r);case"open_url":return Ba(e);case"wait":return await Ma(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${n}`})}}catch(s){return JSON.stringify({error:s.message})}},resolve(){return null}};function Ye(n,e){return ja(e,n)}function Ua(n,e){let t=Ye(n.path,e),r=Hr(t);return r.size>Fr?JSON.stringify({error:`File too large (${(r.size/1024).toFixed(0)}KB). Max: ${Fr/1024}KB`}):Ea(t,"utf-8")}function qa(n,e){let t=Ye(n.path,e),r=zr(t,"..");return $a(r,{recursive:!0}),La(t,n.content,"utf-8"),JSON.stringify({ok:!0,path:Pa(e,t)})}function Da(n,e){let t=Ye(n.path||".",e);return xa(t).map(s=>{try{return Hr(zr(t,s)).isDirectory()?`${s}/`:s}catch{return s}}).join(`
416
- `)}function Ja(n,e){let t=n.cwd?Ye(n.cwd,e):e;return Yr(n.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:Ca,stdio:["pipe","pipe","pipe"]})||"(no output)"}function Ba(n){let{url:e}=n;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,r=t==="darwin"?"open":t==="win32"?"start":"xdg-open";try{return Yr(`${r} "${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 Ma(n,e){let t=Math.min(Math.max(n.seconds||5,1),300),r=n.reason||"async operation",s=500,i=Date.now()+t*1e3;for(;Date.now()<i;){if(e?.aborted)return JSON.stringify({ok:!0,waited:Math.round((t*1e3-(i-Date.now()))/1e3),reason:r,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(s,i-Date.now())))}return JSON.stringify({ok:!0,waited:t,reason:r})}import{existsSync as Ga}from"fs";import{fileURLToPath as Ka}from"url";import{dirname as Fa,resolve as Ha}from"path";import{resolveIntegrationToken as xe}from"@zibby/core/backend-client.js";function za(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let n=Fa(Ka(import.meta.url)),e=Ha(n,"..","bin","mcp-sentry.mjs");return Ga(e)?e:null}function Le(n){return(n||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Zr(n){let e=n||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 Vr(n,e={}){let{token:t,organizationSlug:r,baseUrl:s}=await xe("sentry"),i=`${Le(s)}/api/0/organizations/${Zr(r)}${n}`,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(i,o);if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Sentry API ${a.status}: ${c.slice(0,300)}`)}return a.json()}async function Ya(){return Vr("/projects/?per_page=50")}async function Wa({query:n="is:unresolved",sort:e="date",project:t,limit:r=25}={}){let s=`/issues/?query=${encodeURIComponent(n)}&sort=${e}&per_page=${r}`;return t&&(s+=`&project=${encodeURIComponent(t)}`),Vr(s)}async function It(n){let e=String(n??"").trim();if(!e)throw new Error("resolveSentryIssueId: issueRef is required");if(/^\d+$/.test(e))return e;let{token:t,organizationSlug:r,baseUrl:s}=await xe("sentry"),i=await fetch(`${Le(s)}/api/0/organizations/${Zr(r)}/shortids/${encodeURIComponent(e)}/`,{headers:{Authorization:`Bearer ${t}`}});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`Sentry API ${i.status} resolving shortId "${e}": ${c.slice(0,200)}`)}let o=await i.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 Za(n){if(!n)throw new Error("sentryGetIssue: issueId is required");let e=await It(n),{token:t,baseUrl:r}=await xe("sentry"),s=await fetch(`${Le(r)}/api/0/issues/${e}/`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status}: ${i.slice(0,300)}`)}return s.json()}async function Va(n,e={}){if(!n)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 r=await It(n),{token:s,baseUrl:i}=await xe("sentry"),o=await fetch(`${Le(i)}/api/0/issues/${r}/`,{method:"PUT",headers:{Authorization:`Bearer ${s}`,"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 ${n}: ${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 ${n}: ${a.slice(0,300)}`)}return o.json()}async function Qa(n,e){if(!n)throw new Error("sentryAddComment: issueId is required");if(!e||!String(e).trim())throw new Error("sentryAddComment: text is required");let t=await It(n),{token:r,baseUrl:s}=await xe("sentry"),i=await fetch(`${Le(s)}/api/0/issues/${t}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(e)})});if(!i.ok){let o=await i.text().catch(()=>"");throw i.status===403?new Error(`Sentry API 403 commenting on issue ${n}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${i.status} commenting on issue ${n}: ${o.slice(0,300)}`)}return i.json()}var We={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:v.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
417
+ 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 nc(){let r=["## Available Skills"];for(let[e,t]of Object.entries(he)){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: ${Pt()}`),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(`
418
+ `)}function ic(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=tc(ec(),".zibby","config.json");return Qa(r)&&JSON.parse(Xa(r,"utf-8")).sessionToken||null}catch{return null}}function sc(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function Pt(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function oc(r){try{let e=process.platform;return rc(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 ac(){let r=ic();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${sc()}/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 on(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 an={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:he,promptFragment:nc,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 ac();if(r==="list_available_skills"){let s=Object.entries(he).map(([o,a])=>{let c=n.includes(o),d=on(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=he[s],{getSkill:u}=await import("@zibby/agent-workflow"),m=(u(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?Pt():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!he[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(he).join(", ")}`});let o=he[s];if(o.integrationProvider){let l=on(i.statuses,o.integrationProvider),u=Pt();if(i.checked&&l.connected===!1){let p=oc(u);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:u,openedBrowser:p,setupInstructions:`Please connect ${o.integrationProvider} first at ${u}. After you finish OAuth, ask me to install ${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 cc,readdirSync as lc,statSync as ln,writeFileSync as dc,mkdirSync as uc}from"fs";import{join as dn,resolve as pc,relative as mc}from"path";import{execSync as un}from"child_process";var cn=256*1024,fc=64*1024,pn={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 hc(e,n);case"write_file":return gc(e,n);case"list_directory":return yc(e,n);case"run_command":return _c(e,n);case"open_url":return bc(e);case"wait":return await kc(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function st(r,e){return pc(e,r)}function hc(r,e){let t=st(r.path,e),n=ln(t);return n.size>cn?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${cn/1024}KB`}):cc(t,"utf-8")}function gc(r,e){let t=st(r.path,e),n=dn(t,"..");return uc(n,{recursive:!0}),dc(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:mc(e,t)})}function yc(r,e){let t=st(r.path||".",e);return lc(t).map(i=>{try{return ln(dn(t,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
419
+ `)}function _c(r,e){let t=r.cwd?st(r.cwd,e):e;return un(r.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:fc,stdio:["pipe","pipe","pipe"]})||"(no output)"}function bc(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 kc(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 wc}from"fs";import{fileURLToPath as Sc}from"url";import{dirname as Ic,resolve as vc}from"path";import{resolveIntegrationToken as Me}from"@zibby/core/backend-client.js";function Nc(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=Ic(Sc(import.meta.url)),e=vc(r,"..","bin","mcp-sentry.mjs");return wc(e)?e:null}function Ge(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function mn(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 fn(r,e={}){let{token:t,organizationSlug:n,baseUrl:i}=await Me("sentry"),s=`${Ge(i)}/api/0/organizations/${mn(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 Oc(){return fn("/projects/?per_page=50")}async function Rc({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)}`),fn(i)}async function Ct(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 Me("sentry"),s=await fetch(`${Ge(i)}/api/0/organizations/${mn(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 Tc(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let e=await Ct(r),{token:t,baseUrl:n}=await Me("sentry"),i=await fetch(`${Ge(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 Ac(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 Ct(r),{token:i,baseUrl:s}=await Me("sentry"),o=await fetch(`${Ge(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 xc(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 Ct(r),{token:n,baseUrl:i}=await Me("sentry"),s=await fetch(`${Ge(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 ot={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:N.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
417
420
  You have access to the user's Sentry. Use these tools:
418
421
  - sentry_list_projects: List projects in the organization
419
422
  - sentry_list_issues: List errors/issues (supports Sentry search query, project filter, sort)
420
423
  - sentry_get_issue: Get detailed info about a specific issue (requires issueId)
421
424
  - sentry_update_issue: Change an issue's status (resolved / resolvedInNextRelease / ignored / unresolved / muted), assignment, or bookmark (requires issueId; needs write scope)
422
- - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let n=za();if(!n)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:[n],env:e,alwaysLoad:!0}},async handleToolCall(n,e={}){try{switch(n){case"sentry_list_projects":{let t=await Ya();return JSON.stringify({projects:t.map(r=>({slug:r.slug,name:r.name,platform:r.platform}))})}case"sentry_list_issues":{let t=await Wa({query:e.query,sort:e.sort,project:e.project,limit:e.limit});return JSON.stringify({issues:t.map(r=>({id:r.id,title:r.title,culprit:r.culprit,count:r.count,firstSeen:r.firstSeen,lastSeen:r.lastSeen,level:r.level,status:r.status}))})}case"sentry_get_issue":{let t=await Za(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 Va(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 Qa(e.issueId,e.text);return JSON.stringify({ok:!0,id:t.id,issueId:e.issueId})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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"]}}]};We.tools=We.toolsForAssistant;import{spawn as cn}from"child_process";import{writeFileSync as Xa,mkdirSync as Qr,existsSync as Y,readdirSync as Xe,readFileSync as Qe,unlinkSync as ec,createWriteStream as tc,statSync as rc}from"fs";import{resolve as de,join as G}from"path";import{resolveMaxParallelRuns as ln}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as nc}from"@zibby/core/constants/zibby-scratch.js";var Ot="sessions",Rt=".zibby/output",Ze=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",sc=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",dn=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",U=new Map,ne=[],ic=0,vt=0,Xr=3e3;function un(){return`run_${++ic}_${Date.now().toString(36)}`}function en(n){let e=Math.floor(n/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function pn(n){return n.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function C(n,e,t){if(!sc)return;let r=`
423
- ${e} [${n}] ${t}
424
- `;try{process.stderr.write(r)}catch{}}function Tt(){ne.length=0;for(let[,n]of U)if(n.status==="queued"&&(n.status="cancelled"),n.status==="running"&&n._child)try{n._child.kill("SIGTERM")}catch{}}process.on("exit",Tt);process.on("SIGINT",()=>{Tt(),process.exit(0)});process.on("SIGTERM",()=>{Tt(),process.exit(0)});var mn={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
425
+ - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=Nc();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 Oc();return JSON.stringify({projects:t.map(n=>({slug:n.slug,name:n.name,platform:n.platform}))})}case"sentry_list_issues":{let t=await Rc({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 Tc(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 Ac(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 xc(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"]}}]};ot.tools=ot.toolsForAssistant;import{spawn as vn}from"child_process";import{writeFileSync as Ec,mkdirSync as hn,existsSync as V,readdirSync as dt,readFileSync as lt,unlinkSync as Lc,createWriteStream as $c,statSync as jc}from"fs";import{resolve as ge,join as H}from"path";import{resolveMaxParallelRuns as Nn}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Pc}from"@zibby/core/constants/zibby-scratch.js";var qt="sessions",Jt=".zibby/output",at=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",Cc=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",On=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",q=new Map,ae=[],Uc=0,Ut=0,gn=3e3;function Rn(){return`run_${++Uc}_${Date.now().toString(36)}`}function yn(r){let e=Math.floor(r/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Tn(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function U(r,e,t){if(!Cc)return;let n=`
426
+ ${e} [${r}] ${t}
427
+ `;try{process.stderr.write(n)}catch{}}function Bt(){ae.length=0;for(let[,r]of q)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",Bt);process.on("SIGINT",()=>{Bt(),process.exit(0)});process.on("SIGTERM",()=>{Bt(),process.exit(0)});var An={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
425
428
  You can run zibby test workflows directly from chat:
426
429
 
427
430
  **CRITICAL: When user asks to test a ticket:**
@@ -558,35 +561,35 @@ Each run generates:
558
561
  - events.json: All browser events
559
562
  - raw_stream_output.txt: Agent log
560
563
 
561
- Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(n,e,t){let r=t?.options?.workspace||process.cwd();try{switch(n){case"run_generate":return await oc(e,r);case"run_test":return await pc(e,r,t);case"run_status":return mc(e);case"run_cancel":return fc(e);case"run_artifacts":return gc(e,r);case"run_diagnose":return _c(e,r);case"list_specs":return bc(e,r);default:return JSON.stringify({error:`Unknown tool: ${n}`})}}catch(s){return JSON.stringify({error:s.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 Nt(){let n=0;for(let[,e]of U)e.status==="running"&&n++;return n}function tn(){for(;ne.length>0;){let n=ln(ne[0]?.context?.options?.config);if(Nt()>=n)break;let{args:e,cwd:t,context:r}=ne.shift();fn(e,t,r)}}async function oc(n,e){let{ticket:t,description:r,input:s,repo:i,agent:o,output:a}=n,c=["generate"];t&&c.push("--ticket",t),r&&c.push("--description",r),s&&c.push("--input",s),i&&c.push("--repo",i),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,u=l&&d.includes(l)?l:null;u&&c.push("--agent",u);let p=t||"generate";return C(p,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{dn&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(g=>/\s/.test(g)?JSON.stringify(g):g).join(" ")} cwd=${e}`);let f=cn("zibby",c,{cwd:e,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",_="";f.stdout.on("data",g=>{let b=g.toString();h+=b;for(let y of b.split(`
562
- `)){let w=pn(y).trim();w.startsWith("\u2705")?C(p,"\u2705",w.slice(2).trim()):w.startsWith("\u2713")&&C(p,"\u2714",w.slice(2).trim())}}),f.stderr.on("data",g=>{_+=g.toString()}),f.on("close",g=>{if(g!==0){C(p,"\u274C",`Generation failed (exit ${g})`),m(JSON.stringify({error:`zibby generate failed with exit code ${g}`,stderr:_.slice(-1e3)}));return}let b=de(e,a||"test-specs"),y=[];try{let w=t?t.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";y=Xe(b).filter(A=>A.endsWith(".txt")&&(!w||A.startsWith(w))).map(A=>G(b,A))}catch{}C(p,"\u2705",`Generated ${y.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:t||null,specFiles:y.map(w=>w.replace(`${e}/`,"")),total:y.length,message:`Generated ${y.length} specs. Now call run_test for each file.`}))}),f.on("error",g=>{C(p,"\u274C",`Spawn error: ${g.message}`),m(JSON.stringify({error:g.message}))})})}var rn=1e5,nn=/^[A-Z][A-Z0-9]+-\d+$/,ac=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function cc(n,e){if(!e||!e.length)return n;let t=n;for(let r of e)r.type==="strong"?t=`**${t}**`:r.type==="em"?t=`_${t}_`:r.type==="code"?t=`\`${t}\``:r.type==="strike"?t=`~~${t}~~`:r.type==="link"&&r.attrs?.href&&(t=`[${t}](${r.attrs.href})`);return t}function Ve(n,e=0){if(!Array.isArray(n))return"";let t=[];for(let r of n){if(r.type==="text"){t.push(cc(r.text||"",r.marks));continue}if(r.type==="hardBreak"){t.push(`
563
- `);continue}if(r.type==="rule"){t.push(`
564
+ 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 Dc(e,n);case"run_test":return await Kc(e,n,t);case"run_status":return Fc(e);case"run_cancel":return Hc(e);case"run_artifacts":return Wc(e,n);case"run_diagnose":return Zc(e,n);case"list_specs":return Vc(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 Dt(){let r=0;for(let[,e]of q)e.status==="running"&&r++;return r}function _n(){for(;ae.length>0;){let r=Nn(ae[0]?.context?.options?.config);if(Dt()>=r)break;let{args:e,cwd:t,context:n}=ae.shift();xn(e,t,n)}}async function Dc(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,u=l&&d.includes(l)?l:null;u&&c.push("--agent",u);let p=t||"generate";return U(p,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{On&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(_=>/\s/.test(_)?JSON.stringify(_):_).join(" ")} cwd=${e}`);let f=vn("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(`
565
+ `)){let w=Tn(g).trim();w.startsWith("\u2705")?U(p,"\u2705",w.slice(2).trim()):w.startsWith("\u2713")&&U(p,"\u2714",w.slice(2).trim())}}),f.stderr.on("data",_=>{y+=_.toString()}),f.on("close",_=>{if(_!==0){U(p,"\u274C",`Generation failed (exit ${_})`),m(JSON.stringify({error:`zibby generate failed with exit code ${_}`,stderr:y.slice(-1e3)}));return}let b=ge(e,a||"test-specs"),g=[];try{let w=t?t.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";g=dt(b).filter(T=>T.endsWith(".txt")&&(!w||T.startsWith(w))).map(T=>H(b,T))}catch{}U(p,"\u2705",`Generated ${g.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:t||null,specFiles:g.map(w=>w.replace(`${e}/`,"")),total:g.length,message:`Generated ${g.length} specs. Now call run_test for each file.`}))}),f.on("error",_=>{U(p,"\u274C",`Spawn error: ${_.message}`),m(JSON.stringify({error:_.message}))})})}var bn=1e5,kn=/^[A-Z][A-Z0-9]+-\d+$/,qc=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Jc(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 ct(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(Jc(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
566
+ `);continue}if(n.type==="rule"){t.push(`
564
567
  ---
565
- `);continue}let s=r.content?Ve(r.content,e+1):"";if(r.type==="listItem")t.push(s);else if(r.type==="bulletList"){let i=(r.content||[]).map(o=>`- ${Ve(o.content||[],e+1).trim()}`);t.push(`
566
- ${i.join(`
568
+ `);continue}let i=n.content?ct(n.content,e+1):"";if(n.type==="listItem")t.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${ct(o.content||[],e+1).trim()}`);t.push(`
569
+ ${s.join(`
567
570
  `)}
568
- `)}else if(r.type==="orderedList"){let i=(r.content||[]).map((o,a)=>`${a+1}. ${Ve(o.content||[],e+1).trim()}`);t.push(`
569
- ${i.join(`
571
+ `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${ct(o.content||[],e+1).trim()}`);t.push(`
572
+ ${s.join(`
570
573
  `)}
571
- `)}else if(r.type==="heading"){let i=r.attrs?.level||2;t.push(`
574
+ `)}else if(n.type==="heading"){let s=n.attrs?.level||2;t.push(`
572
575
 
573
- ${"#".repeat(i)} ${s.trim()}
576
+ ${"#".repeat(s)} ${i.trim()}
574
577
 
575
- `)}else ac.has(r.type)?t.push(`
578
+ `)}else qc.has(n.type)?t.push(`
576
579
 
577
- ${s}
578
- `):t.push(s)}return t.join("").replace(/\n{3,}/g,`
580
+ ${i}
581
+ `):t.push(i)}return t.join("").replace(/\n{3,}/g,`
579
582
 
580
- `)}function lc(n){return n==null||n===""?"":typeof n=="string"?n.trim():typeof n=="object"&&Array.isArray(n.content)?Ve(n.content).trim():""}async function dc(n){let{getSkill:e}=await import("@zibby/agent-workflow"),t=e("jira");if(!t||typeof t.handleToolCall!="function")return null;try{let r=await t.handleToolCall("jira_get_issue",{issueKey:n}),s=JSON.parse(r);if(s?.error)return null;let i=await t.handleToolCall("jira_get_comments",{issueKey:n,maxResults:50}),o=JSON.parse(i);if(o?.error)return null;let a=lc(s.description),c=[];a&&c.push(a);let d=Array.isArray(o.comments)?o.comments:[];if(d.length>0){let u=d.map(p=>String(p.body||"").trim()).filter(Boolean).join(`
583
+ `)}function Bc(r){return r==null||r===""?"":typeof r=="string"?r.trim():typeof r=="object"&&Array.isArray(r.content)?ct(r.content).trim():""}async function Mc(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=Bc(i.description),c=[];a&&c.push(a);let d=Array.isArray(o.comments)?o.comments:[];if(d.length>0){let u=d.map(p=>String(p.body||"").trim()).filter(Boolean).join(`
581
584
 
582
585
  `);u&&c.push(u)}let l=c.join(`
583
586
 
584
- `).trim();return l?(l.length>rn&&(l=`${l.slice(0,rn)}
587
+ `).trim();return l?(l.length>bn&&(l=`${l.slice(0,bn)}
585
588
 
586
- ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:n}):null}catch{return null}}function uc(n,e){try{let t=JSON.parse(n);return JSON.stringify({...t,...e})}catch{return n}}async function pc(n,e,t){let r={...n},s=String(r.spec??"").trim();if(!s)return JSON.stringify({error:"spec is required"});let i=null;if(nn.test(s)&&!s.startsWith("inline:")){let l=await dc(s);l&&(s=l.inlineSpec,r.spec=s,String(r.ticketKey||"").trim()||(r.ticketKey=l.issueKey),i=l.issueKey)}let o=String(r.ticketKey||"").trim();if(o){for(let[l,u]of U.entries())if(u?.ticketKey===o&&!(u?.status!=="running"&&u?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:u.status,reused:!0,message:`A run for ${o} is already ${u.status}. Reusing existing run instead of starting a duplicate.`})}if(!s.startsWith("inline:")){let l=de(e,s);if(!Y(l))return nn.test(s)?JSON.stringify({error:`Invalid run_test spec: "${s}" 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:s},invalidExample:{spec:s,ticketKey:s}}):JSON.stringify({error:`Test spec not found: ${s}`,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=ln(t?.options?.config);if(Nt()>=a){let l=un(),u=r.ticketKey||l,p={runId:l,spec:r.ticketKey?`${r.ticketKey}: ${r.spec}`:r.spec,ticketKey:r.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};U.set(l,p),ne.push({args:{...r,_queuedRunId:l},cwd:e,context:t}),C(u,"\u23F3",`Queued (${Nt()}/${a} running, ${ne.length} queued)`);let m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return i&&(m.resolvedFromJiraIssue=i,m.message+=` (spec built from Jira ${i})`),JSON.stringify(m)}let c=Date.now()-vt;c<Xr&&vt>0&&await new Promise(l=>setTimeout(l,Xr-c)),vt=Date.now();let d=fn(r,e,t);return i?uc(d,{resolvedFromJiraIssue:i,message:`Spec was loaded from Jira issue ${i} (description + comments).`}):d}function fn(n,e,t){let{spec:r,ticketKey:s,agent:i,headless:o,workflow:a,_queuedRunId:c}=n,d=c||un(),l=r,u=!1;if(r.startsWith("inline:")){u=!0;let T=nc(e);Qr(T,{recursive:!0}),l=G(T,`${d}.txt`),Xa(l,r.slice(7).trim(),"utf-8")}let p=de(e,".zibby","output","runs");Qr(p,{recursive:!0});let m=G(p,`${d}.log`),f=tc(m,{flags:"a"}),_=i&&["assistant","cursor","claude","codex","gemini"].includes(i)?i:null,g=["test",l];_&&g.push("--agent",_),o&&g.push("--headless"),a&&g.push("--workflow",a),dn&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${g.map(T=>/\s/.test(T)?JSON.stringify(T):T).join(" ")} cwd=${e}`);let b=cn("zibby",g,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),y={runId:d,spec:s?`${s}: ${r}`:r,ticketKey:s||null,specPath:l,logPath:m,isInline:u,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},w=s||d,A="";function ee(T){let O=pn(T).trim();if(!O)return;if(O.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let L=JSON.parse(O.slice(22));L.phase==="node_begin"?y.currentNode=L.node:L.phase==="node_end"&&(L.node&&!y.completedNodes.includes(L.node)&&y.completedNodes.push(L.node),y.currentNode===L.node&&(y.currentNode=null))}catch{}return}let B=O.match(/Session\s+(\S+)/);if(B&&!y.sessionId&&(y.sessionId=B[1],y.sessionPath=de(e,Rt,Ot,y.sessionId)),O.startsWith("\u250C ")||O.startsWith("\u250C ")){let L=O.slice(2).trim();y.currentNode=L,Ze&&C(w,"\u25B6",`${L}`)}else if(O.startsWith("\u2514 ")||O.startsWith("\u2514 ")){let L=O.slice(2).trim();L.startsWith("done")?(y.currentNode&&!y.completedNodes.includes(y.currentNode)&&y.completedNodes.push(y.currentNode),Ze&&C(w,"\u2714",`${y.currentNode||"node"} done ${L.replace("done","").trim()}`),y.currentNode=null):L.startsWith("failed")&&(Ze&&C(w,"\u2718",`${y.currentNode||"node"} failed ${L.replace("failed","").trim()}`),y.currentNode=null)}else O.includes("Workflow completed")&&(y.currentNode=null,Ze&&C(w,"\u2714",`Workflow completed (${en(Date.now()-y.startTime)})`))}function mt(T){let O=T.toString();y.output+=O,f.write(O),y.output.length>5e4&&(y.output=y.output.slice(-3e4)),A+=O;let B=A.split(`
587
- `);A=B.pop();for(let L of B)ee(L)}return b.stdout.on("data",mt),b.stderr.on("data",T=>{let O=T.toString();y.error+=O,f.write(O),y.error.length>2e4&&(y.error=y.error.slice(-1e4))}),b.on("close",T=>{y.status=T===0?"passed":"failed",y.exitCode=T,y.endTime=Date.now(),A&&ee(A),f.end();let O=en(Date.now()-y.startTime);if(T===0?C(w,"\u2705",`Passed (${O})`):C(w,"\u274C",`Failed (${O})`),y.isInline)try{ec(y.specPath)}catch{}tn()}),b.on("error",T=>{y.status="error",y.error+=`
588
- Spawn error: ${T.message}`,C(w,"\u274C",`Spawn error: ${T.message}`),f.end(),tn()}),y._child=b,U.set(d,y),JSON.stringify({runId:d,spec:y.spec,ticketKey:y.ticketKey,status:"running",pid:b.pid,logFile:m})}function sn(n){let e=Math.round(((n.endTime||Date.now())-n.startTime)/1e3),t=n.completedNodes||[],r=n.currentNode||null;if(n.status!=="running")return{elapsed:e,stage:n.status,completedNodes:t,currentNode:null};let s;return r?(s=`Actively executing node "${r}"`,t.length&&(s+=` (completed: ${t.join(", ")})`)):t.length?s=`Between nodes (completed: ${t.join(", ")})`:s="Starting up (initializing workflow)",s+=`. Elapsed: ${e}s. This is normal progress \u2014 do not cancel.`,{elapsed:e,stage:"running",currentNode:r,completedNodes:t,progress:s}}function mc(n){let{runId:e}=n;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let i=[...U.entries()].map(([l,u])=>{let p=sn(u),m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:u.status,elapsed:p.elapsed,exitCode:u.exitCode,sessionId:u.sessionId||null};return u.status==="running"?(m.currentNode=p.currentNode,m.completedNodes=p.completedNodes,m.progress=p.progress):m.outputTail=u.output.slice(-500),m}),o=i.filter(l=>l.status==="running").length,a=i.filter(l=>l.status==="passed").length,c=i.filter(l=>l.status==="failed").length,d={total:i.length,running:o,passed:a,failed:c,runs:i};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let t=U.get(e);if(!t)return JSON.stringify({error:`Run not found: ${e}`});let r=sn(t),s={runId:e,spec:t.spec,ticketKey:t.ticketKey,status:t.status,elapsed:r.elapsed,exitCode:t.exitCode,sessionId:t.sessionId||null};return t.status==="running"?(s.currentNode=r.currentNode,s.completedNodes=r.completedNodes,s.progress=r.progress):(s.outputTail=t.output.slice(-1e3),s.errorTail=t.error.slice(-500)),t.status==="running"&&(s._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(s)}function on(n,e){if(e.status==="queued"){let t=ne.findIndex(r=>r.args._queuedRunId===n);return t>=0&&ne.splice(t,1),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:n,status:"cancelled"}}if(e.status!=="running")return{ok:!1,runId:n,error:`Run is not active (status: ${e.status})`};try{return e._child.kill("SIGTERM"),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:n,status:"cancelled"}}catch(t){return{ok:!1,runId:n,error:`Failed to cancel: ${t.message}`}}}function fc(n){let{runId:e}=n;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let r=[];for(let[s,i]of U.entries())(i.status==="running"||i.status==="queued")&&r.push(on(s,i));return r.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:r.length,results:r})}let t=U.get(e);return JSON.stringify(t?on(e,t):{error:`Run not found: ${e}`})}function hc(n,e){let t=U.get(n);if(t?.sessionPath&&Y(t.sessionPath))return t.sessionPath;if(t?.sessionId){let r=de(e,Rt,Ot,t.sessionId);if(Y(r))return r}return null}function hn(n,e=""){let t=[];if(!Y(n))return t;for(let r of Xe(n,{withFileTypes:!0})){let s=e?`${e}/${r.name}`:r.name;if(r.isDirectory())t.push(...hn(G(n,r.name),s));else{let i=rc(G(n,r.name));t.push({path:s,size:i.size})}}return t}function an(n){if(!Y(n))return null;try{return JSON.parse(Qe(n,"utf-8"))}catch{return null}}function yn(n,e=2e3){if(!n||!Y(n))return"";try{return Qe(n,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function yc({run:n,logTail:e,errorTail:t}){let s=`${e||""}
589
- ${t||""}`.toLowerCase(),i={runId:n?.runId||null,status:n?.status||null,exitCode:n?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return n?.status==="running"||n?.status==="queued"?{...i,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:s.includes("test spec not found")?{...i,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:s.includes("unknown command")&&s.includes("'run'")?{...i,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:s.includes("missing openai_api_key")||s.includes("didn't provide an api key")||s.includes("401")?{...i,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:s.includes("spawn error")||s.includes("enoent")?{...i,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:s.includes("security command failed")||s.includes("security process exited with code: 45")||s.includes("password not found for account")?{...i,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:i}function gc(n,e){let{runId:t,type:r,node:s="execute_live",query:i,tail:o=3e3}=n;if(r==="search"){if(!i)return JSON.stringify({error:'query is required for type="search"'});let c=de(e,Rt,Ot);if(!Y(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=i.toLowerCase();for(let u of Xe(c,{withFileTypes:!0})){if(!u.isDirectory())continue;let p=G(c,u.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let _=G(p,f);if(Y(_))try{let g=Qe(_,"utf-8");if(g.toLowerCase().includes(l)){let b=g.toLowerCase().indexOf(l),y=Math.max(0,b-100),w=Math.min(g.length,b+i.length+100);d.push({sessionId:u.name,artifact:h,snippet:g.slice(y,w)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:i,matches:d,total:d.length})}if(!t)return JSON.stringify({error:"runId is required for this type"});if(r==="log"){let c=U.get(t),d=yn(c?.logPath,o);if(d)return JSON.stringify({runId:t,source:"run-log",totalLength:d.length,tail:d})}let a=hc(t,e);if(!a)return JSON.stringify({error:`No session found for run ${t}. The run may still be starting.`});switch(r){case"list":{let c=hn(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=an(G(a,s,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:s,result:c}:{error:`No result.json found in ${s}`})}case"events":{let c=an(G(a,s,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${s}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:s,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=G(a,s,"raw_stream_output.txt");if(!Y(c))return JSON.stringify({error:`No log found in ${s}`});let d=Qe(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:s,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${r}. Use: list, result, events, log, search`})}}function _c(n,e){let t=String(n?.runId||"all"),r=Number(n?.tail||2e3),s=t==="all"?[...U.keys()]:[t];if(s.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let i=s.map(c=>{let d=U.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=yn(d.logPath,r),u=String(d.error||"").slice(-Math.max(200,r));return{...yc({run:d,logTail:l,errorTail:u}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:u}}),o=i.filter(c=>c.status==="failed"||c.status==="error"),a=i.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:i.length,failed:o.length,active:a.length,diagnoses:i})}function bc(n,e){let t=n?.directory||"test-specs",r=de(e,t);if(!Y(r))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let i=function(o,a){for(let c of Xe(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?i(G(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&s.push(d)}},s=[];return i(r,""),JSON.stringify({specs:s.map(o=>`${t}/${o}`),total:s.length,directory:t})}catch(s){return JSON.stringify({error:s.message})}}import{spawn as kc}from"child_process";import{existsSync as W,mkdirSync as wc,readdirSync as gn,statSync as Sc,readFileSync as Ic}from"fs";import{resolve as At,join as Z,basename as vc}from"path";var Et=".zibby/repos";function et(n,e,t={}){return new Promise((r,s)=>{let i=kc(n,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";i.stdout.on("data",c=>{o+=c.toString()}),i.stderr.on("data",c=>{a+=c.toString()}),i.on("close",c=>{c!==0?s(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):r(o.trim())}),i.on("error",c=>s(c))})}var se={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
589
+ ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function Gc(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function Kc(r,e,t){let n={...r},i=String(n.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let s=null;if(kn.test(i)&&!i.startsWith("inline:")){let l=await Mc(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,u]of q.entries())if(u?.ticketKey===o&&!(u?.status!=="running"&&u?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:u.status,reused:!0,message:`A run for ${o} is already ${u.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let l=ge(e,i);if(!V(l))return kn.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=Nn(t?.options?.config);if(Dt()>=a){let l=Rn(),u=n.ticketKey||l,p={runId:l,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};q.set(l,p),ae.push({args:{...n,_queuedRunId:l},cwd:e,context:t}),U(u,"\u23F3",`Queued (${Dt()}/${a} running, ${ae.length} queued)`);let m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return s&&(m.resolvedFromJiraIssue=s,m.message+=` (spec built from Jira ${s})`),JSON.stringify(m)}let c=Date.now()-Ut;c<gn&&Ut>0&&await new Promise(l=>setTimeout(l,gn-c)),Ut=Date.now();let d=xn(n,e,t);return s?Gc(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function xn(r,e,t){let{spec:n,ticketKey:i,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||Rn(),l=n,u=!1;if(n.startsWith("inline:")){u=!0;let R=Pc(e);hn(R,{recursive:!0}),l=H(R,`${d}.txt`),Ec(l,n.slice(7).trim(),"utf-8")}let p=ge(e,".zibby","output","runs");hn(p,{recursive:!0});let m=H(p,`${d}.log`),f=$c(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),On&&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=vn("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:u,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},w=i||d,T="";function G(R){let O=Tn(R).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=ge(e,Jt,qt,g.sessionId)),O.startsWith("\u250C ")||O.startsWith("\u250C ")){let x=O.slice(2).trim();g.currentNode=x,at&&U(w,"\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),at&&U(w,"\u2714",`${g.currentNode||"node"} done ${x.replace("done","").trim()}`),g.currentNode=null):x.startsWith("failed")&&(at&&U(w,"\u2718",`${g.currentNode||"node"} failed ${x.replace("failed","").trim()}`),g.currentNode=null)}else O.includes("Workflow completed")&&(g.currentNode=null,at&&U(w,"\u2714",`Workflow completed (${yn(Date.now()-g.startTime)})`))}function we(R){let O=R.toString();g.output+=O,f.write(O),g.output.length>5e4&&(g.output=g.output.slice(-3e4)),T+=O;let D=T.split(`
590
+ `);T=D.pop();for(let x of D)G(x)}return b.stdout.on("data",we),b.stderr.on("data",R=>{let O=R.toString();g.error+=O,f.write(O),g.error.length>2e4&&(g.error=g.error.slice(-1e4))}),b.on("close",R=>{g.status=R===0?"passed":"failed",g.exitCode=R,g.endTime=Date.now(),T&&G(T),f.end();let O=yn(Date.now()-g.startTime);if(R===0?U(w,"\u2705",`Passed (${O})`):U(w,"\u274C",`Failed (${O})`),g.isInline)try{Lc(g.specPath)}catch{}_n()}),b.on("error",R=>{g.status="error",g.error+=`
591
+ Spawn error: ${R.message}`,U(w,"\u274C",`Spawn error: ${R.message}`),f.end(),_n()}),g._child=b,q.set(d,g),JSON.stringify({runId:d,spec:g.spec,ticketKey:g.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 Fc(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let s=[...q.entries()].map(([l,u])=>{let p=wn(u),m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:u.status,elapsed:p.elapsed,exitCode:u.exitCode,sessionId:u.sessionId||null};return u.status==="running"?(m.currentNode=p.currentNode,m.completedNodes=p.completedNodes,m.progress=p.progress):m.outputTail=u.output.slice(-500),m}),o=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=q.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 Sn(r,e){if(e.status==="queued"){let t=ae.findIndex(n=>n.args._queuedRunId===r);return t>=0&&ae.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 Hc(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let n=[];for(let[i,s]of q.entries())(s.status==="running"||s.status==="queued")&&n.push(Sn(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=q.get(e);return JSON.stringify(t?Sn(e,t):{error:`Run not found: ${e}`})}function zc(r,e){let t=q.get(r);if(t?.sessionPath&&V(t.sessionPath))return t.sessionPath;if(t?.sessionId){let n=ge(e,Jt,qt,t.sessionId);if(V(n))return n}return null}function En(r,e=""){let t=[];if(!V(r))return t;for(let n of dt(r,{withFileTypes:!0})){let i=e?`${e}/${n.name}`:n.name;if(n.isDirectory())t.push(...En(H(r,n.name),i));else{let s=jc(H(r,n.name));t.push({path:i,size:s.size})}}return t}function In(r){if(!V(r))return null;try{return JSON.parse(lt(r,"utf-8"))}catch{return null}}function Ln(r,e=2e3){if(!r||!V(r))return"";try{return lt(r,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function Yc({run:r,logTail:e,errorTail:t}){let i=`${e||""}
592
+ ${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 Wc(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=ge(e,Jt,qt);if(!V(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=s.toLowerCase();for(let u of dt(c,{withFileTypes:!0})){if(!u.isDirectory())continue;let p=H(c,u.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let y=H(p,f);if(V(y))try{let _=lt(y,"utf-8");if(_.toLowerCase().includes(l)){let b=_.toLowerCase().indexOf(l),g=Math.max(0,b-100),w=Math.min(_.length,b+s.length+100);d.push({sessionId:u.name,artifact:h,snippet:_.slice(g,w)})}}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=q.get(t),d=Ln(c?.logPath,o);if(d)return JSON.stringify({runId:t,source:"run-log",totalLength:d.length,tail:d})}let a=zc(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=En(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=In(H(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=In(H(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=H(a,i,"raw_stream_output.txt");if(!V(c))return JSON.stringify({error:`No log found in ${i}`});let d=lt(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 Zc(r,e){let t=String(r?.runId||"all"),n=Number(r?.tail||2e3),i=t==="all"?[...q.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=q.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=Ln(d.logPath,n),u=String(d.error||"").slice(-Math.max(200,n));return{...Yc({run:d,logTail:l,errorTail:u}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:u}}),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 Vc(r,e){let t=r?.directory||"test-specs",n=ge(e,t);if(!V(n))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let s=function(o,a){for(let c of dt(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(H(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})}}import{spawn as Qc}from"child_process";import{existsSync as Q,mkdirSync as Xc,readdirSync as $n,statSync as el,readFileSync as tl}from"fs";import{resolve as Mt,join as X,basename as rl}from"path";var Gt=".zibby/repos";function ut(r,e,t={}){return new Promise((n,i)=>{let s=Qc(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 ce={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
590
593
  You can clone and explore git repositories locally for codebase analysis:
591
594
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
592
595
  - git_list_repos: List locally cloned repos
@@ -597,7 +600,7 @@ When a test ticket lacks context, use this workflow:
597
600
  2. Use git_explore to understand the project structure
598
601
  3. Use shell commands (grep, cat) to read specific files for deeper understanding
599
602
  4. Use GitHub/GitLab skills to read related PRs and commits
600
- 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(n,e,t){let r=t?.options?.workspace||process.cwd();try{switch(n){case"git_checkout":return await Nc(e,r);case"git_list_repos":return Oc(e,r);case"git_explore":return Rc(e,r);default:return JSON.stringify({error:`Unknown tool: ${n}`})}}catch(s){return JSON.stringify({error:s.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 Nc(n,e){let{url:t,branch:r,shallow:s=!0,name:i}=n;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=i||vc(t.replace(/\.git$/,"")),a=At(e,Et);wc(a,{recursive:!0});let c=Z(a,o),d=t,l=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,p=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(u&&p)try{let h=new URL(p).host;t.includes(h)&&(d=t.replace(`https://${h}`,`https://oauth2:${u}@${h}`))}catch{}if(W(Z(c,".git"))){let h=r?`git -C "${c}" fetch origin ${r} && git -C "${c}" checkout ${r} && git -C "${c}" pull origin ${r}`:`git -C "${c}" pull`;await et(h,e);let _=await et(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:r||"default",head:_})}let m=["git","clone"];s&&m.push("--depth","1"),r&&m.push("--branch",r),m.push(`"${d}"`,`"${c}"`),await et(m.join(" "),e);let f=await et(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:r||"default",shallow:s,head:f})}function Oc(n,e){let t=At(e,Et);if(!W(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let r=[];for(let s of gn(t,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=Z(t,s.name);if(!W(Z(i,".git")))continue;let o=Sc(i);r.push({name:s.name,path:i,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:r,total:r.length,directory:t})}function Rc(n,e){let{repo:t,depth:r=2}=n,s=At(e,Et,t);if(!W(s))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let i={repo:t,path:s},o=Z(s,"package.json");if(W(o))try{let m=JSON.parse(Ic(o,"utf-8"));i.packageJson={name:m.name,version:m.version,scripts:m.scripts?Object.keys(m.scripts):[],dependencies:m.dependencies?Object.keys(m.dependencies).slice(0,30):[],devDependencies:m.devDependencies?Object.keys(m.devDependencies).slice(0,20):[]},m.dependencies?.react?i.framework="React":m.dependencies?.next?i.framework="Next.js":m.dependencies?.vue?i.framework="Vue":m.dependencies?.angular?i.framework="Angular":m.dependencies?.express?i.framework="Express":m.dependencies?.fastify&&(i.framework="Fastify")}catch{}let a=Z(s,"pyproject.toml");W(a)&&(i.language="Python");let c=Z(s,"go.mod");W(c)&&(i.language="Go");let d=Z(s,"Cargo.toml");W(d)&&(i.language="Rust"),W(o)&&(i.language=i.language||"JavaScript/TypeScript");let l=[];function u(m,f,h){if(h>r)return;let _;try{_=gn(m,{withFileTypes:!0})}catch{return}let g=_.filter(b=>!b.name.startsWith(".")&&b.name!=="node_modules"&&b.name!=="__pycache__"&&b.name!=="dist"&&b.name!=="build"&&b.name!==".git").sort((b,y)=>b.isDirectory()!==y.isDirectory()?b.isDirectory()?-1:1:b.name.localeCompare(y.name));for(let b of g){let y=b.isDirectory();l.push(`${f}${y?"\u{1F4C1}":"\u{1F4C4}"} ${b.name}`),y&&h<r&&u(Z(m,b.name),`${f} `,h+1)}}u(s,"",1),i.tree=l.slice(0,80),l.length>80&&(i.treeTruncated=!0);let p=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return i.keyFilesFound=p.filter(m=>W(Z(s,m))),JSON.stringify(i)}function _n(n){let e=(n||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return e?{provider:"github",owner:e[1],repo:e[2]}:(e=(n||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),e?{provider:"gitlab",owner:e[1],repo:e[2]}:null)}var bn={...se,id:"git-write",envKeys:[...se.envKeys||[],...he.envKeys||[],...ye.envKeys||[]].filter((n,e,t)=>t.indexOf(n)===e),promptFragment:`${se.promptFragment}
603
+ 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 nl(e,n);case"git_list_repos":return il(e,n);case"git_explore":return sl(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"git_checkout",description:"Clone a git repository locally (or pull latest if already cloned). Auto-authenticates with GitHub/GitLab tokens if available.",input_schema:{type:"object",properties:{url:{type:"string",description:'Repository URL (e.g. "https://github.com/org/repo" or "org/repo" shorthand for GitHub)'},branch:{type:"string",description:"Branch to checkout (default: repo default branch)"},shallow:{type:"boolean",description:"Shallow clone with depth 1 (default: true, faster)"},name:{type:"string",description:"Local directory name override (default: repo name from URL)"}},required:["url"]}},{name:"git_list_repos",description:"List locally cloned repositories",input_schema:{type:"object",properties:{}}},{name:"git_explore",description:"Quick structural overview of a cloned repo: key files, package.json info, directory tree (top 2 levels), detected framework/language",input_schema:{type:"object",properties:{repo:{type:"string",description:"Repo name (as listed by git_list_repos)"},depth:{type:"number",description:"Directory tree depth (default: 2)"}},required:["repo"]}}]};async function nl(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||rl(t.replace(/\.git$/,"")),a=Mt(e,Gt);Xc(a,{recursive:!0});let c=X(a,o),d=t,l=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,p=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(u&&p)try{let h=new URL(p).host;t.includes(h)&&(d=t.replace(`https://${h}`,`https://oauth2:${u}@${h}`))}catch{}if(Q(X(c,".git"))){let h=n?`git -C "${c}" fetch origin ${n} && git -C "${c}" checkout ${n} && git -C "${c}" pull origin ${n}`:`git -C "${c}" pull`;await ut(h,e);let y=await ut(`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 ut(m.join(" "),e);let f=await ut(`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 il(r,e){let t=Mt(e,Gt);if(!Q(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let i of $n(t,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=X(t,i.name);if(!Q(X(s,".git")))continue;let o=el(s);n.push({name:i.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:t})}function sl(r,e){let{repo:t,depth:n=2}=r,i=Mt(e,Gt,t);if(!Q(i))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let s={repo:t,path:i},o=X(i,"package.json");if(Q(o))try{let m=JSON.parse(tl(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=X(i,"pyproject.toml");Q(a)&&(s.language="Python");let c=X(i,"go.mod");Q(c)&&(s.language="Go");let d=X(i,"Cargo.toml");Q(d)&&(s.language="Rust"),Q(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function u(m,f,h){if(h>n)return;let y;try{y=$n(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&&u(X(m,b.name),`${f} `,h+1)}}u(i,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let p=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return s.keyFilesFound=p.filter(m=>Q(X(i,m))),JSON.stringify(s)}function jn(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 Pn={...ce,id:"git-write",envKeys:[...ce.envKeys||[],...ve.envKeys||[],...Ne.envKeys||[]].filter((r,e,t)=>t.indexOf(r)===e),promptFragment:`${ce.promptFragment}
601
604
 
602
605
  ## Opening a pull request / merge request (git_open_pr)
603
606
  After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
@@ -609,7 +612,7 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
609
612
  To MERGE an open PR/MR, use the provider-agnostic tool:
610
613
  - git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
611
614
  { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
612
- 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(n,e,t){if(n!=="git_open_pr"&&n!=="git_merge_pr")return se.handleToolCall(n,e,t);try{let r=e||{},s=r.repoUrl||r.repo_url||r.url;if(!s)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(n==="git_merge_pr"){let l=r.number??r.iid??r.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let u=_n(s);return u?u.provider==="github"?he.handleToolCall("github_merge_pr",{owner:u.owner,repo:u.repo,number:l,mergeMethod:r.mergeMethod},t):ye.handleToolCall("gitlab_accept_mr",{project:`${u.owner}/${u.repo}`,iid:l},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${s}. git_merge_pr supports github.com and gitlab.com.`})}let i=r.head||r.source_branch||r.sourceBranch||r.branch,o=r.base||r.target_branch||r.targetBranch,{title:a,body:c}=r;if(!i||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=_n(s);return d?d.provider==="github"?he.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:i,base:o,title:a,body:c},t):ye.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:i,target_branch:o,title:a,description:c},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${s}. git_open_pr supports github.com and gitlab.com.`})}catch(r){return JSON.stringify({error:r.message})}},tools:[...se.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 vn}from"child_process";import{existsSync as Ct,mkdirSync as Nn}from"fs";import{join as Q,basename as Tc}from"path";import{randomBytes as Ac}from"crypto";import{pathToFileURL as je}from"url";import{createRequire as On}from"module";var $t=".zibby/memory",Rn="dolt",Tn={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},jt="mem0",xt=new Map,tt=new Map,rt=!1,Ec=On(import.meta.url),ot=()=>Ac(8).toString("hex"),ue=()=>new Date().toISOString(),xc=[`CREATE TABLE IF NOT EXISTS chat_memory (
615
+ 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 ce.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 u=jn(i);return u?u.provider==="github"?ve.handleToolCall("github_merge_pr",{owner:u.owner,repo:u.repo,number:l,mergeMethod:n.mergeMethod},t):Ne.handleToolCall("gitlab_accept_mr",{project:`${u.owner}/${u.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=jn(i);return d?d.provider==="github"?ve.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:s,base:o,title:a,body:c},t):Ne.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:[...ce.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 Jn}from"child_process";import{existsSync as Wt,mkdirSync as Bn}from"fs";import{join as re,basename as ol}from"path";import{randomBytes as al}from"crypto";import{pathToFileURL as Fe}from"url";import{createRequire as Mn}from"module";var Ht=".zibby/memory",Gn="dolt",Kn={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},zt="mem0",Kt=new Map,pt=new Map,mt=!1,cl=Mn(import.meta.url),yt=()=>al(8).toString("hex"),ye=()=>new Date().toISOString(),ll=[`CREATE TABLE IF NOT EXISTS chat_memory (
613
616
  id VARCHAR(64) PRIMARY KEY,
614
617
  memory_key VARCHAR(160),
615
618
  category VARCHAR(32) NOT NULL,
@@ -640,10 +643,10 @@ To MERGE an open PR/MR, use the provider-agnostic tool:
640
643
  tasks_failed INT DEFAULT 0,
641
644
  key_facts TEXT,
642
645
  created_at VARCHAR(32) NOT NULL
643
- )`],kn=new Set;function q(n,e){return vn(Rn,e,{...Tn,cwd:n})}function ie(n,e){try{let t=q(n,["sql","-q",e,"-r","json"]);return JSON.parse(t.trim()).rows||[]}catch{return[]}}function D(n,e){q(n,["sql","-q",e])}function nt(n){if(kn.has(n))return!0;if(!Ct(Q(n,".dolt"))){if(!Lc())return!1;Nn(n,{recursive:!0}),q(n,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${xc.join(`;
644
- `)};`;D(n,e);try{D(n,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{D(n,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return kn.add(n),!0}function Lc(){try{return vn(Rn,["version"],{...Tn,timeout:5e3}),!0}catch{return!1}}function S(n){return n==null?"NULL":`'${String(n).replace(/'/g,"''")}'`}function Pt(n){return String(n||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function ke(n){return n==="long"?3:n==="mid"?2:n==="short"?1:0}function Ut(n,e){let t=["short","mid","long"].includes(n)?n:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(e||"").toLowerCase())&&t==="short"?"mid":t}function An(n){let e=new Map;for(let t of n||[]){let r=Pt(t.content),s=t.memory_key?`key:${t.memory_key}`:r?`norm:${r}`:"";if(!s)continue;let i=e.get(s);if(!i){e.set(s,t);continue}let o=ke(i.tier),a=ke(t.tier);if(a>o){e.set(s,t);continue}a===o&&Number(t.relevance||0)>Number(i.relevance||0)&&e.set(s,t)}return[...e.values()]}function it(n,e){let t=String(n??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function $e(n,e){let t={recentSessions:Array.isArray(n?.recentSessions)?n.recentSessions:[],topMemories:Array.isArray(n?.topMemories)?n.topMemories:[],taskStats:Array.isArray(n?.taskStats)?n.taskStats:[],ticketFilter:n?.ticketFilter||null,backend:e||String(n?.backend||jt),error:n?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function wn(n){let e=[];if(n.recentSessions?.length>0){e.push("Recent sessions:");for(let t of n.recentSessions.slice(0,3))t?.summary?.trim()&&e.push(`- ${it(t.summary,150)}${t.tickets?` [${t.tickets}]`:""}`)}if(n.topMemories?.length>0){e.push("Known facts:");for(let t of n.topMemories.slice(0,10)){let r=t.tier==="long"?"\u2605":"\xB7";e.push(`${r} [${t.category}] ${it(t.content,120)}`)}}return e.length===0?"":`## Memory Context
646
+ )`],Cn=new Set;function J(r,e){return Jn(Gn,e,{...Kn,cwd:r})}function le(r,e){try{let t=J(r,["sql","-q",e,"-r","json"]);return JSON.parse(t.trim()).rows||[]}catch{return[]}}function B(r,e){J(r,["sql","-q",e])}function ft(r){if(Cn.has(r))return!0;if(!Wt(re(r,".dolt"))){if(!dl())return!1;Bn(r,{recursive:!0}),J(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${ll.join(`;
647
+ `)};`;B(r,e);try{B(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{B(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return Cn.add(r),!0}function dl(){try{return Jn(Gn,["version"],{...Kn,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function Yt(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function Te(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function Zt(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 Fn(r){let e=new Map;for(let t of r||[]){let n=Yt(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=Te(s.tier),a=Te(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 gt(r,e){let t=String(r??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function Ke(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||zt),error:r?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function Un(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(`- ${gt(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}] ${gt(t.content,120)}`)}}return e.length===0?"":`## Memory Context
645
648
  ${e.join(`
646
- `)}`}function st(n){return{backend:n.backend,recentSessions:n.recentSessions.slice(0,3).map(e=>({summary:it(String(e?.summary||""),160),tickets:e?.tickets||null,created_at:e?.created_at||null})),topMemories:n.topMemories.slice(0,8).map(e=>({category:e?.category||null,tier:e?.tier||null,content:it(String(e?.content||""),140),source:e?.source||null})),taskStats:n.taskStats,error:n.error||null}}async function $c(n,e){let t=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(t==="mem0"||t==="dolt")return t;let r=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(r==="mem0"||r==="dolt")return r;if(tt.has(n))return tt.get(n);try{let s=Q(n,".zibby.config.mjs");if(Ct(s)){let i=await import(je(s).href),o=String(i?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return tt.set(n,o),o}}catch{}return tt.set(n,jt),jt}function En(n){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${Tc(n||process.cwd())}`}var jc="mem0";function xn(n){let e=Q(n,$t,jc);return{dir:e,vectorDbPath:Q(e,"vectors.db"),historyDbPath:Q(e,"history.db")}}function Pc(n){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(),r=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),s=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),i=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=xn(n||process.cwd());return{llm:{provider:"openai",config:{model:r,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:s,embeddingDims:i,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:i,dbPath:o}},historyDbPath:a}}async function Ln(n){let e=n||process.cwd();if(xt.has(e))return xt.get(e);let t;try{let a=On(je(Q(e,"package.json")).href).resolve("mem0ai/oss");t=await import(je(a).href)}catch{try{let o=Ec.resolve("mem0ai/oss");t=await import(je(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 r=t?.Memory;if(!r)throw new Error("mem0ai/oss does not export Memory");let s=Pc(e);if(s)try{Nn(xn(e).dir,{recursive:!0})}catch{}let i=s?new r(s):new r;return xt.set(e,i),i}function Sn(n,e="mid"){return(Array.isArray(n)?n:Array.isArray(n?.results)?n.results:[]).map(r=>({id:r?.id||ot(),memory_key:r?.metadata?.memoryKey||r?.metadata?.memory_key||null,category:r?.metadata?.category||"fact",content:r?.memory||r?.content||"",source:r?.metadata?.source||"mem0",ticket_key:r?.metadata?.ticketKey||r?.metadata?.ticket_key||null,tier:Ut(r?.metadata?.tier||e,r?.metadata?.category||"fact"),relevance:Number(r?.score??r?.metadata?.relevance??.8),created_at:r?.created_at||r?.metadata?.created_at||ue()})).filter(r=>String(r.content||"").trim().length>0)}var we={id:"dolt",store:(n,e)=>jn(n,e),recall:(n,e)=>Bc(n,e),brief:(n,e)=>Mc(n,e),endSession:(n,e)=>Cn(n,e),logTask:(n,e)=>Un(n,e),taskHistory:(n,e)=>qn(n,e)},Cc={id:"mem0",store:(n,e,t)=>Jc(n,e,t),recall:(n,e,t)=>Pn(n,e,t),brief:(n,e,t)=>Gc(n,e,t),endSession:(n,e)=>Cn(n,e),logTask:(n,e)=>Un(n,e),taskHistory:(n,e)=>qn(n,e)},Uc={dolt:we,mem0:Cc};async function In(n,e){let t=await $c(n,e);return Uc[t]||we}var $n={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
649
+ `)}`}function ht(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:gt(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:gt(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function ul(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(pt.has(r))return pt.get(r);try{let i=re(r,".zibby.config.mjs");if(Wt(i)){let s=await import(Fe(i).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return pt.set(r,o),o}}catch{}return pt.set(r,zt),zt}function Hn(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${ol(r||process.cwd())}`}var pl="mem0";function zn(r){let e=re(r,Ht,pl);return{dir:e,vectorDbPath:re(e,"vectors.db"),historyDbPath:re(e,"history.db")}}function ml(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}=zn(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 Yn(r){let e=r||process.cwd();if(Kt.has(e))return Kt.get(e);let t;try{let a=Mn(Fe(re(e,"package.json")).href).resolve("mem0ai/oss");t=await import(Fe(a).href)}catch{try{let o=cl.resolve("mem0ai/oss");t=await import(Fe(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=ml(e);if(i)try{Bn(zn(e).dir,{recursive:!0})}catch{}let s=i?new n(i):new n;return Kt.set(e,s),s}function Dn(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||yt(),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:Zt(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||ye()})).filter(n=>String(n.content||"").trim().length>0)}var Ae={id:"dolt",store:(r,e)=>Zn(r,e),recall:(r,e)=>bl(r,e),brief:(r,e)=>kl(r,e),endSession:(r,e)=>Qn(r,e),logTask:(r,e)=>Xn(r,e),taskHistory:(r,e)=>ei(r,e)},fl={id:"mem0",store:(r,e,t)=>_l(r,e,t),recall:(r,e,t)=>Vn(r,e,t),brief:(r,e,t)=>wl(r,e,t),endSession:(r,e)=>Qn(r,e),logTask:(r,e)=>Xn(r,e),taskHistory:(r,e)=>ei(r,e)},hl={dolt:Ae,mem0:fl};async function qn(r,e){let t=await ul(r,e);return hl[t]||Ae}var Wn={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
647
650
  You have persistent memory across sessions. Use it to avoid losing context:
648
651
  - **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
649
652
  - **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
@@ -659,40 +662,40 @@ You have persistent memory across sessions. Use it to avoid losing context:
659
662
  - When the user's request is complete: call memory_end_session
660
663
 
661
664
  ### Categories for memory_store
662
- fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(n,e={}){let t=n?.options?.workspace||process.cwd(),r=Q(t,$t),s=await In(t,n),i=s.id;if(i==="dolt"&&!nt(r)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:i,brief:$e({backend:i,error:o},i),promptContext:"",debugPreview:st($e({backend:i,error:o},i)),error:o}}try{let o=await s.brief(e,r,t),a=JSON.parse(o||"{}"),c=$e({...a,backend:i},i);return{backend:i,brief:c,promptContext:wn(c),debugPreview:st(c),error:c.error||null}}catch(o){if(i==="mem0"&&s!==we&&nt(r)){if(!rt){rt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
663
- `)}catch{}}try{let d=await we.brief(e,r,t),l=JSON.parse(d||"{}"),u=$e({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:u,promptContext:wn(u),debugPreview:st(u),error:u.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=$e({backend:i,error:a},i);return{backend:i,brief:c,promptContext:"",debugPreview:st(c),error:a}}},async handleToolCall(n,e,t){let r=t?.options?.workspace||process.cwd(),s=Q(r,$t),i=await In(r,t),o=i.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(n))&&!nt(s))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(n){case"memory_store":return d.store(e,s,r);case"memory_recall":return d.recall(e,s,r);case"memory_brief":return d.brief(e,s,r);case"memory_end_session":return d.endSession(e,s,r);case"task_log":return d.logTask(e,s,r);case"task_history":return d.taskHistory(e,s,r);default:return JSON.stringify({error:`Unknown tool: ${n}`})}};try{return await c(i)}catch(d){if(o==="mem0"&&i!==we){if(nt(s)){if(!rt){rt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
664
- `)}catch{}}try{return await c(we)}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 jn(n,e){let{content:t,category:r,source:s,ticketKey:i,tier:o,memoryKey:a}=n;if(!t||!r)return JSON.stringify({error:"content and category are required"});let c=Pt(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=Ut(o,r),l=d==="long"?1:d==="mid"?.8:.5,u=String(a||"").trim().slice(0,160);if(u){let g=ie(e,`SELECT id, tier, relevance
665
+ fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,e={}){let t=r?.options?.workspace||process.cwd(),n=re(t,Ht),i=await qn(t,r),s=i.id;if(s==="dolt"&&!ft(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:Ke({backend:s,error:o},s),promptContext:"",debugPreview:ht(Ke({backend:s,error:o},s)),error:o}}try{let o=await i.brief(e,n,t),a=JSON.parse(o||"{}"),c=Ke({...a,backend:s},s);return{backend:s,brief:c,promptContext:Un(c),debugPreview:ht(c),error:c.error||null}}catch(o){if(s==="mem0"&&i!==Ae&&ft(n)){if(!mt){mt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
666
+ `)}catch{}}try{let d=await Ae.brief(e,n,t),l=JSON.parse(d||"{}"),u=Ke({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:u,promptContext:Un(u),debugPreview:ht(u),error:u.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=Ke({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:ht(c),error:a}}},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd(),i=re(n,Ht),s=await qn(n,t),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!ft(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!==Ae){if(ft(i)){if(!mt){mt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
667
+ `)}catch{}}try{return await c(Ae)}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 Zn(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=Yt(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=Zt(o,n),l=d==="long"?1:d==="mid"?.8:.5,u=String(a||"").trim().slice(0,160);if(u){let _=le(e,`SELECT id, tier, relevance
665
668
  FROM chat_memory
666
669
  WHERE memory_key = ${S(u)}
667
670
  ORDER BY created_at DESC
668
- LIMIT 1`)[0];if(g){let b=String(g.tier||"mid"),y=Number(g.relevance||0),w=ke(d)>ke(b)?d:b,A=Math.max(l,y);D(e,`UPDATE chat_memory
671
+ LIMIT 1`)[0];if(_){let b=String(_.tier||"mid"),g=Number(_.relevance||0),w=Te(d)>Te(b)?d:b,T=Math.max(l,g);B(e,`UPDATE chat_memory
669
672
  SET content = ${S(t)},
670
- category = ${S(r)},
671
- source = ${S(s)},
672
- ticket_key = ${S(i)},
673
+ category = ${S(n)},
674
+ source = ${S(i)},
675
+ ticket_key = ${S(s)},
673
676
  tier = ${S(w)},
674
- relevance = ${A},
675
- created_at = ${S(ue())}
676
- WHERE id = ${S(g.id)}`);try{q(e,["add","."]),q(e,["commit","-m",`memory upsert: ${r} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:g.id,category:r,tier:w,memoryKey:u,upserted:!0})}}let m=ie(e,`SELECT id, content, tier, relevance
677
+ relevance = ${T},
678
+ created_at = ${S(ye())}
679
+ WHERE id = ${S(_.id)}`);try{J(e,["add","."]),J(e,["commit","-m",`memory upsert: ${n} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:_.id,category:n,tier:w,memoryKey:u,upserted:!0})}}let m=le(e,`SELECT id, content, tier, relevance
677
680
  FROM chat_memory
678
- WHERE category = ${S(r)}
681
+ WHERE category = ${S(n)}
679
682
  ORDER BY created_at DESC
680
- LIMIT 200`).find(_=>Pt(_.content)===c);if(m){let _=String(m.tier||"mid"),g=Number(m.relevance||0),b=ke(d)>ke(_),y=l>g;if(b||y){D(e,`UPDATE chat_memory
681
- SET tier = ${S(b?d:_)},
682
- relevance = ${Math.max(l,g)}
683
- WHERE id = ${S(m.id)}`);try{q(e,["add","."]),q(e,["commit","-m",`memory promote: ${r} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:r,tier:b?d:_,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:r,tier:_,deduped:!0,promoted:!1})}let f=ot(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;D(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
684
- VALUES (${S(f)}, ${S(u||null)}, ${S(r)}, ${S(t)}, ${S(s)}, ${S(i)}, ${S(h)}, ${S(d)}, ${l}, ${S(ue())})`);try{q(e,["add","."]),q(e,["commit","-m",`memory: ${r} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:r,tier:d,memoryKey:u||null,stored:t.slice(0,100)})}function qc(n){let e=String(n||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var Lt=new Map;async function Dc(n,e){if(typeof n=="boolean")return n;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return qc(process.env.ZIBBY_MEM0_INFER);let t=e||process.cwd();if(Lt.has(t))return Lt.get(t);let r=!1;try{let s=Q(t,".zibby.config.mjs");Ct(s)&&(r=(await import(je(s).href))?.default?.memory?.infer===!0)}catch{}return Lt.set(t,r),r}async function Jc(n,e,t){let{content:r,category:s,source:i,ticketKey:o,tier:a,memoryKey:c,infer:d}=n;if(!r||!s)return JSON.stringify({error:"content and category are required"});try{let l=await Ln(t),u=En(t),p=Ut(a,s),m=await Dc(d,t);return await l.add([{role:"user",content:String(r)}],{userId:u,infer:m,metadata:{memoryKey:c||null,category:s,tier:p,source:i||"zibby-chat",ticketKey:o||null,created_at:ue()}}),JSON.stringify({ok:!0,backend:"mem0",userId:u,category:s,tier:p,infer:m,memoryKey:c||null,stored:String(r).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function Bc(n,e){let{query:t,category:r,ticketKey:s,tier:i,limit:o=20}=n,a=[];t&&a.push(`content LIKE ${S(`%${t}%`)}`),r&&a.push(`category = ${S(r)}`),s&&a.push(`ticket_key = ${S(s)}`),i&&a.push(`tier = ${S(i)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
683
+ LIMIT 200`).find(y=>Yt(y.content)===c);if(m){let y=String(m.tier||"mid"),_=Number(m.relevance||0),b=Te(d)>Te(y),g=l>_;if(b||g){B(e,`UPDATE chat_memory
684
+ SET tier = ${S(b?d:y)},
685
+ relevance = ${Math.max(l,_)}
686
+ WHERE id = ${S(m.id)}`);try{J(e,["add","."]),J(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=yt(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;B(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
687
+ VALUES (${S(f)}, ${S(u||null)}, ${S(n)}, ${S(t)}, ${S(i)}, ${S(s)}, ${S(h)}, ${S(d)}, ${l}, ${S(ye())})`);try{J(e,["add","."]),J(e,["commit","-m",`memory: ${n} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:n,tier:d,memoryKey:u||null,stored:t.slice(0,100)})}function gl(r){let e=String(r||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var Ft=new Map;async function yl(r,e){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return gl(process.env.ZIBBY_MEM0_INFER);let t=e||process.cwd();if(Ft.has(t))return Ft.get(t);let n=!1;try{let i=re(t,".zibby.config.mjs");Wt(i)&&(n=(await import(Fe(i).href))?.default?.memory?.infer===!0)}catch{}return Ft.set(t,n),n}async function _l(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 Yn(t),u=Hn(t),p=Zt(a,i),m=await yl(d,t);return await l.add([{role:"user",content:String(n)}],{userId:u,infer:m,metadata:{memoryKey:c||null,category:i,tier:p,source:s||"zibby-chat",ticketKey:o||null,created_at:ye()}}),JSON.stringify({ok:!0,backend:"mem0",userId:u,category:i,tier:p,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 bl(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
685
688
  FROM chat_memory ${a.length>0?`WHERE ${a.join(" AND ")}`:""}
686
689
  ORDER BY relevance DESC, created_at DESC
687
- LIMIT ${o}`,l=ie(e,d);return JSON.stringify({total:l.length,memories:l})}async function Pn(n,e,t){let{query:r,category:s,ticketKey:i,tier:o,limit:a=20}=n;try{let c=await Ln(t),d=En(t),l=[];if(r&&String(r).trim()){let u=await c.search(String(r),{filters:{user_id:d},topK:a});l=Sn(u)}else{let u=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=Sn(u)}return s&&(l=l.filter(u=>u.category===s)),i&&(l=l.filter(u=>u.ticket_key===i)),o&&(l=l.filter(u=>u.tier===o)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function Mc(n,e){let{ticketKey:t}=n;Fc(e);let s=ie(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
688
- FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),i=t?`AND ticket_key = ${S(t)}`:"",o=ie(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
689
- WHERE tier = 'long' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=ie(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
690
- WHERE tier = 'mid' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 8`),d=ie(e,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
691
- GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=An([...o,...a]);return JSON.stringify({recentSessions:s,topMemories:l,taskStats:d,ticketFilter:t||null})}async function Gc(n,e,t){let{ticketKey:r}=n,s=await Pn({limit:80},e,t),i=JSON.parse(s||"{}"),o=Array.isArray(i.memories)?i.memories:[];r&&(o=o.filter(p=>p.ticket_key===r));let a=p=>{let m=Date.parse(String(p?.created_at||""))||0;return Number(p?.relevance||0)*1e12+m},c=(p,m)=>a(m)-a(p),d=o.filter(p=>p.tier==="long").sort(c).slice(0,10),l=o.filter(p=>p.tier==="mid").sort(c).slice(0,8),u=An([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:u,taskStats:[],ticketFilter:r||null,backend:"mem0"})}function Cn(n,e){let{summary:t,tickets:r,tasksRun:s=0,tasksPassed:i=0,tasksFailed:o=0,keyFacts:a}=n;if(!t)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${ot()}`;if(D(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
692
- VALUES (${S(c)}, ${S(t)}, ${S(r)}, ${s}, ${i}, ${o}, ${S(a)}, ${S(ue())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))jn({content:d,category:"fact",source:"session_summary",tier:"mid"},e);Kc(e);try{q(e,["add","."]),q(e,["commit","-m",`session end: ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:t.slice(0,200)})}function Un(n,e){let{title:t,type:r,status:s,ticketKey:i,specPath:o,resultSummary:a}=n;if(!t||!r||!s)return JSON.stringify({error:"title, type, and status are required"});let c=ot(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;D(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
693
- VALUES (${S(c)}, ${S(i)}, ${S(r)}, ${S(t)}, ${S(s)}, ${S(o)}, ${S(d)}, ${S(a)}, ${S(ue())}, ${S(ue())})`);try{q(e,["add","."]),q(e,["commit","-m",`task: ${s} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:t,type:r,status:s})}function qn(n,e){let{ticketKey:t,type:r,status:s,limit:i=20}=n,o=[];t&&o.push(`ticket_key = ${S(t)}`),r&&o.push(`type = ${S(r)}`),s&&o.push(`status = ${S(s)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
690
+ LIMIT ${o}`,l=le(e,d);return JSON.stringify({total:l.length,memories:l})}async function Vn(r,e,t){let{query:n,category:i,ticketKey:s,tier:o,limit:a=20}=r;try{let c=await Yn(t),d=Hn(t),l=[];if(n&&String(n).trim()){let u=await c.search(String(n),{filters:{user_id:d},topK:a});l=Dn(u)}else{let u=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=Dn(u)}return i&&(l=l.filter(u=>u.category===i)),s&&(l=l.filter(u=>u.ticket_key===s)),o&&(l=l.filter(u=>u.tier===o)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function kl(r,e){let{ticketKey:t}=r;Il(e);let i=le(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
691
+ FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),s=t?`AND ticket_key = ${S(t)}`:"",o=le(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
692
+ WHERE tier = 'long' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=le(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
693
+ WHERE tier = 'mid' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 8`),d=le(e,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
694
+ GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=Fn([...o,...a]);return JSON.stringify({recentSessions:i,topMemories:l,taskStats:d,ticketFilter:t||null})}async function wl(r,e,t){let{ticketKey:n}=r,i=await Vn({limit:80},e,t),s=JSON.parse(i||"{}"),o=Array.isArray(s.memories)?s.memories:[];n&&(o=o.filter(p=>p.ticket_key===n));let a=p=>{let m=Date.parse(String(p?.created_at||""))||0;return Number(p?.relevance||0)*1e12+m},c=(p,m)=>a(m)-a(p),d=o.filter(p=>p.tier==="long").sort(c).slice(0,10),l=o.filter(p=>p.tier==="mid").sort(c).slice(0,8),u=Fn([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:u,taskStats:[],ticketFilter:n||null,backend:"mem0"})}function Qn(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_${yt()}`;if(B(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
695
+ VALUES (${S(c)}, ${S(t)}, ${S(n)}, ${i}, ${s}, ${o}, ${S(a)}, ${S(ye())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))Zn({content:d,category:"fact",source:"session_summary",tier:"mid"},e);Sl(e);try{J(e,["add","."]),J(e,["commit","-m",`session end: ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:t.slice(0,200)})}function Xn(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=yt(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;B(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
696
+ VALUES (${S(c)}, ${S(s)}, ${S(n)}, ${S(t)}, ${S(i)}, ${S(o)}, ${S(d)}, ${S(a)}, ${S(ye())}, ${S(ye())})`);try{J(e,["add","."]),J(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 ei(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
694
697
  FROM chat_tasks ${o.length>0?`WHERE ${o.join(" AND ")}`:""}
695
- ORDER BY created_at DESC LIMIT ${i}`,d=ie(e,c);return JSON.stringify({total:d.length,tasks:d})}function Kc(n){try{D(n,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),D(n,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),D(n,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),D(n,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function Fc(n){try{let e=new Date(Date.now()-864e5).toISOString();D(n,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(e)}`)}catch{}}import{existsSync as Dn,readFileSync as Hc}from"node:fs";import{homedir as zc}from"node:os";import{join as Yc,dirname as Wc,resolve as Zc}from"node:path";import{fileURLToPath as Vc}from"node:url";function Qc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Wc(Vc(import.meta.url)),e=Zc(n,"..","bin","mcp-skill.mjs");return Dn(e)?e:null}function Xc(){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 n=Yc(zc(),".zibby","config.json");return Dn(n)&&JSON.parse(Hc(n,"utf-8")).sessionToken||null}catch{return null}}function el(){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 tl(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function qt(n){return`${tl()}:${n}`}async function Dt(n,e){let t=Xc();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let r=`${el()}/credits/review-memory`,s=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:n,...e})});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`KV memory ${n} failed (${s.status}): ${i.slice(0,300)}`)}return s.json()}var Jn={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)
698
+ ORDER BY created_at DESC LIMIT ${s}`,d=le(e,c);return JSON.stringify({total:d.length,tasks:d})}function Sl(r){try{B(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),B(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),B(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),B(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function Il(r){try{let e=new Date(Date.now()-864e5).toISOString();B(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(e)}`)}catch{}}import{existsSync as ti,readFileSync as vl}from"node:fs";import{homedir as Nl}from"node:os";import{join as Ol,dirname as Rl,resolve as Tl}from"node:path";import{fileURLToPath as Al}from"node:url";function xl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Rl(Al(import.meta.url)),e=Tl(r,"..","bin","mcp-skill.mjs");return ti(e)?e:null}function El(){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=Ol(Nl(),".zibby","config.json");return ti(r)&&JSON.parse(vl(r,"utf-8")).sessionToken||null}catch{return null}}function Ll(){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 $l(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Vt(r){return`${$l()}:${r}`}async function Qt(r,e){let t=El();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${Ll()}/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)
696
699
  You have a PRIVATE per-agent key-value memory that survives across your
697
700
  stateless runs. It is automatically namespaced to YOU (this agent type) \u2014 other
698
701
  agents cannot see or collide with your entries, and you don't need to prefix
@@ -707,7 +710,7 @@ Tools:
707
710
  Use to record durable facts \u2014 e.g. dedup markers, prior decisions, summaries.
708
711
 
709
712
  Your namespace is added for you automatically; pass plain keys like
710
- "seen#owner/repo#42" or "lastRun".`,resolve(){let n=Qc();if(!n)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:[n,"../dist/kvMemory.js","kvMemorySkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"kv_recall":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});let r=await Dt("recall",{scope:qt(t)});return JSON.stringify(r)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let r=await Dt("recall-prefix",{scopePrefix:qt(t)});return JSON.stringify(r)}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 r={scope:qt(t),content:e.content};e.metadata!=null&&(r.metadata=e.metadata);let s=await Dt("store",r);return JSON.stringify(s)}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 Mn,readFileSync as rl}from"node:fs";import{homedir as nl}from"node:os";import{join as sl,dirname as il,resolve as ol}from"node:path";import{fileURLToPath as al}from"node:url";function cl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=il(al(import.meta.url)),e=ol(n,"..","bin","mcp-skill.mjs");return Mn(e)?e:null}function Gn(){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 n=sl(nl(),".zibby","config.json");return Mn(n)&&JSON.parse(rl(n,"utf-8")).sessionToken||null}catch{return null}}function Kn(){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 Bn(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function ll(){let n={};for(let[e,t]of Object.entries(process.env)){let r=/^ZIBBY_STORE__(.+)$/.exec(e);if(!r)continue;let s=typeof t=="string"?t.trim():"";s&&(n[r[1]]=s)}return n}var Fn={};function Jt(n){let e={...ll(),...Fn},t=Object.keys(e),r=typeof n=="string"?n.trim():"";return r?Object.prototype.hasOwnProperty.call(e,r)?{storeId:e[r],name:r}:{error:`unknown store '${r}'; 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 dl(n){let e=Gn();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${Kn()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!t.ok){let r=await t.text().catch(()=>"");throw new Error(`ensure_store failed (${t.status}): ${r.slice(0,300)}`)}return t.json()}async function Bt(n,e,t){let r=Gn();if(!r)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let s=`${Kn()}/datasets/stores/${encodeURIComponent(n)}/${e}`,i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Store ${e} failed (${i.status}): ${o.slice(0,300)}`)}return i.json()}var Hn={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)
713
+ "seen#owner/repo#42" or "lastRun".`,resolve(){let r=xl();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 Qt("recall",{scope:Vt(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 Qt("recall-prefix",{scopePrefix:Vt(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:Vt(t),content:e.content};e.metadata!=null&&(n.metadata=e.metadata);let i=await Qt("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 ii,readFileSync as jl}from"node:fs";import{homedir as Pl}from"node:os";import{join as Cl,dirname as Ul,resolve as Dl}from"node:path";import{fileURLToPath as ql}from"node:url";function Jl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ul(ql(import.meta.url)),e=Dl(r,"..","bin","mcp-skill.mjs");return ii(e)?e:null}function si(){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=Cl(Pl(),".zibby","config.json");return ii(r)&&JSON.parse(jl(r,"utf-8")).sessionToken||null}catch{return null}}function oi(){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 ni(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Bl(){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 ai={};function Xt(r){let e={...Bl(),...ai},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 Ml(r){let e=si();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${oi()}/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 er(r,e,t){let n=si();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${oi()}/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 ci={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)
711
714
  You have one or more durable stores for STRUCTURED records that survive across
712
715
  your stateless runs. Unlike key-value memory (for picking up where you left
713
716
  off), this is for accumulating DATA you want to QUERY and AGGREGATE later \u2014 e.g.
@@ -743,13 +746,31 @@ Tools:
743
746
  - sqlite_query: (sqlite stores) Run a SELECT (optionally with \`params\` for safe
744
747
  binding). Returns { columns, rows }. Read-only \u2014 never changes data.
745
748
  Pick the tool that matches the store's TYPE; using a dataset tool on a sqlite
746
- store (or vice-versa) is rejected.`,resolve(){let n=cl();if(!n)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:[n,"../dist/datasetStore.js","datasetStoreSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(n,e){try{switch(n){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=Jt(e?.store);if(t.error)return JSON.stringify({error:t.error});let r=typeof e?.agent=="string"&&e.agent.trim()?e.agent.trim():Bn(),s={record:e.record,agent:r};typeof e?.description=="string"&&e.description.trim()&&(s.description=e.description.trim());let i=await Bt(t.storeId,"append",s);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}case"dataset_query":{let t=Jt(e?.store);if(t.error)return JSON.stringify({error:t.error});let r={};for(let i of["select","where","groupBy","orderBy","limit","since","until","agent"])e?.[i]!=null&&(r[i]=e[i]);let s=await Bt(t.storeId,"query",r);return JSON.stringify({...s,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 r=typeof e?.type=="string"&&e.type.trim()?e.type.trim().toLowerCase():"sqlite",s=typeof e?.description=="string"?e.description.trim():"",i=await dl({name:t,type:r,description:s,namespace:Bn()});return i?.storeId&&(Fn[t]=i.storeId),JSON.stringify({...i,store:t})}case"sqlite_exec":case"sqlite_query":{let t=Jt(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 r={sql:e.sql};Array.isArray(e?.params)&&(r.params=e.params);let s=await Bt(t.storeId,"sql",r);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 ul}from"node:module";import{existsSync as Zn,mkdirSync as pl,writeFileSync as zn}from"node:fs";import{dirname as Vn,join as Se,resolve as Qn}from"node:path";import{fileURLToPath as Xn}from"node:url";var es=ul(import.meta.url),Mt=null;function ml(){return Mt||(Mt=es("echarts")),Mt}var Gt=null;function fl(){return Gt||(Gt=es("@resvg/resvg-js")),Gt}var hl=800,yl=600,gl=4096,_l=16,Yn=60,ts="Noto Sans";function bl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Vn(Xn(import.meta.url)),e=Qn(n,"..","bin","mcp-skill.mjs");return Zn(e)?e:null}function kl(){let n=Vn(Xn(import.meta.url)),e=Qn(n,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>Se(e,t)).filter(t=>Zn(t))}function wl(){let n=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=n||(e?Se(e,"chart-render"):Se(process.cwd(),".zibby","output","charts"));return pl(t,{recursive:!0}),t}function pe(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}function Wn(n,e){let t=Number(n);return Number.isFinite(t)?Math.max(_l,Math.min(gl,Math.round(t))):e}function Kt(n){return typeof n!="string"||n.length<=Yn?n:`${n.slice(0,Yn-1)}\u2026`}function at(n){if(Array.isArray(n))for(let e=0;e<n.length;e++){let t=n[e];typeof t=="string"?n[e]=Kt(t):pe(t)&&typeof t.name=="string"&&(t.name=Kt(t.name))}}function Sl(n){for(let r of["xAxis","yAxis"]){let s=Array.isArray(n[r])?n[r]:n[r]?[n[r]]:[];for(let i of s)pe(i)&&at(i.data)}let e=Array.isArray(n.radar)?n.radar:n.radar?[n.radar]:[];for(let r of e)pe(r)&&at(r.indicator);pe(n.legend)&&at(n.legend.data);let t=Array.isArray(n.series)?n.series:n.series?[n.series]:[];for(let r of t)pe(r)&&(typeof r.name=="string"&&(r.name=Kt(r.name)),at(r.data))}function Il(n){let e=JSON.parse(JSON.stringify(n));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),pe(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=ts),Sl(e),e}function vl(n){return typeof n!="string"?null:n.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Nl(n,e,t){let s=ml().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return s.setOption(n),s.renderToSVGString()}finally{s.dispose()}}function Ol(n){let{Resvg:e}=fl();return new e(n,{font:{fontFiles:kl(),loadSystemFonts:!0,defaultFontFamily:ts}}).render().asPng()}var rs={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)
749
+ store (or vice-versa) is rejected.`,resolve(){let r=Jl();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=Xt(e?.store);if(t.error)return JSON.stringify({error:t.error});let n=typeof e?.agent=="string"&&e.agent.trim()?e.agent.trim():ni(),i={record:e.record,agent:n};typeof e?.description=="string"&&e.description.trim()&&(i.description=e.description.trim());let s=await er(t.storeId,"append",i);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"dataset_query":{let t=Xt(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 er(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 Ml({name:t,type:n,description:i,namespace:ni()});return s?.storeId&&(ai[t]=s.storeId),JSON.stringify({...s,store:t})}case"sqlite_exec":case"sqlite_query":{let t=Xt(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 er(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 Gl}from"node:module";import{existsSync as pi,mkdirSync as Kl,writeFileSync as li}from"node:fs";import{dirname as mi,join as xe,resolve as fi}from"node:path";import{fileURLToPath as hi}from"node:url";var gi=Gl(import.meta.url),tr=null;function Fl(){return tr||(tr=gi("echarts")),tr}var rr=null;function Hl(){return rr||(rr=gi("@resvg/resvg-js")),rr}var zl=800,Yl=600,Wl=4096,Zl=16,di=60,yi="Noto Sans";function Vl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=mi(hi(import.meta.url)),e=fi(r,"..","bin","mcp-skill.mjs");return pi(e)?e:null}function Ql(){let r=mi(hi(import.meta.url)),e=fi(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>xe(e,t)).filter(t=>pi(t))}function Xl(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?xe(e,"chart-render"):xe(process.cwd(),".zibby","output","charts"));return Kl(t,{recursive:!0}),t}function _e(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function ui(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(Zl,Math.min(Wl,Math.round(t))):e}function nr(r){return typeof r!="string"||r.length<=di?r:`${r.slice(0,di-1)}\u2026`}function _t(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=nr(t):_e(t)&&typeof t.name=="string"&&(t.name=nr(t.name))}}function ed(r){for(let n of["xAxis","yAxis"]){let i=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let s of i)_e(s)&&_t(s.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of e)_e(n)&&_t(n.indicator);_e(r.legend)&&_t(r.legend.data);let t=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of t)_e(n)&&(typeof n.name=="string"&&(n.name=nr(n.name)),_t(n.data))}function td(r){let e=JSON.parse(JSON.stringify(r));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),_e(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=yi),ed(e),e}function rd(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function nd(r,e,t){let i=Fl().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return i.setOption(r),i.renderToSVGString()}finally{i.dispose()}}function id(r){let{Resvg:e}=Hl();return new e(r,{font:{fontFiles:Ql(),loadSystemFonts:!0,defaultFontFamily:yi}}).render().asPng()}var _i={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)
747
750
  You can render charts LOCALLY with the chart_render tool \u2014 pass a standard
748
751
  Apache ECharts option object as \`spec\` (any chart type: bar, line, pie,
749
752
  radar, scatter, heatmap, \u2026). It renders server-side to SVG/PNG files in the
750
753
  run's output folder (auto-attached to the run as artifacts) and returns the
751
754
  file paths. No browser, no external chart service \u2014 the data never leaves
752
- the machine. Don't set animation (it's forced off). Default 800\xD7600 PNG.`,resolve({sessionPath:n,nodeName:e}={}){let t=bl();if(!t)return{command:null,args:[],env:{},description:this.description};let r={},s=n&&e?Se(n,e):null;s&&(r.ZIBBY_NODE_SESSION_PATH=s),n&&(r.ZIBBY_SESSION_PATH=n);for(let i of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!r[i]&&process.env[i]&&(r[i]=process.env[i]);return{type:"stdio",command:"node",args:[t,"../dist/chartRender.js","chartRenderSkill"],env:r,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){if(n!=="chart_render")return JSON.stringify({error:`Unknown tool: ${n}`});try{let t=e?.spec;if(!pe(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 r=Wn(e?.width,hl),s=Wn(e?.height,yl),i=["svg","png","both"].includes(e?.output)?e.output:"png",o=vl(e?.filename)||`chart-${Date.now()}`,a;try{a=Nl(Il(t),r,s)}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=wl(),d=[];if(i==="svg"||i==="both"){let l=Se(c,`${o}.svg`);zn(l,a,"utf-8"),d.push({path:l,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}if(i==="png"||i==="both"){let l;try{l=Ol(a)}catch(p){return JSON.stringify({error:`PNG rasterization failed: ${p.message}. Retry with output:'svg' if you only need the vector.`})}let u=Se(c,`${o}.png`);zn(u,l),d.push({path:u,format:"png",bytes:l.length})}return JSON.stringify({ok:!0,width:r,height:s,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{dirname as Rl,resolve as Tl}from"path";import{fileURLToPath as Al}from"url";import{existsSync as El}from"fs";function xl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Rl(Al(import.meta.url)),e=Tl(n,"..","bin","mcp-skill.mjs");return El(e)?e:null}function Ll(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function $l(){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 jl={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:[]}},ns={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 n=xl();if(!n)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:[n,"../dist/triggerAgent.js","triggerAgentSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(n,e={}){if(n!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${n}`});try{let t=process.env.PROJECT_ID,r=Ll(),s=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(!r)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!s)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let i=`${$l()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(s)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(i,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify({input: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 u=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:s,executionId:u,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[jl]};import{spawnSync as Pl}from"node:child_process";import{existsSync as ct,mkdirSync as ss,readdirSync as Cl,writeFileSync as Ul}from"node:fs";import{createHash as ql}from"node:crypto";import{join as lt}from"node:path";function is(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function os(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let n=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return n?lt(n,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function Dl(){let n=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=lt(n,".zibby","repos");try{if(ct(e)){let t=Cl(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>lt(e,r.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return ct(n)?n:null}function Jl(n){return ql("sha256").update(n).digest("hex").slice(0,16)}var as={id:"codebase-memory",serverName:"codebase_memory",allowedTools:["mcp__codebase_memory__*"],description:"Codebase memory \u2014 code-graph + semantic index over the checked-out repo (architecture, graph search, dependency trace, change detection)",promptFragment:`## Codebase Memory (code-graph + semantic index over THIS repo)
755
+ the machine. Don't set animation (it's forced off). Default 800\xD7600 PNG.`,resolve({sessionPath:r,nodeName:e}={}){let t=Vl();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?xe(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(!_e(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=ui(e?.width,zl),i=ui(e?.height,Yl),s=["svg","png","both"].includes(e?.output)?e.output:"png",o=rd(e?.filename)||`chart-${Date.now()}`,a;try{a=nd(td(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=Xl(),d=[];if(s==="svg"||s==="both"){let l=xe(c,`${o}.svg`);li(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=id(a)}catch(p){return JSON.stringify({error:`PNG rasterization failed: ${p.message}. Retry with output:'svg' if you only need the vector.`})}let u=xe(c,`${o}.png`);li(u,l),d.push({path:u,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 sd}from"node:module";import{existsSync as Si,mkdirSync as od,writeFileSync as bi}from"node:fs";import{dirname as Ii,join as Le,resolve as vi}from"node:path";import{fileURLToPath as Ni}from"node:url";var ad=sd(import.meta.url),ir=null;function cd(){return ir||(ir=ad("@resvg/resvg-js")),ir}var Oi=1200,ld=627,dd=4096,ud=320,pd="#3b82f6",be="Noto Sans",md=3;function fd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ii(Ni(import.meta.url)),e=vi(r,"..","bin","mcp-skill.mjs");return Si(e)?e:null}function hd(){let r=Ii(Ni(import.meta.url)),e=vi(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>Le(e,t)).filter(t=>Si(t))}function gd(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?Le(e,"social-card"):Le(process.cwd(),".zibby","output","social-cards"));return od(t,{recursive:!0}),t}function ki(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(ud,Math.min(dd,Math.round(t))):e}function Ee(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function yd(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function _d(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 Ri(r,e,t){return String(r).length*e*t}function sr(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&&Ri(c,t,n)>e?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function bd(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 wi(r,e,t,n,i){let s=(Array.isArray(r)?r:[]).map(y=>String(y??"").trim()).filter(Boolean).slice(0,md);if(s.length<2)return null;let o=24,a=54,c=26,d=90,l=17,u=s.map(y=>Math.max(96,Ri(y,o,.58)+c*2)),p=u.reduce((y,_)=>y+_,0)+d*(s.length-1),m=e-p/2,f=t+a/2,h=[];for(let y=0;y<s.length;y++){let _=u[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="${be}" font-size="${o}" font-weight="700" fill="${n.pillText}">${Ee(s[y])}</text>`),m+=_,y<s.length-1){let b=m,g=m+d,w=(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="${w.toFixed(1)}" cy="${f}" r="${l}" fill="${i}"/>`,`<path d="M ${(w-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(`
756
+ `),height:a}}function kd(r){let{width:e,height:t,theme:n,accent:i}=r,s=bd(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():"",u=r.subhead?String(r.subhead).trim():"",p=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=e/Oi,h=Math.round(22*f),y=Math.round(29*f),_=u?sr(u,c,y,.52):[],b=Math.round(y*1.28),g=4,w=Math.round(26*f),T=Math.round(20*f),G=Math.round(24*f),we=Math.round(30*f),R=!!(p||m),O=a,D=R?Math.round(110*f):a,x=t-O-D,de=wi(r.diagram,o,0,s,i),mr=($,ie)=>{let je=g+w;return l&&(je+=h+T),je+=ie.length*Math.round($*1.16),_.length&&(je+=G+_.length*b),de&&(je+=we+de.height),je},vt=[76,66,58,50,44,38].map($=>Math.round($*f)),es=4,Se=vt[vt.length-1],Nt=sr(d,c,Se,.6);for(let $ of vt){let ie=sr(d,c,$,.6);if(ie.length<=es&&mr($,ie)<=x){Se=$,Nt=ie;break}}let ts=Math.round(Se*1.16),rs=mr(Se,Nt),K=O+Math.max(0,(x-rs)/2),ee=[];ee.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${s.bg}"/>`);let fr=Math.round(60*f);ee.push(`<rect x="${(o-fr/2).toFixed(1)}" y="${K}" width="${fr}" height="${g}" rx="2" fill="${i}"/>`),K+=g+w,l&&(ee.push(`<text x="${o}" y="${(K+h*.82).toFixed(1)}" text-anchor="middle" font-family="${be}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${i}">${Ee(l)}</text>`),K+=h+T);for(let $ of Nt)ee.push(`<text x="${o}" y="${(K+Se*.82).toFixed(1)}" text-anchor="middle" font-family="${be}" font-size="${Se}" font-weight="700" fill="${s.fg}">${Ee($)}</text>`),K+=ts;if(_.length){K+=G;for(let $ of _)ee.push(`<text x="${o}" y="${(K+y*.82).toFixed(1)}" text-anchor="middle" font-family="${be}" font-size="${y}" font-weight="400" fill="${s.muted}">${Ee($)}</text>`),K+=b}if(de){K+=we;let $=wi(r.diagram,o,K,s,i);$&&ee.push($.svg)}if(R){let $=Math.round(24*f),ie=t-Math.round(46*f);m&&ee.push(`<text x="${a}" y="${ie}" text-anchor="start" font-family="${be}" font-size="${$}" font-weight="400" fill="${s.muted}">${Ee(m)}</text>`),p&&ee.push(`<text x="${e-a}" y="${ie}" text-anchor="end" font-family="${be}" font-size="${$}" font-weight="700" fill="${i}">${Ee(p)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
757
+ ${ee.join(`
758
+ `)}
759
+ </svg>`}function wd(r){let{Resvg:e}=cd();return new e(r,{font:{fontFiles:hd(),loadSystemFonts:!0,defaultFontFamily:be}}).render().asPng()}var Ti={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)
760
+ You can render a BRANDED concept card PNG with the social_card_render tool \u2014 the
761
+ clean, high-signal LinkedIn "concept card" style (bold headline + small uppercase
762
+ eyebrow + optional stat/footer + optional A\u2014\u2713\u2014B diagram). Give it STRUCTURED
763
+ fields that capture the ONE key idea of your post:
764
+ - headline (required): the big, bold line \u2014 the single takeaway.
765
+ - eyebrow: a short uppercase kicker (e.g. "MY WORKFLOW", "OPEN SOURCE").
766
+ - subhead: one supporting line under the headline.
767
+ - stat / footer: e.g. stat "11.8k stars", footer "Apache 2.0".
768
+ - diagram: 2-3 short labels rendered as a chain, e.g. ["Claude Code","Codex"].
769
+ - theme ('dark' default | 'light'), accent (hex).
770
+ It renders server-side to a PNG in the run's output folder and returns
771
+ { ok:true, files:[{ path, format:'png', bytes }] }. Pass the returned \`path\` as
772
+ \`imagePath\` when you draft/publish a LinkedIn post to ATTACH the card as the
773
+ post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=fd();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?Le(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,Oi),i=ki(e?.height,ld),s=e?.theme==="light"?"light":"dark",o=_d(e?.accent,pd),a;try{a=kd({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=wd(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=gd(),l=yd(e?.filename)||`social-card-${Date.now()}`,u=Le(d,`${l}.png`);bi(u,c);let p=[{path:u,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=Le(d,`${l}.svg`);bi(m,a,"utf-8"),p.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:i,theme:s,files:p})}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{dirname as Sd,resolve as Id}from"path";import{fileURLToPath as vd}from"url";import{existsSync as Nd}from"fs";function Od(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Sd(vd(import.meta.url)),e=Id(r,"..","bin","mcp-skill.mjs");return Nd(e)?e:null}function Rd(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function Td(){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 Ad={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:[]}},Ai={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=Od();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=Rd(),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=`${Td()}/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 u=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:u,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[Ad]};import{spawnSync as xd}from"node:child_process";import{existsSync as bt,mkdirSync as xi,readdirSync as Ed,writeFileSync as Ld}from"node:fs";import{createHash as $d}from"node:crypto";import{join as kt}from"node:path";function Ei(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function Li(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?kt(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function jd(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=kt(r,".zibby","repos");try{if(bt(e)){let t=Ed(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>kt(e,n.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return bt(r)?r:null}function Pd(r){return $d("sha256").update(r).digest("hex").slice(0,16)}var $i={id:"codebase-memory",serverName:"codebase_memory",allowedTools:["mcp__codebase_memory__*"],description:"Codebase memory \u2014 code-graph + semantic index over the checked-out repo (architecture, graph search, dependency trace, change detection)",promptFragment:`## Codebase Memory (code-graph + semantic index over THIS repo)
753
774
  The checked-out repository is indexed into a queryable code graph + semantic
754
775
  index. Reach for these instead of blindly grepping when you need structure,
755
776
  relationships, or "where does X live / what depends on Y":
@@ -761,8 +782,8 @@ relationships, or "where does X live / what depends on Y":
761
782
  - get_code_snippet / search_code: pull the exact code for a node / text match.
762
783
  - index_status / list_projects: confirm the index is present before querying.
763
784
  The repo is indexed for you at the start of the run; if a query comes back
764
- empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let n=os();try{ss(n,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:n};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:is(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let n=Dl();if(!n)return{};let e=os();try{ss(e,{recursive:!0})}catch{}let t=lt(e,`.cbm-indexed-${Jl(n)}`);if(ct(t))return{};let r=is();if(!ct(r)&&!process.env.CBM_BIN)return{};let s=Pl(r,["cli","index_repository",JSON.stringify({repo_path:n})],{env:{...process.env,CBM_CACHE_DIR:e},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{Ul(t,`${new Date().toISOString()} status=${s.status}
765
- `)}catch{}}catch{}return{}}};import{existsSync as X,readFileSync as Ce,readdirSync as Ft,mkdirSync as Bl,writeFileSync as Ie,statSync as ds}from"fs";import{join as R,resolve as Ht,relative as us,dirname as ps}from"path";import{fileURLToPath as Ml}from"url";import{createRequire as Gl}from"module";var Kl=Gl(import.meta.url),Fl=`## Workflow Builder
785
+ empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=Li();try{xi(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:Ei(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=jd();if(!r)return{};let e=Li();try{xi(e,{recursive:!0})}catch{}let t=kt(e,`.cbm-indexed-${Pd(r)}`);if(bt(t))return{};let n=Ei();if(!bt(n)&&!process.env.CBM_BIN)return{};let i=xd(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{Ld(t,`${new Date().toISOString()} status=${i.status}
786
+ `)}catch{}}catch{}return{}}};import{existsSync as ne,readFileSync as ze,readdirSync as or,mkdirSync as Cd,writeFileSync as $e,statSync as Ci}from"fs";import{join as A,resolve as ar,relative as Ui,dirname as Di}from"path";import{fileURLToPath as Ud}from"url";import{createRequire as Dd}from"module";var qd=Dd(import.meta.url),Jd=`## Workflow Builder
766
787
 
767
788
  You can help users build custom AI workflows using the Zibby workflow framework.
768
789
 
@@ -872,26 +893,26 @@ Call with no arguments to see all available topics.
872
893
  - Workflow names must be kebab-case (e.g., ticket-triage, pr-review).
873
894
  - State flows through: each node's validated output is stored under its name in state (e.g., state.classify_ticket).
874
895
  - Downstream nodes reference upstream outputs in their prompt function (e.g., \\\`\\\${JSON.stringify(state.classify_ticket, null, 2)}\\\`).
875
- - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,ms=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function fs(n){return`${n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function Pe(n){return`${n.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}Node`}function Hl(n){let e=n?.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 zl(n){let e=Ht(n,".zibby.config.mjs");if(!X(e))return{};try{return(await import(e)).default||{}}catch{return{}}}function Yl(){try{let n=ps(Kl.resolve("@zibby/core/package.json")),e=R(n,"templates","browser-test-automation"),t=Ce(R(e,"nodes","preflight.mjs"),"utf-8"),r=Ce(R(e,"graph.mjs"),"utf-8");return{preflight:t,graph:r}}catch{return null}}var cs=ps(Ml(import.meta.url));function hs(){let n=Ht(cs,"..","..","..","docsite","docs");if(X(n))return n;let e=Ht(cs,"..","docs");return X(e)?e:null}function ls(){let n=hs();if(!n)return[];try{let e=(t,r="")=>{let s=[];for(let i of Ft(t)){let o=R(t,i);try{if(ds(o).isDirectory())s=s.concat(e(o,`${r}${i}/`));else if(i.endsWith(".md")){let a=`${r}${i.replace(/\.md$/,"")}`;s.push(a)}}catch{}}return s};return e(n)}catch{return[]}}function ys(n){let e=hs();if(!e)return null;let t=R(e,`${n}.md`);if(!X(t))return null;try{return Ce(t,"utf-8")}catch{return null}}function Wl(n){let e=n.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(`
876
- `),t=n.edges.map(o=>o.condition?`- ${o.from} \u2192 ${o.to} (conditional: ${o.condition})`:`- ${o.from} \u2192 ${o.to}`).join(`
877
- `),r=Yl(),s=ys("custom-workflows"),i="";return r&&(i+=`
896
+ - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,qi=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function Ji(r){return`${r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function He(r){return`${r.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}Node`}function Bd(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 Md(r){let e=ar(r,".zibby.config.mjs");if(!ne(e))return{};try{return(await import(e)).default||{}}catch{return{}}}function Gd(){try{let r=Di(qd.resolve("@zibby/core/package.json")),e=A(r,"templates","browser-test-automation"),t=ze(A(e,"nodes","preflight.mjs"),"utf-8"),n=ze(A(e,"graph.mjs"),"utf-8");return{preflight:t,graph:n}}catch{return null}}var ji=Di(Ud(import.meta.url));function Bi(){let r=ar(ji,"..","..","..","docsite","docs");if(ne(r))return r;let e=ar(ji,"..","docs");return ne(e)?e:null}function Pi(){let r=Bi();if(!r)return[];try{let e=(t,n="")=>{let i=[];for(let s of or(t)){let o=A(t,s);try{if(Ci(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 Mi(r){let e=Bi();if(!e)return null;let t=A(e,`${r}.md`);if(!ne(t))return null;try{return ze(t,"utf-8")}catch{return null}}function Kd(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(`
897
+ `),t=r.edges.map(o=>o.condition?`- ${o.from} \u2192 ${o.to} (conditional: ${o.condition})`:`- ${o.from} \u2192 ${o.to}`).join(`
898
+ `),n=Gd(),i=Mi("custom-workflows"),s="";return n&&(s+=`
878
899
  ## Real working examples from the Zibby framework
879
900
 
880
901
  ### Example node (preflight.mjs) \u2014 a prompt-only node with Zod schema and onComplete hook:
881
902
  \`\`\`javascript
882
- ${r.preflight}
903
+ ${n.preflight}
883
904
  \`\`\`
884
905
 
885
906
  ### Example graph (graph.mjs) \u2014 WorkflowAgent subclass with conditional routing:
886
907
  \`\`\`javascript
887
- ${r.graph}
908
+ ${n.graph}
888
909
  \`\`\`
889
910
 
890
911
  Study these examples carefully. Your generated code must follow the same patterns exactly.
891
- `),s&&(i+=`
912
+ `),i&&(s+=`
892
913
  ## Full framework documentation (Custom Workflows)
893
- ${s}
894
- `),`Generate the code for a Zibby workflow called "${n.name}".
914
+ ${i}
915
+ `),`Generate the code for a Zibby workflow called "${r.name}".
895
916
 
896
917
  ## Zibby Workflow Framework Reference
897
918
 
@@ -928,11 +949,11 @@ SKILLS.BROWSER, SKILLS.MEMORY, SKILLS.GITHUB, SKILLS.JIRA, SKILLS.SLACK, SKILLS.
928
949
  - Export name: camelCase + "Node" (e.g., \`classifyTicketNode\` for name \`classify_ticket\`)
929
950
  - Prompt function: template literal referencing \`state.input\` and upstream \`state.<node_name>\`
930
951
  - Prompts must be detailed \u2014 tell the agent exactly what to analyze/produce
931
- ${i}
932
- ## Workflow to generate: "${n.name}"
952
+ ${s}
953
+ ## Workflow to generate: "${r.name}"
933
954
 
934
955
  ### Description
935
- ${n.description}
956
+ ${r.description}
936
957
 
937
958
  ### Nodes
938
959
  ${e}
@@ -951,9 +972,9 @@ Return a JSON object with this exact structure:
951
972
  }
952
973
  }
953
974
 
954
- IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function gs(n,e){let t=await zl(e),r=Hl(t);try{let{invokeAgent:s}=await import("@zibby/core"),i=Wl(n),o=await s(i,{state:{agentType:r,config:t,cwd:e,workspace:e}},{model:t?.agent?.[r]?.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(s){return console.warn(`Agent code generation failed (${s.message}), using templates`),Zl(n)}}function Zl(n){let e={};for(let t of n.nodes){let r=Pe(t.name),s=`${t.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,i=t.outputFields?.length?t.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
975
+ IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function Gi(r,e){let t=await Md(e),n=Bd(t);try{let{invokeAgent:i}=await import("@zibby/core"),s=Kd(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`),Fd(r)}}function Fd(r){let e={};for(let t of r.nodes){let n=He(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(`
955
976
  `):` summary: z.string().describe('Summary of the result'),
956
- status: z.enum(['ok', 'warn', 'error']).describe('Overall status'),`,o=n.edges.filter(c=>c.to===t.name&&c.from!=="START").map(c=>`Previous step (${c.from}): \${JSON.stringify(state.${c.from} || {}, null, 2)}`).join(`
977
+ 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(`
957
978
  `),a=o?`${t.description}
958
979
 
959
980
  Input:
@@ -964,25 +985,25 @@ ${o}`:`${t.description}
964
985
  Input:
965
986
  \${JSON.stringify(state.input || {}, null, 2)}`;e[t.name]={code:`import { z } from '@zibby/core';
966
987
 
967
- const ${s} = z.object({
968
- ${i}
988
+ const ${i} = z.object({
989
+ ${s}
969
990
  });
970
991
 
971
- export const ${r} = {
992
+ export const ${n} = {
972
993
  name: '${t.name}',
973
994
  prompt: (state) => \`${a}\`,
974
- outputSchema: ${s},
995
+ outputSchema: ${i},
975
996
  };
976
- `}}return{nodes:e}}function Vl(n,e,t,r){let s=e.toLowerCase(),i=fs(s),o=R(n,".zibby","workflows",s),a=R(o,"nodes");Bl(a,{recursive:!0});let c=t.nodes.map(g=>g.name);for(let g of t.nodes){let b=r.nodes?.[g.name]?.code;b&&Ie(R(a,`${g.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let d=c.map(g=>{let b=Pe(g),y=g.replace(/_/g,"-");return`export { ${b} } from './${y}.mjs';`});Ie(R(a,"index.mjs"),`${d.join(`
997
+ `}}return{nodes:e}}function Hd(r,e,t,n){let i=e.toLowerCase(),s=Ji(i),o=A(r,".zibby","workflows",i),a=A(o,"nodes");Cd(a,{recursive:!0});let c=t.nodes.map(_=>_.name);for(let _ of t.nodes){let b=n.nodes?.[_.name]?.code;b&&$e(A(a,`${_.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let d=c.map(_=>{let b=He(_),g=_.replace(/_/g,"-");return`export { ${b} } from './${g}.mjs';`});$e(A(a,"index.mjs"),`${d.join(`
977
998
  `)}
978
- `,"utf-8");let l=c[0],u=c.map(g=>Pe(g)).join(", "),p=c.map(g=>` graph.addNode('${g}', ${Pe(g)});`).join(`
979
- `),m=t.edges.map(g=>g.condition?` graph.addConditionalEdges('${g.from}', (state) => {
980
- ${g.condition}
981
- });`:` graph.addEdge('${g.from}', '${g.to}');`).join(`
999
+ `,"utf-8");let l=c[0],u=c.map(_=>He(_)).join(", "),p=c.map(_=>` graph.addNode('${_}', ${He(_)});`).join(`
1000
+ `),m=t.edges.map(_=>_.condition?` graph.addConditionalEdges('${_.from}', (state) => {
1001
+ ${_.condition}
1002
+ });`:` graph.addEdge('${_.from}', '${_.to}');`).join(`
982
1003
  `),f=`import { WorkflowAgent, WorkflowGraph } from '@zibby/core';
983
1004
  import { ${u} } from './nodes/index.mjs';
984
1005
 
985
- export class ${i} extends WorkflowAgent {
1006
+ export class ${s} extends WorkflowAgent {
986
1007
  buildGraph() {
987
1008
  const graph = new WorkflowGraph();
988
1009
 
@@ -995,21 +1016,21 @@ ${m}
995
1016
  }
996
1017
 
997
1018
  async onComplete(result) {
998
- console.log(\`[${s}] workflow complete \u2014 success: \${result.success !== false}\`);
1019
+ console.log(\`[${i}] workflow complete \u2014 success: \${result.success !== false}\`);
999
1020
  }
1000
1021
  }
1001
- `;Ie(R(o,"graph.mjs"),f,"utf-8");let h={name:s,description:t.description||`${i} workflow`,entryClass:i,triggers:{api:!0}};Ie(R(o,"workflow.json"),`${JSON.stringify(h,null,2)}
1002
- `,"utf-8");let _=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(g=>`nodes/${g.replace(/_/g,"-")}.mjs`)];return{workflowDir:us(n,o),files:_,className:i,slug:s}}async function Ql(n){let{name:e,description:t,nodes:r,edges:s}=n;if(!e||!ms.test(e.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${e}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!r||r.length===0)return JSON.stringify({error:"At least one node is required."});let i={name:e.toLowerCase(),description:t||`${fs(e.toLowerCase())} workflow`,nodes:r.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:s||[]};if(i.edges.length===0&&i.nodes.length>0){for(let o=0;o<i.nodes.length-1;o++)i.edges.push({from:i.nodes[o].name,to:i.nodes[o+1].name});i.edges.push({from:i.nodes[i.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:i,message:`Workflow "${i.name}" designed with ${i.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:i.nodes.map(o=>o.name),flow:i.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function Xl(n,e){let{name:t,spec:r}=n,s=(t||r?.name||"").toLowerCase();if(!s||!ms.test(s))return JSON.stringify({error:`Invalid workflow name "${s}".`});if(!r||!r.nodes||r.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let i=R(e,".zibby","workflows",s);if(X(i))return JSON.stringify({error:`Workflow "${s}" already exists at .zibby/workflows/${s}/. Delete it first or choose a different name.`});let o=await gs(r,e),a=Vl(e,s,r,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${s}" created at ${a.workflowDir}/`,nextSteps:[`Test locally: zibby start ${s}`,`Deploy to cloud: zibby deploy ${s} --project <project-id>`,`Tail logs: zibby logs --workflow ${s} --project <project-id>`]})}async function ed(n,e){let{workflowName:t,nodeName:r,description:s,inputFields:i,outputFields:o}=n,a=(t||"").toLowerCase(),c=(r||"").replace(/-/g,"_"),d=R(e,".zibby","workflows",a);if(!X(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:s||`Process ${c}`,inputFields:i||[],outputFields:o||[]}],edges:[]},p=(await gs(l,e)).nodes?.[c]?.code;if(!p)return JSON.stringify({error:"Failed to generate node code."});let m=R(d,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;Ie(R(m,f),p,"utf-8");let h=R(m,"index.mjs"),_=Pe(c),g=`export { ${_} } from './${c.replace(/_/g,"-")}.mjs';
1003
- `,b=X(h)?Ce(h,"utf-8"):"";return b.includes(_)||Ie(h,b+g,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:_,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function td(n,e){let{name:t,projectId:r}=n,s=(t||"").toLowerCase();if(!s)return JSON.stringify({error:"Workflow name is required."});if(!r)return JSON.stringify({error:"projectId is required."});let i=R(e,".zibby","workflows",s);if(!X(i))return JSON.stringify({error:`Workflow "${s}" not found at .zibby/workflows/${s}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${R(e,"packages/cli/bin/zibby.js")}" deploy ${s} --project ${r}`,{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 ${s} --project ${r}`,{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 rd(n){let e=R(n,".zibby","workflows");if(!X(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let r=Ft(e).filter(s=>{try{return ds(R(e,s)).isDirectory()}catch{return!1}}).map(s=>{let i=R(e,s,"workflow.json"),o={};try{o=JSON.parse(Ce(i,"utf-8"))}catch{}let a=R(e,s,"nodes"),c=0;try{c=Ft(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:s,description:o.description||"",nodeCount:c,path:us(n,R(e,s))}});return JSON.stringify({workflows:r})}var _s={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:Fl,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(n,e,t){let r=t?.options?.workspace||process.cwd();try{switch(n){case"design_workflow":return await Ql(e);case"build_workflow":return await Xl(e,r);case"add_node":return await ed(e,r);case"deploy_workflow":return await td(e,r);case"list_workflows":return rd(r);case"explore_framework_docs":{let s=(e.topic||"").trim();if(!s){let o=ls();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let i=ys(s);if(!i){let o=ls();return JSON.stringify({error:`Doc "${s}" not found.`,available:o})}return JSON.stringify({topic:s,content:i})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}catch(s){return JSON.stringify({error:s.message})}},resolve(){return null}};import{resolveIntegrationToken as nd}from"@zibby/core/backend-client.js";var Yt=Object.freeze({id:"openai_billing",requiresIntegration:v.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),Wt=Object.freeze({id:"anthropic_billing",requiresIntegration:v.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),Zt=Object.freeze({id:"cursor_admin",requiresIntegration:v.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function bs(n){return Math.floor(n/1e3)}function zt(n){return new Date(n).toISOString().slice(0,10)}function ks(n){return new Date(n).toISOString()}async function Ue(n){let e=await nd(n);if(!e?.token)throw new Error(`${n} token resolver returned no token`);return e.token}async function ws({startMs:n,endMs:e,groupBy:t=["project_id","line_item"]}){let r=await Ue("openai_billing"),s=[],i=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=${bs(n)}`,`end_time=${bs(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{Authorization:`Bearer ${r}`}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`OpenAI costs API ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){i+=1;let f=zt((m.start_time||0)*1e3);for(let h of m.results||[])s.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:s,rawBuckets:i}}async function sd(){let n=await Ue("openai_billing"),t=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${n}`}});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${i.slice(0,200)}`)}let r=await t.json(),s=new Map;for(let i of r.data||[])s.set(i.id,i.name);return s}async function Ss({startMs:n,endMs:e,groupBy:t=["workspace_id"]}){let r=await Ue("anthropic_billing"),s=[],i=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(ks(n))}`,`ending_at=${encodeURIComponent(ks(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Anthropic cost_report ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){i+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])s.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:s,rawBuckets:i}}async function id(){let n=await Ue("anthropic_billing"),t=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${i.slice(0,200)}`)}let r=await t.json(),s=new Map;for(let i of r.data||[])s.set(i.id,i.name);return s}async function Is({startMs:n,endMs:e}){let t=await Ue("cursor_admin"),r=zt(n),s=zt(e),i=`https://api.cursor.com/teams/daily-usage-data?startDate=${r}&endDate=${s}`,o=await fetch(i,{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 u=l.date;for(let p of l.userMetrics||[]){for(let m of p.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:u,costUsd:Number(m.totalCents??0)/100,userEmail:p.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!p.modelUsage||p.modelUsage.length===0)&&c.push({provider:"cursor",day:u,costUsd:Number(p.totalCents??0)/100,userEmail:p.email})}}return{ok:!0,items:c,rawBuckets:d}}async function od({startMs:n,endMs:e}){let[t,r,s]=await Promise.allSettled([ws({startMs:n,endMs:e}),Ss({startMs:n,endMs:e}),Is({startMs:n,endMs:e})]),i=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=i(t),a=i(r),c=i(s),d=[{provider:"openai",totalUsd:o.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,u)=>l+(u.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function ad(n,e){let t=new Map;for(let r of n){let s=e(r);if(!s)continue;let i=t.get(s)||{key:s,totalUsd:0,count:0};i.totalUsd+=r.costUsd||0,i.count+=1,t.set(s,i)}return[...t.values()].sort((r,s)=>s.totalUsd-r.totalUsd)}function cd(n){if(!n.length)return{mean:0,stddev:0};let e=n.reduce((r,s)=>r+s,0)/n.length,t=n.reduce((r,s)=>r+(s-e)**2,0)/n.length;return{mean:e,stddev:Math.sqrt(t)}}import{z as k}from"zod";var qe=["ok","info","warn","critical"],ld=k.object({primary:k.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:k.object({value:k.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:k.enum(["up","down","flat"]).optional(),severity:k.enum(qe).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:k.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),dd=k.object({kind:k.literal("trend"),title:k.string().max(120).optional(),labels:k.array(k.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:k.array(k.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:k.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:k.enum(qe).optional()}),ud=k.object({kind:k.literal("table"),title:k.string().max(120).optional(),headers:k.array(k.string().max(40)).min(1).max(8),rows:k.array(k.array(k.union([k.string().max(200),k.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),pd=k.object({kind:k.literal("callouts"),title:k.string().max(120).optional(),tone:k.enum(qe).default("info").optional(),items:k.array(k.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),md=k.object({kind:k.literal("breakdown"),title:k.string().max(120).optional(),rows:k.array(k.object({label:k.string().min(1).max(80),value:k.string().min(1).max(80),sub:k.string().max(120).optional(),severity:k.enum(qe).optional()})).min(1).max(20)}),fd=k.object({kind:k.literal("paragraph"),title:k.string().max(120).optional(),text:k.string().min(1).max(3e3)}),hd=k.discriminatedUnion("kind",[dd,ud,pd,md,fd]),De=k.object({title:k.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:k.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:ld,sections:k.array(hd).max(20).default([]).superRefine((n,e)=>{n.forEach((t,r)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:k.ZodIssueCode.custom,path:[r,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(s=>s.length===t.headers.length)&&e.addIssue({code:k.ZodIssueCode.custom,path:[r,"rows"],message:"every row must have headers.length entries"})})}),footer:k.object({viewUrl:k.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:k.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),P=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),dt=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),yd=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function ut(n,e,t=12){if(!Number.isFinite(n)||!Number.isFinite(e)||e<=0)return"";let r=Math.max(0,Math.min(1,n/e)),s=Math.round(r*t);return"\u2593".repeat(s)+"\u2591".repeat(t-s)}function Je(n,e){let t=String(n);return t.length>=e?t:t+" ".repeat(e-t.length)}function pt(n,e){let t=String(n);return t.length>=e?t:" ".repeat(e-t.length)+t}function Os({headers:n,rows:e}){let t=n.map((o,a)=>{let c=Math.max(String(o).length,...e.map(d=>String(d[a]??"").length));return Math.min(c,32)}),r=o=>o.map((a,c)=>Je(a,t[c])).join(" "),s=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[r(n),s,...e.map(o=>r(o))].join(`
1004
- `)+"\n```"}function gd(n){let e=De.parse(n),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 r=[`*${e.headline.primary}*`];if(e.headline.delta){let i=dt[e.headline.delta.direction]||"",o=e.headline.delta.severity?P[e.headline.delta.severity]:"";r.push(`${i} ${e.headline.delta.value} ${o}`.trim())}let s=r.join(" ");e.headline.summary&&(s+=`
1005
- `+e.headline.summary),t.push({type:"section",text:{type:"mrkdwn",text:s}});for(let i of e.sections)switch(t.push({type:"divider"}),i.title&&t.push({type:"section",text:{type:"mrkdwn",text:`*${i.title}*`}}),i.kind){case"trend":{let o=Math.max(...i.values),a=i.labels.map((c,d)=>{let l=i.values[d],u=ut(l,o),m=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&l===o||i.highlight==="min"&&l===Math.min(...i.values))&&i.severity?` ${P[i.severity]}`:"";return`${Je(c,10)} ${pt(l.toLocaleString(),8)} ${u}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1006
- `)+"\n```"}});break}case"table":{t.push({type:"section",text:{type:"mrkdwn",text:Os(i)}});break}case"callouts":{let o=P[i.tone||"info"];t.push({type:"section",text:{type:"mrkdwn",text:i.items.map(a=>`${o} ${a}`).join(`
1007
- `)}});break}case"breakdown":{let o=i.rows.map(a=>({type:"mrkdwn",text:`*${a.label}*
1022
+ `;$e(A(o,"graph.mjs"),f,"utf-8");let h={name:i,description:t.description||`${s} workflow`,entryClass:s,triggers:{api:!0}};$e(A(o,"workflow.json"),`${JSON.stringify(h,null,2)}
1023
+ `,"utf-8");let y=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(_=>`nodes/${_.replace(/_/g,"-")}.mjs`)];return{workflowDir:Ui(r,o),files:y,className:s,slug:i}}async function zd(r){let{name:e,description:t,nodes:n,edges:i}=r;if(!e||!qi.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||`${Ji(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 Yd(r,e){let{name:t,spec:n}=r,i=(t||n?.name||"").toLowerCase();if(!i||!qi.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(ne(s))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await Gi(n,e),a=Hd(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 Wd(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(!ne(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:[]},p=(await Gi(l,e)).nodes?.[c]?.code;if(!p)return JSON.stringify({error:"Failed to generate node code."});let m=A(d,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;$e(A(m,f),p,"utf-8");let h=A(m,"index.mjs"),y=He(c),_=`export { ${y} } from './${c.replace(/_/g,"-")}.mjs';
1024
+ `,b=ne(h)?ze(h,"utf-8"):"";return b.includes(y)||$e(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 Zd(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(!ne(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 Vd(r){let e=A(r,".zibby","workflows");if(!ne(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=or(e).filter(i=>{try{return Ci(A(e,i)).isDirectory()}catch{return!1}}).map(i=>{let s=A(e,i,"workflow.json"),o={};try{o=JSON.parse(ze(s,"utf-8"))}catch{}let a=A(e,i,"nodes"),c=0;try{c=or(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:c,path:Ui(r,A(e,i))}});return JSON.stringify({workflows:n})}var Ki={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:Jd,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 zd(e);case"build_workflow":return await Yd(e,n);case"add_node":return await Wd(e,n);case"deploy_workflow":return await Zd(e,n);case"list_workflows":return Vd(n);case"explore_framework_docs":{let i=(e.topic||"").trim();if(!i){let o=Pi();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=Mi(i);if(!s){let o=Pi();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 Qd}from"@zibby/core/backend-client.js";var lr=Object.freeze({id:"openai_billing",requiresIntegration:N.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),dr=Object.freeze({id:"anthropic_billing",requiresIntegration:N.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),ur=Object.freeze({id:"cursor_admin",requiresIntegration:N.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Fi(r){return Math.floor(r/1e3)}function cr(r){return new Date(r).toISOString().slice(0,10)}function Hi(r){return new Date(r).toISOString()}async function Ye(r){let e=await Qd(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function zi({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let n=await Ye("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=${Fi(r)}`,`end_time=${Fi(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{Authorization:`Bearer ${n}`}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`OpenAI costs API ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){s+=1;let f=cr((m.start_time||0)*1e3);for(let h of m.results||[])i.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Xd(){let r=await Ye("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 Yi({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let n=await Ye("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(Hi(r))}`,`ending_at=${encodeURIComponent(Hi(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Anthropic cost_report ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){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(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:i,rawBuckets:s}}async function eu(){let r=await Ye("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 Wi({startMs:r,endMs:e}){let t=await Ye("cursor_admin"),n=cr(r),i=cr(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 u=l.date;for(let p of l.userMetrics||[]){for(let m of p.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:u,costUsd:Number(m.totalCents??0)/100,userEmail:p.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!p.modelUsage||p.modelUsage.length===0)&&c.push({provider:"cursor",day:u,costUsd:Number(p.totalCents??0)/100,userEmail:p.email})}}return{ok:!0,items:c,rawBuckets:d}}async function tu({startMs:r,endMs:e}){let[t,n,i]=await Promise.allSettled([zi({startMs:r,endMs:e}),Yi({startMs:r,endMs:e}),Wi({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,u)=>l+(u.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,u)=>l+(u.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function ru(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 nu(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{z as k}from"zod";var We=["ok","info","warn","critical"],iu=k.object({primary:k.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:k.object({value:k.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:k.enum(["up","down","flat"]).optional(),severity:k.enum(We).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:k.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),su=k.object({kind:k.literal("trend"),title:k.string().max(120).optional(),labels:k.array(k.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:k.array(k.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:k.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:k.enum(We).optional()}),ou=k.object({kind:k.literal("table"),title:k.string().max(120).optional(),headers:k.array(k.string().max(40)).min(1).max(8),rows:k.array(k.array(k.union([k.string().max(200),k.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),au=k.object({kind:k.literal("callouts"),title:k.string().max(120).optional(),tone:k.enum(We).default("info").optional(),items:k.array(k.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),cu=k.object({kind:k.literal("breakdown"),title:k.string().max(120).optional(),rows:k.array(k.object({label:k.string().min(1).max(80),value:k.string().min(1).max(80),sub:k.string().max(120).optional(),severity:k.enum(We).optional()})).min(1).max(20)}),lu=k.object({kind:k.literal("paragraph"),title:k.string().max(120).optional(),text:k.string().min(1).max(3e3)}),du=k.discriminatedUnion("kind",[su,ou,au,cu,lu]),Ze=k.object({title:k.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:k.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:iu,sections:k.array(du).max(20).default([]).superRefine((r,e)=>{r.forEach((t,n)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:k.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:k.ZodIssueCode.custom,path:[n,"rows"],message:"every row must have headers.length entries"})})}),footer:k.object({viewUrl:k.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:k.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),C=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),wt=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),uu=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function St(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 Ve(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function It(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function Qi({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)=>Ve(a,t[c])).join(" "),i=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),i,...e.map(o=>n(o))].join(`
1025
+ `)+"\n```"}function pu(r){let e=Ze.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=wt[e.headline.delta.direction]||"",o=e.headline.delta.severity?C[e.headline.delta.severity]:"";n.push(`${s} ${e.headline.delta.value} ${o}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1026
+ `+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],u=St(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?` ${C[s.severity]}`:"";return`${Ve(c,10)} ${It(l.toLocaleString(),8)} ${u}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1027
+ `)+"\n```"}});break}case"table":{t.push({type:"section",text:{type:"mrkdwn",text:Qi(s)}});break}case"callouts":{let o=C[s.tone||"info"];t.push({type:"section",text:{type:"mrkdwn",text:s.items.map(a=>`${o} ${a}`).join(`
1028
+ `)}});break}case"breakdown":{let o=s.rows.map(a=>({type:"mrkdwn",text:`*${a.label}*
1008
1029
  ${a.value}${a.sub?`
1009
- _${a.sub}_`:""}${a.severity?` ${P[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:i.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let i=[];e.footer.viewUrl&&i.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:e.footer.viewUrl,style:"primary"}),e.footer.rerunUrl&&i.push({type:"button",text:{type:"plain_text",text:"Run again"},url:e.footer.rerunUrl}),t.push({type:"divider"}),t.push({type:"actions",elements:i})}return t}function _d(n){let e=De.parse(n),t=[],r=[`**${e.headline.primary}**`];if(e.headline.delta){let o=dt[e.headline.delta.direction]||"",a=e.headline.delta.severity?P[e.headline.delta.severity]:"";r.push(`${o} ${e.headline.delta.value} ${a}`.trim())}let s=r.join(" ");e.headline.summary&&(s+=`
1010
- `+e.headline.summary),t.push({tag:"div",text:{tag:"lark_md",content:s}});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 u=o.values[l],p=ut(u,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&u===a||o.highlight==="min"&&u===Math.min(...o.values))&&o.severity?` ${P[o.severity]}`:"";return`${Je(d,10)} ${pt(u.toLocaleString(),8)} ${p}${f}`});t.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1011
- `)+"\n```"}});break}case"table":{t.push({tag:"div",text:{tag:"lark_md",content:Os(o)}});break}case"callouts":{let a=P[o.tone||"info"];t.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
1012
- `)}});break}case"breakdown":{let a=o.rows.map(c=>{let d=c.severity?` ${P[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(`
1013
- `)}});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 i="blue";return e.headline.delta?.severity&&(i=yd[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:i},elements:t}}var bd=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),vs=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function me(n,e={}){let t={type:"text",text:{content:String(n).slice(0,2e3)}};return e.annotations&&(t.annotations=e.annotations),[t]}function Vt(n,e){let t={object:"block",type:"paragraph",paragraph:{rich_text:me(n)}};return e&&(t.paragraph.color=e),t}function kd(n){return{object:"block",type:"code",code:{rich_text:me(n),language:"plain text"}}}function wd(n){let e=De.parse(n),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:me(e.title.slice(0,200))}}),e.subtitle&&t.push(Vt(e.subtitle,"gray_background"));let r=[{type:"text",text:{content:e.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(e.headline.delta){let i=dt[e.headline.delta.direction]||"",o=e.headline.delta.severity?P[e.headline.delta.severity]:"",a=` ${i} ${e.headline.delta.value} ${o}`.trimEnd();r.push({type:"text",text:{content:a}})}t.push({object:"block",type:"paragraph",paragraph:{rich_text:r}}),e.headline.summary&&t.push(Vt(e.headline.summary));for(let i of e.sections)switch(t.push({object:"block",type:"divider",divider:{}}),i.title&&t.push({object:"block",type:"heading_2",heading_2:{rich_text:me(i.title)}}),i.kind){case"trend":{let o=Math.max(...i.values),a=Math.min(...i.values),c=i.labels.map((d,l)=>{let u=i.values[l],p=ut(u,o),f=(i.highlight==="last"&&l===i.labels.length-1||i.highlight==="max"&&u===o||i.highlight==="min"&&u===a)&&i.severity?` ${P[i.severity]}`:"";return`${Je(d,10)} ${pt(u.toLocaleString(),8)} ${p}${f}`});t.push(kd(c.join(`
1014
- `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:i.headers.map(c=>me(c))}},a=i.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>me(String(d)))}}));t.push({object:"block",type:"table",table:{table_width:i.headers.length,has_column_header:!0,has_row_header:!1,children:[o,...a]}});break}case"callouts":{let o=i.tone||"info",a=vs[o],c=bd[o];for(let d of i.items)t.push({object:"block",type:"callout",callout:{rich_text:me(d),icon:{type:"emoji",emoji:a},color:c}});break}case"breakdown":{for(let o of i.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:` ${P[o.severity]}`}}),t.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{t.push(Vt(i.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 s=e.headline.delta?.severity?vs[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:s}}function Ns(n){return String(n??"").replace(/\|/g,"\\|")}function Sd(n){let e=De.parse(n),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let r=[`**${e.headline.primary}**`];if(e.headline.delta){let s=dt[e.headline.delta.direction]||"",i=e.headline.delta.severity?P[e.headline.delta.severity]:"";r.push(`${s} ${e.headline.delta.value} ${i}`.trim())}t.push("",r.join(" ")),e.headline.summary&&t.push("",e.headline.summary);for(let s of e.sections)switch(t.push("","---",""),s.title&&t.push(`## ${s.title}`,""),s.kind){case"trend":{let i=Math.max(...s.values),o=Math.min(...s.values),a=s.labels.map((c,d)=>{let l=s.values[d],u=ut(l,i),m=(s.highlight==="last"&&d===s.labels.length-1||s.highlight==="max"&&l===i||s.highlight==="min"&&l===o)&&s.severity?` ${P[s.severity]}`:"";return`${Je(c,10)} ${pt(l.toLocaleString(),8)} ${u}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${s.headers.map(Ns).join(" | ")} |`),t.push(`| ${s.headers.map(()=>"---").join(" | ")} |`);for(let i of s.rows)t.push(`| ${i.map(Ns).join(" | ")} |`);break}case"callouts":{let i=P[s.tone||"info"];for(let o of s.items)t.push(`- ${i} ${o}`);break}case"breakdown":{for(let i of s.rows){let o=i.sub?` _${i.sub}_`:"",a=i.severity?` ${P[i.severity]}`:"";t.push(`- **${i.label}**: ${i.value}${o}${a}`)}break}case"paragraph":{t.push(s.text);break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let s=[];e.footer.viewUrl&&s.push(`[View in Zibby](${e.footer.viewUrl})`),e.footer.rerunUrl&&s.push(`[Run again](${e.footer.rerunUrl})`),t.push("","---","",s.join(" \xB7 "))}return t.join(`
1015
- `)}import{createRequire as Id}from"module";import{fileURLToPath as vd}from"url";import{registerHandlers as Nd}from"@zibby/core/function-skill-registry.js";import{registerSkill as Od}from"@zibby/agent-workflow";var Rd=Id(import.meta.url);function Td(){try{return Rd.resolve("@zibby/core/function-bridge.js")}catch{return null}}var Ad=import.meta.url;function Ed(){let n=Error.prepareStackTrace;try{Error.prepareStackTrace=(r,s)=>s;let t=new Error().stack;for(let r=2;r<t.length;r++){let s=t[r].getFileName();if(s&&s!==Ad&&!s.startsWith("node:"))return s.startsWith("file://")?vd(s):s}return null}finally{Error.prepareStackTrace=n}}function xd(n){if(!n||typeof n!="object")return{type:"object",properties:{},required:[]};let e={},t=[];for(let[r,s]of Object.entries(n))if(typeof s=="string")e[r]={type:s},t.push(r);else{let{required:i,...o}=s;e[r]=o,i!==!1&&t.push(r)}return{type:"object",properties:e,required:t}}function Ld(n,e,t){if(typeof t.handler!="function")throw new Error(`Skill "${n}" must have a handler function`);let r={[n]:t.handler},s=[{name:n,description:t.description||"",input_schema:xd(t.input)}];return Nd(n,r,s),{id:n,type:"function",serverName:n,allowedTools:[`mcp__${n}__*`],description:t.description||`Function skill: ${n}`,envKeys:[],tools:s,resolve(){let i=Td();return i?{command:"node",args:[i,e,n]}:null}}}function $d(n,e){return{id:n,type:"mcp",serverName:e.serverName||n,allowedTools:e.allowedTools||[`mcp__${e.serverName||n}__*`],description:e.description||`MCP skill: ${n}`,envKeys:e.envKeys||[],tools:e.tools||[],resolve:e.resolve,...e.cursorKey&&{cursorKey:e.cursorKey},...e.sessionEnvKey&&{sessionEnvKey:e.sessionEnvKey}}}function Rs(n,e){let t;if("handler"in e){if(typeof e.handler!="function")throw new Error(`Skill "${n}" must have a handler function`);let r=Ed();if(!r)throw new Error(`Could not resolve caller file for skill "${n}".`);t=Ld(n,r,e)}else if(typeof e.resolve=="function")t=$d(n,e);else throw new Error(`Skill "${n}" must have either a handler (function skill) or resolve (MCP skill).`);return Od(t),t}var jd=Rs;import{registerSkill as kf,getSkill as wf,hasSkill as Sf,getAllSkills as If,listSkillIds as vf}from"@zibby/agent-workflow";N(Qt);N(tr);N(he);N(ye);N(sr);N(or);N(ar);N(dr);N(j);N(K);N(mr);N(wr);N(Or);N(xr);N(Dr);N(Jr);N(We);N(Mr);N(mn);N(se);N(bn);N(Kr);N(Wr);N($n);N(Jn);N(Hn);N(rs);N(ns);N(as);N(_s);N(Yt);N(Wt);N(Zt);N({...j,id:"slack_notify"});var ff={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",LINEAR:"linear",PLANE:"plane",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINKEDIN:"linkedin",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",DATASET_STORE:"dataset-store",CHART_RENDER:"chart-render",CODEBASE_MEMORY:"codebase-memory",WORKFLOW_BUILDER:"workflow-builder",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"};export{v as INTEGRATIONS,Cs as INTEGRATION_REGISTRY,qe as REPORT_SEVERITIES,ff as SKILLS,Wt as anthropicBillingSkill,Qt as browserSkill,rs as chartRenderSkill,$n as chatMemorySkill,Jr as chatNotifySkill,as as codebaseMemorySkill,Wr as coreToolsSkill,Zt as cursorAdminSkill,Hn as datasetStoreSkill,mr as discordSkill,od as fetchAllProviders,Ss as fetchAnthropicCosts,id as fetchAnthropicWorkspaces,Is as fetchCursorSpend,ws as fetchOpenAICosts,sd as fetchOpenAIProjects,sr as figmaSkill,jd as functionSkill,If as getAllSkills,wf as getSkill,se as gitSkill,bn as gitWriteSkill,he as githubSkill,ye as gitlabSkill,xr as googleDocsSkill,ad as groupByKey,Sf as hasSkill,tr as jiraSkill,Jn as kvMemorySkill,Dr as larkDocsSkill,K as larkSkill,or as linearSkill,Or as linkedinSkill,vf as listSkillIds,cd as meanStddev,Mr as memorySkill,wr as notionSkill,Yt as openaiBillingSkill,dr as opendesignSkill,ar as planeSkill,kf as registerSkill,De as reportObjectSchema,gd as reportToBlockKit,_d as reportToLarkCard,Sd as reportToMarkdown,wd as reportToNotionBlocks,mn as runnerSkill,We as sentrySkill,Rs as skill,Kr as skillInstallerSkill,j as slackSkill,mn as testRunnerSkill,_s as workflowBuilderSkill};
1030
+ _${a.sub}_`:""}${a.severity?` ${C[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 mu(r){let e=Ze.parse(r),t=[],n=[`**${e.headline.primary}**`];if(e.headline.delta){let o=wt[e.headline.delta.direction]||"",a=e.headline.delta.severity?C[e.headline.delta.severity]:"";n.push(`${o} ${e.headline.delta.value} ${a}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1031
+ `+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 u=o.values[l],p=St(u,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&u===a||o.highlight==="min"&&u===Math.min(...o.values))&&o.severity?` ${C[o.severity]}`:"";return`${Ve(d,10)} ${It(u.toLocaleString(),8)} ${p}${f}`});t.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1032
+ `)+"\n```"}});break}case"table":{t.push({tag:"div",text:{tag:"lark_md",content:Qi(o)}});break}case"callouts":{let a=C[o.tone||"info"];t.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
1033
+ `)}});break}case"breakdown":{let a=o.rows.map(c=>{let d=c.severity?` ${C[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(`
1034
+ `)}});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=uu[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 fu=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),Zi=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function ke(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:ke(r)}};return e&&(t.paragraph.color=e),t}function hu(r){return{object:"block",type:"code",code:{rich_text:ke(r),language:"plain text"}}}function gu(r){let e=Ze.parse(r),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:ke(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=wt[e.headline.delta.direction]||"",o=e.headline.delta.severity?C[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:ke(s.title)}}),s.kind){case"trend":{let o=Math.max(...s.values),a=Math.min(...s.values),c=s.labels.map((d,l)=>{let u=s.values[l],p=St(u,o),f=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&u===o||s.highlight==="min"&&u===a)&&s.severity?` ${C[s.severity]}`:"";return`${Ve(d,10)} ${It(u.toLocaleString(),8)} ${p}${f}`});t.push(hu(c.join(`
1035
+ `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>ke(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>ke(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=Zi[o],c=fu[o];for(let d of s.items)t.push({object:"block",type:"callout",callout:{rich_text:ke(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:` ${C[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?Zi[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:i}}function Vi(r){return String(r??"").replace(/\|/g,"\\|")}function yu(r){let e=Ze.parse(r),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let n=[`**${e.headline.primary}**`];if(e.headline.delta){let i=wt[e.headline.delta.direction]||"",s=e.headline.delta.severity?C[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],u=St(l,s),m=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&l===s||i.highlight==="min"&&l===o)&&i.severity?` ${C[i.severity]}`:"";return`${Ve(c,10)} ${It(l.toLocaleString(),8)} ${u}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${i.headers.map(Vi).join(" | ")} |`),t.push(`| ${i.headers.map(()=>"---").join(" | ")} |`);for(let s of i.rows)t.push(`| ${s.map(Vi).join(" | ")} |`);break}case"callouts":{let s=C[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?` ${C[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(`
1036
+ `)}import{createRequire as _u}from"module";import{fileURLToPath as bu}from"url";import{registerHandlers as ku}from"@zibby/core/function-skill-registry.js";import{registerSkill as wu}from"@zibby/agent-workflow";var Su=_u(import.meta.url);function Iu(){try{return Su.resolve("@zibby/core/function-bridge.js")}catch{return null}}var vu=import.meta.url;function Nu(){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!==vu&&!i.startsWith("node:"))return i.startsWith("file://")?bu(i):i}return null}finally{Error.prepareStackTrace=r}}function Ou(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 Ru(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:Ou(t.input)}];return ku(r,n,i),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:t.description||`Function skill: ${r}`,envKeys:[],tools:i,resolve(){let s=Iu();return s?{command:"node",args:[s,e,r]}:null}}}function Tu(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 Xi(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=Nu();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);t=Ru(r,n,e)}else if(typeof e.resolve=="function")t=Tu(r,e);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return wu(t),t}var Au=Xi;import{registerSkill as wh,getSkill as Sh,hasSkill as Ih,getAllSkills as vh,listSkillIds as Nh}from"@zibby/agent-workflow";v(hr);v(_r);v(ve);v(Ne);v(wr);v(Ir);v(vr);v(Rr);v(P);v(z);v(xr);v(Dr);v(Mr);v(zr);v(tn);v(rn);v(ot);v(sn);v(An);v(ce);v(Pn);v(an);v(pn);v(Wn);v(ri);v(ci);v(_i);v(Ti);v(Ai);v($i);v(Ki);v(lr);v(dr);v(ur);v({...P,id:"slack_notify"});var hh={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",LINEAR:"linear",PLANE:"plane",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINKEDIN:"linkedin",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",DATASET_STORE:"dataset-store",CHART_RENDER:"chart-render",SOCIAL_CARD:"social-card",CODEBASE_MEMORY:"codebase-memory",WORKFLOW_BUILDER:"workflow-builder",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"};export{N as INTEGRATIONS,us as INTEGRATION_REGISTRY,We as REPORT_SEVERITIES,hh as SKILLS,dr as anthropicBillingSkill,hr as browserSkill,_i as chartRenderSkill,Wn as chatMemorySkill,rn as chatNotifySkill,$i as codebaseMemorySkill,pn as coreToolsSkill,ur as cursorAdminSkill,ci as datasetStoreSkill,xr as discordSkill,tu as fetchAllProviders,Yi as fetchAnthropicCosts,eu as fetchAnthropicWorkspaces,Wi as fetchCursorSpend,zi as fetchOpenAICosts,Xd as fetchOpenAIProjects,wr as figmaSkill,Au as functionSkill,vh as getAllSkills,Sh as getSkill,ce as gitSkill,Pn as gitWriteSkill,ve as githubSkill,Ne as gitlabSkill,zr as googleDocsSkill,ru as groupByKey,Ih as hasSkill,_r as jiraSkill,ri as kvMemorySkill,tn as larkDocsSkill,z as larkSkill,Ir as linearSkill,Mr as linkedinSkill,Nh as listSkillIds,nu as meanStddev,sn as memorySkill,Dr as notionSkill,lr as openaiBillingSkill,Rr as opendesignSkill,vr as planeSkill,wh as registerSkill,Ze as reportObjectSchema,pu as reportToBlockKit,mu as reportToLarkCard,yu as reportToMarkdown,gu as reportToNotionBlocks,An as runnerSkill,ot as sentrySkill,Xi as skill,an as skillInstallerSkill,P as slackSkill,Ti as socialCardSkill,An as testRunnerSkill,Ki as workflowBuilderSkill};