@zibby/skills 0.2.15 → 0.2.17

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 ch}from"@zibby/agent-workflow";var cn=Object.freeze(["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"]),gt=new WeakMap;function ln(r){if(!r||r.callsBackend!==!0)return r;if(gt.has(r))return gt.get(r);let t=Object.isExtensible(r)&&!Object.isFrozen(r)?r:{...r};if(gt.set(r,t),gt.set(t,t),t.command||Array.isArray(t.envKeys)){let e=Array.isArray(t.envKeys)?[...t.envKeys]:[];for(let n of cn)e.includes(n)||e.push(n);t.envKeys=e}if(typeof t.resolve=="function"){let e=t.resolve;t.resolve=function(...i){let s=e.apply(this,i);if(!s||!s.command)return s;let o={...s.env||{}};for(let a of cn)o[a]===void 0&&process.env[a]&&(o[a]=process.env[a]);return{...s,env:o}}}return t}import{createRequire as Lo}from"module";import{join as $o}from"path";var Po=Lo(import.meta.url);function Co(){if(process.env.MCP_BROWSER_PATH)return process.env.MCP_BROWSER_PATH;try{return Po.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js")}catch{return null}}var Uo="1280x720",Bo="1280x720";function Jo({headless:r}={}){if(r===!0)return!0;if(r===!1)return!1;let t=process.env.ZIBBY_HEADLESS;return t==="1"||String(t).toLowerCase()==="true"}function qo(r,t){let e=(r||[]).filter(n=>n!=="--headless");return t?[...e,"--headless"]:e}var dn={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 Ry}from"@zibby/agent-workflow";var Sn=Object.freeze(["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"]),Ot=new WeakMap;function vn(r){if(!r||r.callsBackend!==!0)return r;if(Ot.has(r))return Ot.get(r);let t=Object.isExtensible(r)&&!Object.isFrozen(r)?r:{...r};if(Ot.set(r,t),Ot.set(t,t),t.command||Array.isArray(t.envKeys)){let e=Array.isArray(t.envKeys)?[...t.envKeys]:[];for(let n of Sn)e.includes(n)||e.push(n);t.envKeys=e}if(typeof t.resolve=="function"){let e=t.resolve;t.resolve=function(...i){let s=e.apply(this,i);if(!s||!s.command)return s;let o={...s.env||{}};for(let a of Sn)o[a]===void 0&&process.env[a]&&(o[a]=process.env[a]);return{...s,env:o}}}return t}import{createRequire as ca}from"module";import{join as la}from"path";var da=ca(import.meta.url);function pa(){if(process.env.MCP_BROWSER_PATH)return process.env.MCP_BROWSER_PATH;try{return da.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js")}catch{return null}}var ua="1280x720",ma="1280x720";function fa({headless:r}={}){if(r===!0)return!0;if(r===!1)return!1;let t=process.env.ZIBBY_HEADLESS;return t==="1"||String(t).toLowerCase()==="true"}function ha(r,t){let e=(r||[]).filter(n=>n!=="--headless");return t?[...e,"--headless"]:e}var In={id:"browser",serverName:"playwright",cursorKey:"playwright-official",allowedTools:["mcp__playwright__*"],sessionEnvKey:"ZIBBY_SESSION_INFO",description:"Playwright Browser MCP Server",envKeys:[],tools:[],promptFragment:`Execute this test using the browser tools available to you. You MUST make actual browser tool calls \u2014 do not fabricate results.
2
2
  If you DO NOT have access to browser tools \u2192 return {"success": false, "steps": [], "browserClosed": false, "notes": "No browser tools available"}.
3
- DO NOT return success: true unless you ACTUALLY called browser tools.`,resolve({sessionPath:r,workspace:t,nodeName:e,headless:n}={}){let i=Co(),s=r&&e?$o(r,e):null,o=s||r||t||"test-results",a=Jo({headless:n}),c={};if(s&&(c.ZIBBY_NODE_SESSION_PATH=s),r&&(c.ZIBBY_SESSION_PATH=r),!i)throw new Error(`@zibby/mcp-browser is not installed.
3
+ DO NOT return success: true unless you ACTUALLY called browser tools.`,resolve({sessionPath:r,workspace:t,nodeName:e,headless:n}={}){let i=pa(),s=r&&e?la(r,e):null,o=s||r||t||"test-results",a=fa({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:qo([i,"--isolated",`--save-video=${Uo}`,`--viewport-size=${Bo}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as Mo}from"module";import{resolveIntegrationToken as Ko,clearTokenCache as Go}from"@zibby/core/backend-client.js";var I=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Do=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"},lark_docs:{id:"lark_docs",name:"Lark Docs",connectPath:"/integrations?provider=lark_docs"},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"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var Fo=Mo(import.meta.url);function Ho(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return Fo.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var zo=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Yo(r,t){if(!t||!t.length)return r;let e=r;for(let n of t)n.type==="strong"?e=`**${e}**`:n.type==="em"?e=`_${e}_`:n.type==="code"?e=`\`${e}\``:n.type==="strike"?e=`~~${e}~~`:n.type==="link"&&n.attrs?.href&&(e=`[${e}](${n.attrs.href})`);return e}function _t(r,t=0){if(!Array.isArray(r))return"";let e=[];for(let n of r){if(n.type==="text"){e.push(Yo(n.text||"",n.marks));continue}if(n.type==="hardBreak"){e.push(`
6
+ Override: set MCP_BROWSER_PATH to the path of mcp-browser-zibby.js.`);return{command:"node",args:ha([i,"--isolated",`--save-video=${ua}`,`--viewport-size=${ma}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as ga}from"module";import{resolveIntegrationToken as ba,clearTokenCache as _a}from"@zibby/core/backend-client.js";var I=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),ya=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"},lark_docs:{id:"lark_docs",name:"Lark Docs",connectPath:"/integrations?provider=lark_docs"},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"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var ka=ga(import.meta.url);function wa(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return ka.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var Sa=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function va(r,t){if(!t||!t.length)return r;let e=r;for(let n of t)n.type==="strong"?e=`**${e}**`:n.type==="em"?e=`_${e}_`:n.type==="code"?e=`\`${e}\``:n.type==="strike"?e=`~~${e}~~`:n.type==="link"&&n.attrs?.href&&(e=`[${e}](${n.attrs.href})`);return e}function Tt(r,t=0){if(!Array.isArray(r))return"";let e=[];for(let n of r){if(n.type==="text"){e.push(va(n.text||"",n.marks));continue}if(n.type==="hardBreak"){e.push(`
7
7
  `);continue}if(n.type==="rule"){e.push(`
8
8
  ---
9
- `);continue}let i=n.content?_t(n.content,t+1):"";if(n.type==="listItem")e.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${_t(o.content||[],t+1).trim()}`);e.push(`
9
+ `);continue}let i=n.content?Tt(n.content,t+1):"";if(n.type==="listItem")e.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${Tt(o.content||[],t+1).trim()}`);e.push(`
10
10
  ${s.join(`
11
11
  `)}
12
- `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${_t(o.content||[],t+1).trim()}`);e.push(`
12
+ `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${Tt(o.content||[],t+1).trim()}`);e.push(`
13
13
  ${s.join(`
14
14
  `)}
15
15
  `)}else if(n.type==="heading"){let s=n.attrs?.level||2;e.push(`
16
16
 
17
17
  ${"#".repeat(s)} ${i.trim()}
18
18
 
19
- `)}else zo.has(n.type)?e.push(`
19
+ `)}else Sa.has(n.type)?e.push(`
20
20
 
21
21
  ${i}
22
22
  `):e.push(i)}return e.join("").replace(/\n{3,}/g,`
23
23
 
24
- `)}function Le(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function ar(r){return Le(r).replace(/[a-z0-9]+/g,"")}function bt(r,t){let e=Le(r),n=Le(t);if(!e||!n)return 0;if(e===n)return 1;if(e.length===1||n.length===1)return e===n?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=i(e),o=i(n),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of s.entries()){let u=o.get(l)||0;a+=Math.min(p,u)}return 2*a/Math.max(1,c+d)}function me(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Wo(r,t=[]){let e=Array.isArray(t)?t:[];if(e.length===0)return{requested:r||null,resolved:null,strategy:"none"};let n=e.filter(a=>!a.subtask),i=n.length>0?n:e,s=me(r);if(s){let a=i.find(l=>me(l.name)===s);if(a)return{requested:r,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(u=>me(u)===s))continue;let p=i.find(u=>l.some(m=>me(m)===me(u.name)));if(p)return{requested:r,resolved:p,strategy:"alias"}}let d=i.map(l=>({t:l,score:bt(r,l.name)})).sort((l,p)=>p.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:r,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(d=>me(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 pn(r){let t=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,e=await x(`/rest/api/3/issue/createmeta?${t}`),n=Array.isArray(e?.projects)?e.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 un(r,t){if(!r)throw new Error("projectKey is required");let e="sprint is not EMPTY";t==="active"?e="sprint in openSprints()":t==="closed"?e="sprint in closedSprints()":t==="future"&&(e="sprint in futureSprints()");let n=`project = ${r} AND ${e} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(n)}&maxResults=100&fields=customfield_10020`,s=await x(`/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 Zo(r,{sprintId:t,sprintName:e,target:n}={}){let i=Array.isArray(r)?r:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(t!=null&&String(t).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(t))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).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:bt(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 Vo(r,t){let e=r?.fields?.customfield_10020;return Array.isArray(e)?e.some(n=>String(n?.id)===String(t)):!1}async function Xo({issueKey:r,projectKey:t,sprintId:e,attempts:n=3,delayMs:i=450}){let s=[];for(let o=0;o<n;o++){try{let a=`project = ${t} AND key = ${r} AND sprint = ${e}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,d=await x(`/rest/api/3/search/jql?${c}`);if(Number(d?.total||0)>0)return s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let p=await x(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),u=Vo(p,e);if(s.push({attempt:o+1,jql:!1,issueField:u}),u)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<n-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:s}}async function cr({issueKey:r,projectKey:t,sprintId:e,sprintName:n,target:i}){if(!r)return{ok:!1,error:"issueKey is required"};let s=t;if(!s&&(s=(await x(`/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 un(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=Zo(o,{sprintId:e,sprintName:n,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:e??null,sprintName:n??null,target:i??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await x(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await Xo({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 x(r,t={}){let e=async()=>{let{token:n,cloudId:i}=await Ko("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:t.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let a=await o.text().catch(()=>"");if(!a||!a.trim())return{};try{return JSON.parse(a)}catch{return{raw:a}}};try{return await e()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw n;return Go("jira"),e()}}var mn={id:"jira",callsBackend:!0,serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:I.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira
24
+ `)}function Be(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function br(r){return Be(r).replace(/[a-z0-9]+/g,"")}function Rt(r,t){let e=Be(r),n=Be(t);if(!e||!n)return 0;if(e===n)return 1;if(e.length===1||n.length===1)return e===n?1:0;let i=d=>{let p=new Map;for(let u=0;u<d.length-1;u++){let m=d.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=i(e),o=i(n),a=0,c=0,l=0;for(let d of s.values())c+=d;for(let d of o.values())l+=d;for(let[d,p]of s.entries()){let u=o.get(d)||0;a+=Math.min(p,u)}return 2*a/Math.max(1,c+l)}function be(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ia(r,t=[]){let e=Array.isArray(t)?t:[];if(e.length===0)return{requested:r||null,resolved:null,strategy:"none"};let n=e.filter(a=>!a.subtask),i=n.length>0?n:e,s=be(r);if(s){let a=i.find(d=>be(d.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 d of Object.values(c)){if(!d.some(u=>be(u)===s))continue;let p=i.find(u=>d.some(m=>be(m)===be(u.name)));if(p)return{requested:r,resolved:p,strategy:"alias"}}let l=i.map(d=>({t:d,score:Rt(r,d.name)})).sort((d,p)=>p.score-d.score);if(l[0]&&l[0].score>=.5)return{requested:r,resolved:l[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(l=>be(l.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 Nn(r){let t=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,e=await j(`/rest/api/3/issue/createmeta?${t}`),n=Array.isArray(e?.projects)?e.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 On(r,t){if(!r)throw new Error("projectKey is required");let e="sprint is not EMPTY";t==="active"?e="sprint in openSprints()":t==="closed"?e="sprint in closedSprints()":t==="future"&&(e="sprint in futureSprints()");let n=`project = ${r} AND ${e} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(n)}&maxResults=100&fields=customfield_10020`,s=await j(`/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 l={active:0,future:1,closed:2},d=(l[a.state]??3)-(l[c.state]??3);return d!==0?d:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function Na(r,{sprintId:t,sprintName:e,target:n}={}){let i=Array.isArray(r)?r:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(t!=null&&String(t).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(t))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),a=i.find(l=>String(l.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(l=>({s:l,score:Rt(o,l.name||"")})).sort((l,d)=>d.score-l.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 Oa(r,t){let e=r?.fields?.customfield_10020;return Array.isArray(e)?e.some(n=>String(n?.id)===String(t)):!1}async function Ta({issueKey:r,projectKey:t,sprintId:e,attempts:n=3,delayMs:i=450}){let s=[];for(let o=0;o<n;o++){try{let a=`project = ${t} AND key = ${r} AND sprint = ${e}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,l=await j(`/rest/api/3/search/jql?${c}`);if(Number(l?.total||0)>0)return s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let p=await j(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),u=Oa(p,e);if(s.push({attempt:o+1,jql:!1,issueField:u}),u)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<n-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:s}}async function _r({issueKey:r,projectKey:t,sprintId:e,sprintName:n,target:i}){if(!r)return{ok:!1,error:"issueKey is required"};let s=t;if(!s&&(s=(await j(`/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 On(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=Na(o,{sprintId:e,sprintName:n,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:e??null,sprintName:n??null,target:i??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await j(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let l=await Ta({issueKey:r,projectKey:s,sprintId:a.id}),d=l.ok;return{ok:d,issueKey:r,projectKey:s,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:l.method,verified:d,verificationTrace:l.traces,warning:d?null:`Sprint assignment attempted but verification did not find ${r} in sprint ${a.id}`}}async function j(r,t={}){let e=async()=>{let{token:n,cloudId:i}=await ba("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:t.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let a=await o.text().catch(()=>"");if(!a||!a.trim())return{};try{return JSON.parse(a)}catch{return{raw:a}}};try{return await e()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw n;return _a("jira"),e()}}var Tn={id:"jira",callsBackend:!0,serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:I.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira
25
25
  You have direct access to the user's Jira. Use these tools proactively:
26
26
 
27
27
  ### Issue tools
@@ -71,7 +71,7 @@ When user asks to move/transition ticket status:
71
71
  3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
72
72
  4. Call jira_get_issue(issueKey) to verify final status before claiming success.
73
73
  5. If target wording differs (e.g. \u5DF2\u7ECF\u9A8C\u6536 vs \u5DF2\u9A8C\u6536), try toStatus first; only ask user to confirm when no reasonable match exists.
74
- 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=Ho();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);process.env.ATLASSIAN_INSTANCE_URL&&(t.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let e of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[e]&&(t[e]=process.env[e]);return{command:"node",args:[r],env:t,description:this.description}},async handleToolCall(r,t){try{switch(r){case"jira_list_projects":{let e=await x("/rest/api/3/project"),n=(Array.isArray(e)?e:[]).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:e}=t||{};if(e){let s=await x(`/rest/api/3/project/${encodeURIComponent(e)}/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:e,count:c.length,statuses:c})}let n=await x("/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:e}=t||{};if(!e)return JSON.stringify({error:"projectKey is required"});let n=await pn(e);return JSON.stringify({projectKey:e,count:n.length,issueTypes:n})}case"jira_search":{let e=t.jql||"",n=t.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let s=`jql=${encodeURIComponent(e)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await x(`/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 e=t.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let n=await x(`/rest/api/3/issue/${e}`);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:e,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=t;if(!e||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await pn(e),f=Wo(i,h)}catch{}let b={project:{key:e},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(b.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(b.priority={name:o}),a?.length&&(b.labels=a),c&&(b.assignee={id:c});let g=await x("/rest/api/3/issue",{method:"POST",body:{fields:b}}),_={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(_.issueType=f.resolved.name,_.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&me(f.requested)!==me(f.resolved.name)&&(_.issueTypeWarning=`Requested "${f.requested}" is not available in ${e}; used "${f.resolved.name}" instead.`)),h.length>0&&(_.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(_.sprintMove=await cr({issueKey:g.key,projectKey:e,sprintId:p,sprintName:u,target:m})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:e,state:n}=t,i=await un(e,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:n,sprintId:i,sprintName:s,target:o}=t||{},a=await cr({issueKey:e,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:n,sprintId:i,sprintName:s,target:o}=t||{},a=await cr({issueKey:e,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:n,projectKey:i,status:s,maxResults:o}=t;if(!e&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${e}"`,d=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",p=`${d}${c}${l} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await x(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(b=>({key:b.key,project:b.fields?.project?.key,summary:b.fields?.summary,status:b.fields?.status?.name,assignee:b.fields?.assignee?.displayName||"Unassigned",priority:b.fields?.priority?.name,type:b.fields?.issuetype?.name})),h={};for(let b of f)h[b.status]=(h[b.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:e,maxResults:n}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let s=await x(`/rest/api/3/issue/${e}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=_t(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:e,body:n}=t;return!e||!n?JSON.stringify({error:"issueKey and body are required"}):(await x(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:n}=t;return!e||!n?JSON.stringify({error:"issueKey and fields are required"}):(await x(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:n,toStatus:i,statusName:s,status:o}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let p=((await x(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:p})}let c=n;if(!c){let p=(await x(`/rest/api/3/issue/${e}/transitions`)).transitions||[],u=Le(a),m=p.find(f=>Le(f?.name||"")===u||Le(f?.to?.name||"")===u);if(!m){let f=ar(a);f.length>=2&&(m=p.find(h=>{let b=ar(h?.name||""),g=ar(h?.to?.name||""),_=b.length>=2&&(b.includes(f)||f.includes(b)),y=g.length>=2&&(g.includes(f)||f.includes(g));return _||y}))}if(!m){let f=p.map(_=>{let y=bt(a,_?.name||""),k=bt(a,_?.to?.name||"");return{t:_,score:Math.max(y,k)}}).sort((_,y)=>y.score-_.score),h=f[0],b=f[1];h&&h.score>=.45&&(!b||h.score-b.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:e,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await x(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await x(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as ma}from"fs";import{fileURLToPath as fa}from"url";import{dirname as ha,resolve as ya}from"path";import{resolveIntegrationToken as bn}from"@zibby/core/backend-client.js";import{spawn as Qo,execSync as ea}from"child_process";import{existsSync as Q,mkdirSync as ta,readdirSync as yn,statSync as ra,readFileSync as na}from"fs";import{resolve as lr,join as ee,basename as ia}from"path";var dr=".zibby/repos";function fn(r,t){try{let e=new URL(r);return e.protocol==="https:"&&e.host.toLowerCase()===t.toLowerCase()}catch{return!1}}function hn(r,t,e){let n=new URL(r);return n.username=encodeURIComponent(t),n.password=encodeURIComponent(e),n.toString()}function sa(r){let t=String(r??"");for(let e of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])e&&(t=t.split(e).join("***"));return t.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,e=>e.replace(/:[^@\s]+@/,":***@"))}function We(r,t,e,n,i="clone"){try{r(`git -C "${t}" remote set-url origin "${e}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);n&&(o=o.split(n).join("***")),console.error(`[${i}] WARNING: failed to strip token from .git/config: ${o}`)}}function kt(r,t,e={}){return new Promise((n,i)=>{let s=Qo(r,{cwd:t,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),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 fe={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],inProcessOnly:!0,promptFragment:`## Git Repositories
74
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=wa();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);process.env.ATLASSIAN_INSTANCE_URL&&(t.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let e of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[e]&&(t[e]=process.env[e]);return{command:"node",args:[r],env:t,description:this.description}},async handleToolCall(r,t){try{switch(r){case"jira_list_projects":{let e=await j("/rest/api/3/project"),n=(Array.isArray(e)?e:[]).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:e}=t||{};if(e){let s=await j(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let l of o)for(let d of l.statuses||[])d?.id&&(a.has(d.id)||a.set(d.id,{id:d.id,name:d.name,category:d.statusCategory?.name||null}));let c=[...a.values()].sort((l,d)=>String(l.name).localeCompare(String(d.name)));return JSON.stringify({scope:"project",projectKey:e,count:c.length,statuses:c})}let n=await j("/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:e}=t||{};if(!e)return JSON.stringify({error:"projectKey is required"});let n=await Nn(e);return JSON.stringify({projectKey:e,count:n.length,issueTypes:n})}case"jira_search":{let e=t.jql||"",n=t.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let s=`jql=${encodeURIComponent(e)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await j(`/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 e=t.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let n=await j(`/rest/api/3/issue/${e}`);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:e,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:l,moveToActiveSprint:d,sprintId:p,sprintName:u,target:m}=t;if(!e||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await Nn(e),f=Ia(i,h)}catch{}let _={project:{key:e},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(_.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(_.priority={name:o}),a?.length&&(_.labels=a),c&&(_.assignee={id:c});let y=await j("/rest/api/3/issue",{method:"POST",body:{fields:_}}),b={ok:!0,key:y.key,id:y.id,self:y.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&be(f.requested)!==be(f.resolved.name)&&(b.issueTypeWarning=`Requested "${f.requested}" is not available in ${e}; used "${f.resolved.name}" instead.`)),h.length>0&&(b.availableIssueTypes=h.map(g=>g.name)),(l||d)&&(b.sprintMove=await _r({issueKey:y.key,projectKey:e,sprintId:p,sprintName:u,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:e,state:n}=t,i=await On(e,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:n,sprintId:i,sprintName:s,target:o}=t||{},a=await _r({issueKey:e,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:n,sprintId:i,sprintName:s,target:o}=t||{},a=await _r({issueKey:e,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:n,projectKey:i,status:s,maxResults:o}=t;if(!e&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${e}"`,l=i?`project = ${i} AND `:"",d=s?` AND status = "${s}"`:"",p=`${l}${c}${d} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await j(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(_=>({key:_.key,project:_.fields?.project?.key,summary:_.fields?.summary,status:_.fields?.status?.name,assignee:_.fields?.assignee?.displayName||"Unassigned",priority:_.fields?.priority?.name,type:_.fields?.issuetype?.name})),h={};for(let _ of f)h[_.status]=(h[_.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:e,maxResults:n}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let s=await j(`/rest/api/3/issue/${e}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=Tt(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:e,body:n}=t;return!e||!n?JSON.stringify({error:"issueKey and body are required"}):(await j(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:n}=t;return!e||!n?JSON.stringify({error:"issueKey and fields are required"}):(await j(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:n,toStatus:i,statusName:s,status:o}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let p=((await j(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:p})}let c=n;if(!c){let p=(await j(`/rest/api/3/issue/${e}/transitions`)).transitions||[],u=Be(a),m=p.find(f=>Be(f?.name||"")===u||Be(f?.to?.name||"")===u);if(!m){let f=br(a);f.length>=2&&(m=p.find(h=>{let _=br(h?.name||""),y=br(h?.to?.name||""),b=_.length>=2&&(_.includes(f)||f.includes(_)),g=y.length>=2&&(y.includes(f)||f.includes(y));return b||g}))}if(!m){let f=p.map(b=>{let g=Rt(a,b?.name||""),k=Rt(a,b?.to?.name||"");return{t:b,score:Math.max(g,k)}}).sort((b,g)=>g.score-b.score),h=f[0],_=f[1];h&&h.score>=.45&&(!_||h.score-_.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:e,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await j(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let l=await j(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:l?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as Ma}from"fs";import{fileURLToPath as Fa}from"url";import{dirname as Ka,resolve as Ga}from"path";import{resolveIntegrationToken as Ln}from"@zibby/core/backend-client.js";import{spawn as Ra,execSync as Aa}from"child_process";import{existsSync as ee,mkdirSync as Ea,readdirSync as En,statSync as xa,readFileSync as ja}from"fs";import{resolve as kr,join as te,basename as La}from"path";var wr=".zibby/repos";function Rn(r,t){try{let e=new URL(r);return e.protocol==="https:"&&e.host.toLowerCase()===t.toLowerCase()}catch{return!1}}function An(r,t,e){let n=new URL(r);return n.username=encodeURIComponent(t),n.password=encodeURIComponent(e),n.toString()}function $a(r){let t=String(r??"");for(let e of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])e&&(t=t.split(e).join("***"));return t.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,e=>e.replace(/:[^@\s]+@/,":***@"))}function tt(r,t,e,n,i="clone"){try{r(`git -C "${t}" remote set-url origin "${e}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);n&&(o=o.split(n).join("***")),console.error(`[${i}] WARNING: failed to strip token from .git/config: ${o}`)}}function At(r,t,e={}){return new Promise((n,i)=>{let s=Ra(r,{cwd:t,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),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 _e={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],inProcessOnly:!0,promptFragment:`## Git Repositories
75
75
  You can clone and explore git repositories locally for codebase analysis:
76
76
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
77
77
  - git_list_repos: List locally cloned repos
@@ -81,11 +81,11 @@ When your task needs repository context you don't have yet:
81
81
  1. Clone the relevant repo with git_checkout
82
82
  2. Use git_explore to understand the project structure
83
83
  3. Use shell commands (grep, cat) to read specific files for deeper understanding
84
- 4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(r,t,e){let n=e?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await oa(t,n);case"git_list_repos":return aa(t,n);case"git_explore":return ca(t,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:sa(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 oa(r,t){let{url:e,branch:n,shallow:i=!0,name:s}=r;!e.includes("://")&&!e.startsWith("git@")&&(e=`https://github.com/${e}`);let o=s||ia(e.replace(/\.git$/,"")),a=lr(t,dr);ta(a,{recursive:!0});let c=ee(a,o),d=e,l=process.env.GITHUB_TOKEN,p=process.env.GITLAB_TOKEN,u=process.env.GITLAB_URL;if(fn(e,"github.com")&&l)d=hn(e,"x-access-token",l);else if(p&&u)try{let h=new URL(u).host;fn(e,h)&&(d=hn(e,"oauth2",p))}catch{}if(Q(ee(c,".git"))){let h=n?`git -C "${c}" fetch "${d}" ${n} && git -C "${c}" checkout ${n} && git -C "${c}" merge --ff-only FETCH_HEAD`:`git -C "${c}" pull "${d}"`;await kt(h,t);let b=await kt(`git -C "${c}" log -1 --format="%h %s"`,t);return JSON.stringify({action:"updated",repo:o,path:c,branch:n||"default",head:b})}let m=["git","clone"];i&&m.push("--depth","1"),n&&m.push("--branch",n),m.push(`"${d}"`,`"${c}"`),await kt(m.join(" "),t),We(ea,c,e,l||p,"git_checkout");let f=await kt(`git -C "${c}" log -1 --format="%h %s"`,t);return JSON.stringify({action:"cloned",repo:o,path:c,branch:n||"default",shallow:i,head:f})}function aa(r,t){let e=lr(t,dr);if(!Q(e))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let i of yn(e,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=ee(e,i.name);if(!Q(ee(s,".git")))continue;let o=ra(s);n.push({name:i.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:e})}function ca(r,t){let{repo:e,depth:n=2}=r,i=lr(t,dr,e);if(!Q(i))return JSON.stringify({error:`Repo not found: ${e}. Run git_checkout first.`});let s={repo:e,path:i},o=ee(i,"package.json");if(Q(o))try{let m=JSON.parse(na(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=ee(i,"pyproject.toml");Q(a)&&(s.language="Python");let c=ee(i,"go.mod");Q(c)&&(s.language="Go");let d=ee(i,"Cargo.toml");Q(d)&&(s.language="Rust"),Q(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function p(m,f,h){if(h>n)return;let b;try{b=yn(m,{withFileTypes:!0})}catch{return}let g=b.filter(_=>!_.name.startsWith(".")&&_.name!=="node_modules"&&_.name!=="__pycache__"&&_.name!=="dist"&&_.name!=="build"&&_.name!==".git").sort((_,y)=>_.isDirectory()!==y.isDirectory()?_.isDirectory()?-1:1:_.name.localeCompare(y.name));for(let _ of g){let y=_.isDirectory();l.push(`${f}${y?"\u{1F4C1}":"\u{1F4C4}"} ${_.name}`),y&&h<n&&p(ee(m,_.name),`${f} `,h+1)}}p(i,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let u=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return s.keyFilesFound=u.filter(m=>Q(ee(i,m))),JSON.stringify(s)}import la from"crypto";var gn=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,_n=/<!--\s*zbreview-summary\s*-->/i;function da(r){return String(r||"").replace(gn,"").replace(_n,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function pa(r,t){return la.createHash("sha256").update(`${String(r||"")}\0${da(t)}`).digest("hex").slice(0,12)}function ua(r){return`
84
+ 4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(r,t,e){let n=e?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await Pa(t,n);case"git_list_repos":return Ca(t,n);case"git_explore":return Ua(t,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:$a(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 Pa(r,t){let{url:e,branch:n,shallow:i=!0,name:s}=r;!e.includes("://")&&!e.startsWith("git@")&&(e=`https://github.com/${e}`);let o=s||La(e.replace(/\.git$/,"")),a=kr(t,wr);Ea(a,{recursive:!0});let c=te(a,o),l=e,d=process.env.GITHUB_TOKEN,p=process.env.GITLAB_TOKEN,u=process.env.GITLAB_URL;if(Rn(e,"github.com")&&d)l=An(e,"x-access-token",d);else if(p&&u)try{let h=new URL(u).host;Rn(e,h)&&(l=An(e,"oauth2",p))}catch{}if(ee(te(c,".git"))){let h=n?`git -C "${c}" fetch "${l}" ${n} && git -C "${c}" checkout ${n} && git -C "${c}" merge --ff-only FETCH_HEAD`:`git -C "${c}" pull "${l}"`;await At(h,t);let _=await At(`git -C "${c}" log -1 --format="%h %s"`,t);return JSON.stringify({action:"updated",repo:o,path:c,branch:n||"default",head:_})}let m=["git","clone"];i&&m.push("--depth","1"),n&&m.push("--branch",n),m.push(`"${l}"`,`"${c}"`),await At(m.join(" "),t),tt(Aa,c,e,d||p,"git_checkout");let f=await At(`git -C "${c}" log -1 --format="%h %s"`,t);return JSON.stringify({action:"cloned",repo:o,path:c,branch:n||"default",shallow:i,head:f})}function Ca(r,t){let e=kr(t,wr);if(!ee(e))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let i of En(e,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=te(e,i.name);if(!ee(te(s,".git")))continue;let o=xa(s);n.push({name:i.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:e})}function Ua(r,t){let{repo:e,depth:n=2}=r,i=kr(t,wr,e);if(!ee(i))return JSON.stringify({error:`Repo not found: ${e}. Run git_checkout first.`});let s={repo:e,path:i},o=te(i,"package.json");if(ee(o))try{let m=JSON.parse(ja(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=te(i,"pyproject.toml");ee(a)&&(s.language="Python");let c=te(i,"go.mod");ee(c)&&(s.language="Go");let l=te(i,"Cargo.toml");ee(l)&&(s.language="Rust"),ee(o)&&(s.language=s.language||"JavaScript/TypeScript");let d=[];function p(m,f,h){if(h>n)return;let _;try{_=En(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 y){let g=b.isDirectory();d.push(`${f}${g?"\u{1F4C1}":"\u{1F4C4}"} ${b.name}`),g&&h<n&&p(te(m,b.name),`${f} `,h+1)}}p(i,"",1),s.tree=d.slice(0,80),d.length>80&&(s.treeTruncated=!0);let u=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return s.keyFilesFound=u.filter(m=>ee(te(i,m))),JSON.stringify(s)}import Ba from"crypto";var xn=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,jn=/<!--\s*zbreview-summary\s*-->/i;function Ja(r){return String(r||"").replace(xn,"").replace(jn,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function Da(r,t){return Ba.createHash("sha256").update(`${String(r||"")}\0${Ja(t)}`).digest("hex").slice(0,12)}function qa(r){return`
85
85
 
86
- <!-- zbfp:${r} -->`}var wt=`
86
+ <!-- zbfp:${r} -->`}var Et=`
87
87
 
88
- <!-- zbreview-summary -->`;function St(r){let t=gn.exec(String(r||""));return t?t[1].toLowerCase():null}function vt(r){return _n.test(String(r||""))}function It(r,t){let e=new Set([...t||[]].map(s=>String(s).toLowerCase())),n=[],i=0;for(let s of Array.isArray(r)?r:[]){if(!s||!s.body)continue;let o=pa(s.path,s.body);if(e.has(o)){i+=1;continue}e.add(o),n.push({...s,_fp:o,body:`${String(s.body)}${ua(o)}`})}return{toPost:n,skipped:i}}function ga(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ha(fa(import.meta.url)),t=ya(r,"..","bin","mcp-skill.mjs");return ma(t)?t:null}async function N(r,t={}){let{token:e}=await bn("github"),n=r.startsWith("https://")?r:`https://api.github.com${r}`,i={Authorization:`Bearer ${e}`,Accept:t.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...t.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`)}return t.raw?s.text():s.json()}var $e={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:I.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
88
+ <!-- zbreview-summary -->`;function xt(r){let t=xn.exec(String(r||""));return t?t[1].toLowerCase():null}function jt(r){return jn.test(String(r||""))}function Lt(r,t){let e=new Set([...t||[]].map(s=>String(s).toLowerCase())),n=[],i=0;for(let s of Array.isArray(r)?r:[]){if(!s||!s.body)continue;let o=Da(s.path,s.body);if(e.has(o)){i+=1;continue}e.add(o),n.push({...s,_fp:o,body:`${String(s.body)}${qa(o)}`})}return{toPost:n,skipped:i}}function Ha(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ka(Fa(import.meta.url)),t=Ga(r,"..","bin","mcp-skill.mjs");return Ma(t)?t:null}async function N(r,t={}){let{token:e}=await Ln("github"),n=r.startsWith("https://")?r:`https://api.github.com${r}`,i={Authorization:`Bearer ${e}`,Accept:t.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...t.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`)}return t.raw?s.text():s.json()}var Je={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:I.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
89
89
  You have access to the user's GitHub repositories. Available tools:
90
90
 
91
91
  ### Discovery
@@ -128,11 +128,11 @@ When user says "check out repo-name" or "clone repo-name":
128
128
  3. STOP. Do not offer to inspect files or ask what to do next.
129
129
 
130
130
  When user just wants to "look at" or "read" files (not clone):
131
- - Use github_get_file to read individual files via API`,resolve(){let r=ga();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/github.js","githubSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"github_search_issues":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let n=await N(`/search/issues?q=${encodeURIComponent(e)}&per_page=${t.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 e=t.query;if(!e)return JSON.stringify({error:"query is required"});let n=t.repo?`+repo:${t.repo}`:"",i=t.language?`+language:${t.language}`:"",s=await N(`/search/code?q=${encodeURIComponent(e)}${n}${i}&per_page=${t.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:e,repo:n,number:i}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${n}/pulls/${i}/comments?per_page=50`),o=await N(`/repos/${e}/${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:e,repo:n,number:i,commentId:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await N(`/repos/${e}/${n}/pulls/comments/${s}`),a=o.in_reply_to_id||o.id,c=[];try{c=await N(`/repos/${e}/${n}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let d=c.filter(u=>u.id===a||u.in_reply_to_id===a).sort((u,m)=>new Date(u.created_at)-new Date(m.created_at)),l=d.length?d:[o],p=l.find(u=>u.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:l.map(u=>({id:u.id,user:u.user?.login,body:(u.body||"").slice(0,4e3),createdAt:u.created_at,isRoot:u.id===a,url:u.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:n,number:i,commentId:s,body:o}=t||{};if(!e||!n||!i||!s||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await N(`/repos/${e}/${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:e,repo:n,number:i,body:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${e}/${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:e,repo:n,number:i,body:s,event:o,comments:a}=t||{};if(!e||!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(_=>_&&_.path&&_.body&&(_.line!=null||_.position!=null)).map(_=>{let y={path:_.path,body:String(_.body)};return _.line!=null?(y.line=Number(_.line),y.side=_.side==="LEFT"?"LEFT":"RIGHT"):y.position=Number(_.position),y}):[];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=new Set,p=null;try{for(let _=1;_<=20;_+=1){let y=await N(`/repos/${e}/${n}/pulls/${i}/comments?per_page=100&page=${_}`);if(!Array.isArray(y)||y.length===0)break;for(let k of y){let O=St(k.body);O&&l.add(O)}if(y.length<100)break}for(let _=1;_<=20&&p==null;_+=1){let y=await N(`/repos/${e}/${n}/issues/${i}/comments?per_page=100&page=${_}`);if(!Array.isArray(y)||y.length===0)break;for(let k of y)if(vt(k.body)){p=k.id;break}if(y.length<100)break}}catch{}let u=!1,m=!1;if(s){let _=`${String(s)}${wt}`;try{p!=null?(await N(`/repos/${e}/${n}/issues/comments/${p}`,{method:"PATCH",body:{body:_}}),u=!0):await N(`/repos/${e}/${n}/issues/${i}/comments`,{method:"POST",body:{body:_}}),m=!0}catch{}}let{toPost:f,skipped:h}=It(d,l),b=f.map(({_fp:_,...y})=>y),g=null;if(b.length>0||c==="APPROVE"||c==="REQUEST_CHANGES"){let _={event:c};b.length>0&&(_.comments=b),b.length===0&&c==="REQUEST_CHANGES"&&(_.body="Changes requested \u2014 see the review summary comment."),g=await N(`/repos/${e}/${n}/pulls/${i}/reviews`,{method:"POST",body:_})}return JSON.stringify({ok:!0,id:g?g.id:void 0,state:g?g.state:void 0,event:c,notePosted:m,summaryUpdated:u,commentsPosted:b.length,inlineSkipped:h||void 0,url:g?g.html_url:void 0})}case"github_list_commits":{let{owner:e,repo:n,branch:i,path:s,limit:o,since:a,until:c,page:d}=t;if(!e||!n)return JSON.stringify({error:"owner and repo are required"});let l=Math.min(Number(o)||20,100),p=`/repos/${e}/${n}/commits?per_page=${l}&page=${Number(d)||1}`;i&&(p+=`&sha=${encodeURIComponent(i)}`),s&&(p+=`&path=${encodeURIComponent(s)}`),a&&(p+=`&since=${encodeURIComponent(a)}`),c&&(p+=`&until=${encodeURIComponent(c)}`);let u=await N(p);return JSON.stringify({total:u.length,page:Number(d)||1,hasMore:u.length>=l,commits:u.map(m=>({sha:m.sha?.slice(0,8),fullSha:m.sha,message:m.commit?.message?.slice(0,300),author:m.commit?.author?.name,authorEmail:m.commit?.author?.email,date:m.commit?.author?.date,url:m.html_url}))})}case"github_get_commit":{let{owner:e,repo:n,sha:i,includePrs:s}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let o=await N(`/repos/${e}/${n}/commits/${i}`),a;if(s)try{let c=await N(`/repos/${e}/${n}/commits/${i}/pulls`);a=(Array.isArray(c)?c:[]).map(d=>({number:d.number,title:d.title,state:d.state,merged:!!d.merged_at,webUrl:d.html_url}))}catch{a=[]}return JSON.stringify({sha:o.sha?.slice(0,8),message:o.commit?.message,author:o.commit?.author?.name,date:o.commit?.author?.date,stats:o.stats,files:(o.files||[]).map(c=>({filename:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:e,repo:n,path:i,ref:s}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${n}/contents/${encodeURIComponent(i)}`;s&&(o+=`?ref=${encodeURIComponent(s)}`);let a=await N(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:i,entries:a.map(l=>({name:l.name,type:l.type,size:l.size,path:l.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),d=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:d?c.slice(0,2e4):c,truncated:d})}case"github_get_user":try{let e=await N("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let n=e.repositories[0],i=n.owner.login,s=n.owner.type,o=s==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await N(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:s,isOrg:s==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(e){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${e.message})`})}case"github_list_orgs":try{let n=(await N("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of n)o.owner.type==="Organization"&&(i.has(o.owner.login)||i.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let s=Array.from(i.values());return JSON.stringify({count:s.length,orgs:s,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(e){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${e.message}`})}case"github_clone":{let f=function(_){let y=_.replace(/^~(?=$|\/|\\)/,m);return a(y)},{owner:e,repo:n,destination:i}=t;if(!e||!n)return JSON.stringify({error:"owner and repo are required"});let{execSync:s}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:d}=await import("fs"),{homedir:l,platform:p}=await import("os"),{token:u}=await bn("github"),m=l(),h=i?f(i):o(m,"zibby-repos"),b=o(h,n);if(d(h,{recursive:!0}),c(b))return JSON.stringify({error:`Directory ${b} already exists. Remove it first or use a different destination.`,existingPath:b});let g=`https://x-access-token:${u}@github.com/${e}/${n}.git`;try{s(`git clone ${g} "${b}"`,{stdio:"pipe"});let _=`https://github.com/${e}/${n}.git`;We(s,b,_,u,"github_clone");let y=p()==="win32",k;return y?k=s(`dir "${b}"`,{encoding:"utf-8",shell:"cmd.exe"}):k=s(`ls -la "${b}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:b,message:`Cloned ${e}/${n} to ${b}`,contents:k.split(`
131
+ - Use github_get_file to read individual files via API`,resolve(){let r=Ha();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/github.js","githubSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"github_search_issues":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let n=await N(`/search/issues?q=${encodeURIComponent(e)}&per_page=${t.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 e=t.query;if(!e)return JSON.stringify({error:"query is required"});let n=t.repo?`+repo:${t.repo}`:"",i=t.language?`+language:${t.language}`:"",s=await N(`/search/code?q=${encodeURIComponent(e)}${n}${i}&per_page=${t.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:e,repo:n,number:i}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${n}/pulls/${i}/comments?per_page=50`),o=await N(`/repos/${e}/${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,l)=>new Date(c.createdAt)-new Date(l.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:n,number:i,commentId:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await N(`/repos/${e}/${n}/pulls/comments/${s}`),a=o.in_reply_to_id||o.id,c=[];try{c=await N(`/repos/${e}/${n}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let l=c.filter(u=>u.id===a||u.in_reply_to_id===a).sort((u,m)=>new Date(u.created_at)-new Date(m.created_at)),d=l.length?l:[o],p=d.find(u=>u.id===a)||d[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:d.map(u=>({id:u.id,user:u.user?.login,body:(u.body||"").slice(0,4e3),createdAt:u.created_at,isRoot:u.id===a,url:u.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:n,number:i,commentId:s,body:o}=t||{};if(!e||!n||!i||!s||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await N(`/repos/${e}/${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:e,repo:n,number:i,body:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${e}/${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:e,repo:n,number:i,body:s,event:o,comments:a}=t||{};if(!e||!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 l=Array.isArray(a)?a.filter(b=>b&&b.path&&b.body&&(b.line!=null||b.position!=null)).map(b=>{let g={path:b.path,body:String(b.body)};return b.line!=null?(g.line=Number(b.line),g.side=b.side==="LEFT"?"LEFT":"RIGHT"):g.position=Number(b.position),g}):[];if(c!=="APPROVE"&&!s&&l.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let d=new Set,p=null;try{for(let b=1;b<=20;b+=1){let g=await N(`/repos/${e}/${n}/pulls/${i}/comments?per_page=100&page=${b}`);if(!Array.isArray(g)||g.length===0)break;for(let k of g){let O=xt(k.body);O&&d.add(O)}if(g.length<100)break}for(let b=1;b<=20&&p==null;b+=1){let g=await N(`/repos/${e}/${n}/issues/${i}/comments?per_page=100&page=${b}`);if(!Array.isArray(g)||g.length===0)break;for(let k of g)if(jt(k.body)){p=k.id;break}if(g.length<100)break}}catch{}let u=!1,m=!1;if(s){let b=`${String(s)}${Et}`;try{p!=null?(await N(`/repos/${e}/${n}/issues/comments/${p}`,{method:"PATCH",body:{body:b}}),u=!0):await N(`/repos/${e}/${n}/issues/${i}/comments`,{method:"POST",body:{body:b}}),m=!0}catch{}}let{toPost:f,skipped:h}=Lt(l,d),_=f.map(({_fp:b,...g})=>g),y=null;if(_.length>0||c==="APPROVE"||c==="REQUEST_CHANGES"){let b={event:c};_.length>0&&(b.comments=_),_.length===0&&c==="REQUEST_CHANGES"&&(b.body="Changes requested \u2014 see the review summary comment."),y=await N(`/repos/${e}/${n}/pulls/${i}/reviews`,{method:"POST",body:b})}return JSON.stringify({ok:!0,id:y?y.id:void 0,state:y?y.state:void 0,event:c,notePosted:m,summaryUpdated:u,commentsPosted:_.length,inlineSkipped:h||void 0,url:y?y.html_url:void 0})}case"github_list_commits":{let{owner:e,repo:n,branch:i,path:s,limit:o,since:a,until:c,page:l}=t;if(!e||!n)return JSON.stringify({error:"owner and repo are required"});let d=Math.min(Number(o)||20,100),p=`/repos/${e}/${n}/commits?per_page=${d}&page=${Number(l)||1}`;i&&(p+=`&sha=${encodeURIComponent(i)}`),s&&(p+=`&path=${encodeURIComponent(s)}`),a&&(p+=`&since=${encodeURIComponent(a)}`),c&&(p+=`&until=${encodeURIComponent(c)}`);let u=await N(p);return JSON.stringify({total:u.length,page:Number(l)||1,hasMore:u.length>=d,commits:u.map(m=>({sha:m.sha?.slice(0,8),fullSha:m.sha,message:m.commit?.message?.slice(0,300),author:m.commit?.author?.name,authorEmail:m.commit?.author?.email,date:m.commit?.author?.date,url:m.html_url}))})}case"github_get_commit":{let{owner:e,repo:n,sha:i,includePrs:s}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let o=await N(`/repos/${e}/${n}/commits/${i}`),a;if(s)try{let c=await N(`/repos/${e}/${n}/commits/${i}/pulls`);a=(Array.isArray(c)?c:[]).map(l=>({number:l.number,title:l.title,state:l.state,merged:!!l.merged_at,webUrl:l.html_url}))}catch{a=[]}return JSON.stringify({sha:o.sha?.slice(0,8),message:o.commit?.message,author:o.commit?.author?.name,date:o.commit?.author?.date,stats:o.stats,files:(o.files||[]).map(c=>({filename:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:e,repo:n,path:i,ref:s}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${n}/contents/${encodeURIComponent(i)}`;s&&(o+=`?ref=${encodeURIComponent(s)}`);let a=await N(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:i,entries:a.map(d=>({name:d.name,type:d.type,size:d.size,path:d.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),l=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:l?c.slice(0,2e4):c,truncated:l})}case"github_get_user":try{let e=await N("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let n=e.repositories[0],i=n.owner.login,s=n.owner.type,o=s==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await N(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:s,isOrg:s==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(e){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${e.message})`})}case"github_list_orgs":try{let n=(await N("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of n)o.owner.type==="Organization"&&(i.has(o.owner.login)||i.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let s=Array.from(i.values());return JSON.stringify({count:s.length,orgs:s,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(e){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${e.message}`})}case"github_clone":{let f=function(b){let g=b.replace(/^~(?=$|\/|\\)/,m);return a(g)},{owner:e,repo:n,destination:i}=t;if(!e||!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:l}=await import("fs"),{homedir:d,platform:p}=await import("os"),{token:u}=await Ln("github"),m=d(),h=i?f(i):o(m,"zibby-repos"),_=o(h,n);if(l(h,{recursive:!0}),c(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});let y=`https://x-access-token:${u}@github.com/${e}/${n}.git`;try{s(`git clone ${y} "${_}"`,{stdio:"pipe"});let b=`https://github.com/${e}/${n}.git`;tt(s,_,b,u,"github_clone");let g=p()==="win32",k;return g?k=s(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):k=s(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${e}/${n} to ${_}`,contents:k.split(`
132
132
  `).slice(0,30).join(`
133
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(_){let k=String(_.message||_).split(u).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${k}`})}}case"github_search_repos":{let{query:e,limit:n}=t;if(!e)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=e.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:e,count:a.length,repos:a.slice(0,n||20)})}case"github_list_repos":{let{owner:e,type:n,sort:i,direction:s,limit:o,query:a}=t,c=100,d=o||200,l=[],p=y=>({name:y.name,fullName:y.full_name,private:y.private,description:y.description,language:y.language,defaultBranch:y.default_branch,updatedAt:y.updated_at,stars:y.stargazers_count,url:y.html_url,fullPath:y.full_name,webUrl:y.html_url,visibility:y.visibility||(y.private?"private":"public")}),u=y=>{if(!a)return!0;let k=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(k)||y.fullName&&y.fullName.toLowerCase().includes(k)||y.description&&y.description.toLowerCase().includes(k)};if(!e){let y=1,k=!0;for(;k&&l.length<d;){let D=`/installation/repositories?per_page=${c}&page=${y}`,be=(await N(D)).repositories||[];if(be.length===0)break;l=l.concat(be),k=be.length===c,y++}let O=l.map(p).filter(u),Y=O.slice(0,d),je=O.length>Y.length,R=Y.filter(D=>D.private).length,A=Y.filter(D=>!D.private).length;return JSON.stringify({count:Y.length,repos:Y,truncated:je,privateCount:R,publicCount:A,message:`Found ${R} private and ${A} public repos`})}let m=await N(`/orgs/${e}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&l.length<d;){let y;m?y=`/orgs/${e}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:y=`/users/${e}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let k=await N(y),O=Array.isArray(k)?k:[];if(O.length===0)break;l=l.concat(O),h=O.length===c,f++}let b=l.map(p).filter(u),g=b.slice(0,d),_=b.length>g.length;return JSON.stringify({count:g.length,repos:g,truncated:_})}case"github_create_pr":{let{owner:e,repo:n,head:i,title:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=t.base;if(!o)try{o=(await N(`/repos/${e}/${n}`)).default_branch||"main"}catch{o="main"}let a={title:String(s),head:String(i),base:String(o),body:t.body?String(t.body):"",draft:!!t.draft};try{let c=await N(`/repos/${e}/${n}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${e}/${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:`${e}/${n}`,provider:"github",skippedReason:d});throw c}}case"github_merge_pr":{let{owner:e,repo:n,number:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=t.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};t.commitTitle&&(o.commit_title=String(t.commitTitle)),t.commitMessage&&(o.commit_message=String(t.commitMessage));try{let a=await N(`/repos/${e}/${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:e,repo:n,title:i,body:s}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await N(`/repos/${e}/${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:e,repo:n,state:i,labels:s,since:o,assignee:a,sort:c,direction:d,limit:l}=t||{};if(!e||!n)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",i||"open"),p.set("per_page",String(l||30)),p.set("sort",c||"updated"),p.set("direction",d||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),o&&p.set("since",o),a&&p.set("assignee",a);let u=await N(`/repos/${e}/${n}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:e,repo:n,number:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i,limit:s}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await N(`/repos/${e}/${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:e,repo:n,number:i,body:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${e}/${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:e,repo:n,number:i,stateReason:s}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};s&&(o.state_reason=s);let a=await N(`/repos/${e}/${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:e,repo:n,number:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i,labels:s,mode:o}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(s)?s:s?[s]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await N(`/repos/${e}/${n}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await N(`/repos/${e}/${n}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await N(`/repos/${e}/${n}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let d=await N(`/repos/${e}/${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(e){return JSON.stringify({error:e.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). 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:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},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)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},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 _a}from"fs";import{AsyncLocalStorage as ba}from"async_hooks";import{fileURLToPath as ka}from"url";import{dirname as wa,resolve as Sa}from"path";function va(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=wa(ka(import.meta.url)),t=Sa(r,"..","bin","mcp-skill.mjs");return _a(t)?t:null}function Ze(r){return String(r??"").trim().replace(/^\/+|\/+$/g,"").toLowerCase()}var Nt=null;function Ia(r){let t;try{t=JSON.parse(r)}catch{throw new Error("GITLAB_INSTANCES is set but is not valid JSON. Expected an array of { host, token, repos: [...] }.")}if(!Array.isArray(t)||t.length===0)throw new Error("GITLAB_INSTANCES must be a non-empty JSON array of { host, token, repos: [...] }.");let e=[],n=new Map;return t.forEach((i,s)=>{let o=i&&typeof i.host=="string"?i.host.trim().replace(/\/+$/,""):"",a=i&&typeof i.token=="string"?i.token.trim():"",c=i&&Array.isArray(i.repos)?i.repos:null;if(!o)throw new Error(`GITLAB_INSTANCES[${s}] is missing "host".`);if(!a)throw new Error(`GITLAB_INSTANCES[${s}] (${o}) is missing "token".`);if(!c||c.length===0)throw new Error(`GITLAB_INSTANCES[${s}] (${o}) declares no "repos" \u2014 an entry that routes nothing is a config error, not an empty selection.`);let d=o.replace(/\/api\/v\d+$/,""),l=new Set;for(let p of c){let u=Ze(p);if(!u)continue;let m=n.get(u);if(m!==void 0&&m!==s)throw new Error(`GITLAB_INSTANCES claims "${u}" on more than one server (${e[m].webHost} and ${d}). A repo path must name exactly one server.`);n.set(u,s),l.add(u)}if(l.size===0)throw new Error(`GITLAB_INSTANCES[${s}] (${o}) declares no usable "repos".`);e.push({webHost:d,apiBase:/\/api\/v\d+$/.test(o)?o:`${d}/api/v4`,token:a,repos:l})}),e}function Ot(){let r=process.env.GITLAB_INSTANCES;if(typeof r!="string"||!r.trim())return null;if(Nt&&Nt.raw===r)return Nt.value;let t=Ia(r);return Nt={raw:r,value:t},t}var Tt=new ba,Na="GitLab: this call was not routed to a connected server. With GITLAB_INSTANCES set, every call must name a project one of the declared servers owns.";function At(){let r=Tt.getStore();if(r)return r;if(Ot())throw new Error(Na);return null}function Oa(){let r=At();if(r)return r.apiBase;let t=process.env.GITLAB_API_URL;if(t)return t.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 Ta(){let r=At();if(r)return{"PRIVATE-TOKEN":r.token};if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let t=process.env.GITLAB_TOKEN;if(!t)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":t}}async function T(r,t={}){let e=/^https?:\/\//.test(r)?r:`${Oa()}${r}`,n={Accept:"application/json","User-Agent":"Zibby-App",...Ta(),...t.body?{"Content-Type":"application/json"}:{}},i=await fetch(e,{method:t.method||"GET",headers:n,body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`GitLab API ${i.status}: ${s.slice(0,300)}`)}return t.raw?i.text():i.json()}function kn(){let r=At();if(r)return r.webHost;let t=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(t?t.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Aa(){let r=At();return r?r.token:process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function L(r){let t=String(r);return/^\d+$/.test(t)?t:encodeURIComponent(t)}function vn(){let r=Ot();if(r){let n=new Set;for(let i of r)for(let s of i.repos)n.add(s);return n}let t=process.env.GITLAB_ALLOWED_REPOS;if(typeof t!="string"||!t.trim())return null;let e=new Set(t.split(",").map(Ze).filter(Boolean));return e.size?e:null}function In(r,t){if(!r)return!0;let e=Ze(t);return e!==""&&r.has(e)}function Ra(r){if(!r||typeof r!="object")return null;for(let t of["projectPath","projectId","project","repo","repoPath"]){let e=r[t];if(e!=null&&String(e).trim()!=="")return String(e).trim()}return null}async function wn(r){if(!/^\d+$/.test(r))return r;try{let t=await T(`/projects/${L(r)}`);return t&&t.path_with_namespace||null}catch{return null}}async function Ea(r,t){if(!t)return{path:await wn(r),instance:null};if(!/^\d+$/.test(r)){let n=Ze(r);return{path:r,instance:t.find(i=>i.repos.has(n))||null}}let e=null;for(let n of t){let i=await Tt.run(n,()=>wn(r));if(i&&(e===null&&(e=i),n.repos.has(Ze(i))))return{path:i,instance:n}}return{path:e,instance:null}}async function Sn(r,t){switch(r){case"gitlab_clone":{let{projectPath:e,projectId:n,destination:i,branch:s}=t||{},o=e&&String(e).trim();if(!o&&n!=null&&(/^\d+$/.test(String(n))?o=(await T(`/projects/${L(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=Aa();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:d,resolve:l}=await import("path"),{existsSync:p,mkdirSync:u}=await import("fs"),m=i?l(i):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(u(m,{recursive:!0}),p(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let b=kn().replace(/^https?:\/\//,""),g=kn().startsWith("http://")?"http":"https",_=`${g}://oauth2:${a}@${b}/${o}.git`,y=s?`--branch "${String(s).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${y}${_} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let k=`${g}://${b}/${o}.git`;We(c,h,k,a,"gitlab_clone");let O=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:O.split(`
133
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(b){let k=String(b.message||b).split(u).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${k}`})}}case"github_search_repos":{let{query:e,limit:n}=t;if(!e)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=e.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:e,count:a.length,repos:a.slice(0,n||20)})}case"github_list_repos":{let{owner:e,type:n,sort:i,direction:s,limit:o,query:a}=t,c=100,l=o||200,d=[],p=g=>({name:g.name,fullName:g.full_name,private:g.private,description:g.description,language:g.language,defaultBranch:g.default_branch,updatedAt:g.updated_at,stars:g.stargazers_count,url:g.html_url,fullPath:g.full_name,webUrl:g.html_url,visibility:g.visibility||(g.private?"private":"public")}),u=g=>{if(!a)return!0;let k=String(a).toLowerCase();return g.name&&g.name.toLowerCase().includes(k)||g.fullName&&g.fullName.toLowerCase().includes(k)||g.description&&g.description.toLowerCase().includes(k)};if(!e){let g=1,k=!0;for(;k&&d.length<l;){let M=`/installation/repositories?per_page=${c}&page=${g}`,Ie=(await N(M)).repositories||[];if(Ie.length===0)break;d=d.concat(Ie),k=Ie.length===c,g++}let O=d.map(p).filter(u),q=O.slice(0,l),ye=O.length>q.length,T=q.filter(M=>M.private).length,A=q.filter(M=>!M.private).length;return JSON.stringify({count:q.length,repos:q,truncated:ye,privateCount:T,publicCount:A,message:`Found ${T} private and ${A} public repos`})}let m=await N(`/orgs/${e}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&d.length<l;){let g;m?g=`/orgs/${e}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:g=`/users/${e}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let k=await N(g),O=Array.isArray(k)?k:[];if(O.length===0)break;d=d.concat(O),h=O.length===c,f++}let _=d.map(p).filter(u),y=_.slice(0,l),b=_.length>y.length;return JSON.stringify({count:y.length,repos:y,truncated:b})}case"github_create_pr":{let{owner:e,repo:n,head:i,title:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=t.base;if(!o)try{o=(await N(`/repos/${e}/${n}`)).default_branch||"main"}catch{o="main"}let a={title:String(s),head:String(i),base:String(o),body:t.body?String(t.body):"",draft:!!t.draft};try{let c=await N(`/repos/${e}/${n}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${e}/${n}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let l=String(c.message||c);if(/GitHub API 422/.test(l))return JSON.stringify({success:!1,branch:i,base:o,repo:`${e}/${n}`,provider:"github",skippedReason:l});throw c}}case"github_merge_pr":{let{owner:e,repo:n,number:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=t.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};t.commitTitle&&(o.commit_title=String(t.commitTitle)),t.commitMessage&&(o.commit_message=String(t.commitMessage));try{let a=await N(`/repos/${e}/${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:e,repo:n,title:i,body:s}=t;if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await N(`/repos/${e}/${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:e,repo:n,state:i,labels:s,since:o,assignee:a,sort:c,direction:l,limit:d}=t||{};if(!e||!n)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",i||"open"),p.set("per_page",String(d||30)),p.set("sort",c||"updated"),p.set("direction",l||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),o&&p.set("since",o),a&&p.set("assignee",a);let u=await N(`/repos/${e}/${n}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:e,repo:n,number:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i,limit:s}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await N(`/repos/${e}/${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:e,repo:n,number:i,body:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${e}/${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:e,repo:n,number:i,stateReason:s}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};s&&(o.state_reason=s);let a=await N(`/repos/${e}/${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:e,repo:n,number:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await N(`/repos/${e}/${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:e,repo:n,number:i,labels:s,mode:o}=t||{};if(!e||!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 d=await N(`/repos/${e}/${n}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await N(`/repos/${e}/${n}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let d=await N(`/repos/${e}/${n}/issues/${i}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let l=await N(`/repos/${e}/${n}/issues/${i}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(l)?l:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). 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:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},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)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},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 za}from"fs";import{AsyncLocalStorage as Ya}from"async_hooks";import{fileURLToPath as Wa}from"url";import{dirname as Za,resolve as Va}from"path";function Xa(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Za(Wa(import.meta.url)),t=Va(r,"..","bin","mcp-skill.mjs");return za(t)?t:null}function rt(r){return String(r??"").trim().replace(/^\/+|\/+$/g,"").toLowerCase()}var $t=null;function Qa(r){let t;try{t=JSON.parse(r)}catch{throw new Error("GITLAB_INSTANCES is set but is not valid JSON. Expected an array of { host, token, repos: [...] }.")}if(!Array.isArray(t)||t.length===0)throw new Error("GITLAB_INSTANCES must be a non-empty JSON array of { host, token, repos: [...] }.");let e=[],n=new Map;return t.forEach((i,s)=>{let o=i&&typeof i.host=="string"?i.host.trim().replace(/\/+$/,""):"",a=i&&typeof i.token=="string"?i.token.trim():"",c=i&&Array.isArray(i.repos)?i.repos:null;if(!o)throw new Error(`GITLAB_INSTANCES[${s}] is missing "host".`);if(!a)throw new Error(`GITLAB_INSTANCES[${s}] (${o}) is missing "token".`);if(!c||c.length===0)throw new Error(`GITLAB_INSTANCES[${s}] (${o}) declares no "repos" \u2014 an entry that routes nothing is a config error, not an empty selection.`);let l=o.replace(/\/api\/v\d+$/,""),d=new Set;for(let p of c){let u=rt(p);if(!u)continue;let m=n.get(u);if(m!==void 0&&m!==s)throw new Error(`GITLAB_INSTANCES claims "${u}" on more than one server (${e[m].webHost} and ${l}). A repo path must name exactly one server.`);n.set(u,s),d.add(u)}if(d.size===0)throw new Error(`GITLAB_INSTANCES[${s}] (${o}) declares no usable "repos".`);e.push({webHost:l,apiBase:/\/api\/v\d+$/.test(o)?o:`${l}/api/v4`,token:a,repos:d})}),e}function Pt(){let r=process.env.GITLAB_INSTANCES;if(typeof r!="string"||!r.trim())return null;if($t&&$t.raw===r)return $t.value;let t=Qa(r);return $t={raw:r,value:t},t}var Ct=new Ya,ec="GitLab: this call was not routed to a connected server. With GITLAB_INSTANCES set, every call must name a project one of the declared servers owns.";function Ut(){let r=Ct.getStore();if(r)return r;if(Pt())throw new Error(ec);return null}function tc(){let r=Ut();if(r)return r.apiBase;let t=process.env.GITLAB_API_URL;if(t)return t.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 rc(){let r=Ut();if(r)return{"PRIVATE-TOKEN":r.token};if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let t=process.env.GITLAB_TOKEN;if(!t)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":t}}async function R(r,t={}){let e=/^https?:\/\//.test(r)?r:`${tc()}${r}`,n={Accept:"application/json","User-Agent":"Zibby-App",...rc(),...t.body?{"Content-Type":"application/json"}:{}},i=await fetch(e,{method:t.method||"GET",headers:n,body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`GitLab API ${i.status}: ${s.slice(0,300)}`)}return t.raw?i.text():i.json()}function $n(){let r=Ut();if(r)return r.webHost;let t=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(t?t.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function nc(){let r=Ut();return r?r.token:process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function L(r){let t=String(r);return/^\d+$/.test(t)?t:encodeURIComponent(t)}function Un(){let r=Pt();if(r){let n=new Set;for(let i of r)for(let s of i.repos)n.add(s);return n}let t=process.env.GITLAB_ALLOWED_REPOS;if(typeof t!="string"||!t.trim())return null;let e=new Set(t.split(",").map(rt).filter(Boolean));return e.size?e:null}function Bn(r,t){if(!r)return!0;let e=rt(t);return e!==""&&r.has(e)}function ic(r){if(!r||typeof r!="object")return null;for(let t of["projectPath","projectId","project","repo","repoPath"]){let e=r[t];if(e!=null&&String(e).trim()!=="")return String(e).trim()}return null}async function Pn(r){if(!/^\d+$/.test(r))return r;try{let t=await R(`/projects/${L(r)}`);return t&&t.path_with_namespace||null}catch{return null}}async function sc(r,t){if(!t)return{path:await Pn(r),instance:null};if(!/^\d+$/.test(r)){let n=rt(r);return{path:r,instance:t.find(i=>i.repos.has(n))||null}}let e=null;for(let n of t){let i=await Ct.run(n,()=>Pn(r));if(i&&(e===null&&(e=i),n.repos.has(rt(i))))return{path:i,instance:n}}return{path:e,instance:null}}async function Cn(r,t){switch(r){case"gitlab_clone":{let{projectPath:e,projectId:n,destination:i,branch:s}=t||{},o=e&&String(e).trim();if(!o&&n!=null&&(/^\d+$/.test(String(n))?o=(await R(`/projects/${L(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=nc();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:l,resolve:d}=await import("path"),{existsSync:p,mkdirSync:u}=await import("fs"),m=i?d(i):d(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=l(m,f);if(u(m,{recursive:!0}),p(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let _=$n().replace(/^https?:\/\//,""),y=$n().startsWith("http://")?"http":"https",b=`${y}://oauth2:${a}@${_}/${o}.git`,g=s?`--branch "${String(s).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${g}${b} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let k=`${y}://${_}/${o}.git`;tt(c,h,k,a,"gitlab_clone");let O=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:O.split(`
134
134
  `).slice(0,30).join(`
135
- `)})}catch(k){let O=String(k.message||k).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${O}`})}}case"gitlab_create_mr":{let e=t?.project??t?.projectId,n=t?.source_branch??t?.sourceBranch,{title:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let s=L(e),o=t?.target_branch??t?.targetBranch;if(!o)try{o=(await T(`/projects/${s}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(n),target_branch:String(o),title:String(i),description:t?.description?String(t.description):""};try{let c=await T(`/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(e),provider:"gitlab",state:c.state})}catch(c){let d=String(c.message||c);if(/GitLab API (409|400)/.test(d))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",skippedReason:d});throw c}}case"gitlab_accept_mr":{let e=t?.project??t?.projectId,{iid:n}=t||{};if(!e||!n)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let i=L(e),s={};t.squash!=null&&(s.squash=!!t.squash),t.mergeCommitMessage&&(s.merge_commit_message=String(t.mergeCommitMessage)),t.mergeWhenPipelineSucceeds!=null&&(s.merge_when_pipeline_succeeds=!!t.mergeWhenPipelineSucceeds);try{let o=await T(`/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(e),provider:"gitlab",state:o.state})}catch(o){let a=String(o.message||o);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:n,project:String(e),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:e,iid:n}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await T(`/projects/${L(e)}/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:e,iid:n}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await T(`/projects/${L(e)}/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_commits":{let{projectId:e,since:n,until:i,refName:s,page:o,perPage:a,withStats:c}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let d=new URLSearchParams;d.set("per_page",String(Math.min(Number(a)||50,100))),d.set("page",String(Number(o)||1)),n&&d.set("since",n),i&&d.set("until",i),s&&d.set("ref_name",s),c!==!1&&d.set("with_stats","true");let l=await T(`/projects/${L(e)}/repository/commits?${d.toString()}`),p=(Array.isArray(l)?l:[]).map(u=>({id:u.id,shortId:u.short_id,title:u.title,authorName:u.author_name,authorEmail:u.author_email,authoredDate:u.authored_date,committedDate:u.committed_date,parentIds:Array.isArray(u.parent_ids)?u.parent_ids:[],stats:u.stats||null}));return JSON.stringify({page:Number(o)||1,count:p.length,hasMore:p.length>=Math.min(Number(a)||50,100),commits:p})}case"gitlab_get_commit":{let{projectId:e,sha:n,includeDiff:i,includeMrs:s}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and sha are required"});let o=await T(`/projects/${L(e)}/repository/commits/${encodeURIComponent(n)}`),a;if(s)try{let d=await T(`/projects/${L(e)}/repository/commits/${encodeURIComponent(n)}/merge_requests`);a=(Array.isArray(d)?d:[]).map(l=>({iid:l.iid,title:l.title,state:l.state,webUrl:l.web_url}))}catch{a=[]}let c;if(i!==!1){let d=await T(`/projects/${L(e)}/repository/commits/${encodeURIComponent(n)}/diff`);c=(Array.isArray(d)?d:[]).map(l=>({oldPath:l.old_path,newPath:l.new_path,newFile:!!l.new_file,deletedFile:!!l.deleted_file,renamedFile:!!l.renamed_file,diff:typeof l.diff=="string"?l.diff.slice(0,3e3):""}))}return JSON.stringify({id:o.id,shortId:o.short_id,title:o.title,message:typeof o.message=="string"?o.message.slice(0,2e3):"",authorName:o.author_name,authorEmail:o.author_email,authoredDate:o.authored_date,committedDate:o.committed_date,parentIds:Array.isArray(o.parent_ids)?o.parent_ids:[],stats:o.stats||null,webUrl:o.web_url,...c?{filesChanged:c.length,files:c}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:e,state:n,targetBranch:i,sourceBranch:s,authorUsername:o,labels:a,search:c,sort:d,orderBy:l,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||20)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("target_branch",i),s&&u.set("source_branch",s),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await T(`/projects/${L(e)}/merge_requests?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:e,iid:n,limit:i}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await T(`/projects/${L(e)}/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:e,iid:n,body:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await T(`/projects/${L(e)}/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:e,iid:n,path:i,oldPath:s,newLine:o,oldLine:a,body:c}=t||{};if(!e||!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=L(e),l=t.diffRefs||null;if(l||(l=(await T(`/projects/${d}/merge_requests/${n}`)).diff_refs||null),!l||!l.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let p={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:i,old_path:s||i};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await T(`/projects/${d}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(c),position:p}});return JSON.stringify({ok:!0,discussionId:u.id})}catch(u){return JSON.stringify({ok:!1,error:`inline anchor rejected (${u.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:e,iid:n,body:i,comments:s}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let o=L(e),a=Array.isArray(s)?s.filter(g=>g&&g.path&&g.body&&(g.newLine!=null||g.oldLine!=null)):[];if(!i&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=t.diffRefs||null;a.length>0&&!c&&(c=(await T(`/projects/${o}/merge_requests/${n}`)).diff_refs||null);let d=new Set,l=null;try{for(let g=1;g<=20;g+=1){let _=await T(`/projects/${o}/merge_requests/${n}/discussions?per_page=100&page=${g}`);if(!Array.isArray(_)||_.length===0)break;for(let y of _)for(let k of y.notes||[]){let O=St(k.body);O&&d.add(O),l==null&&vt(k.body)&&(l=k.id)}if(_.length<100)break}}catch{}let p=!1,u=!1;if(i){let g=`${String(i)}${wt}`;try{l!=null?(await T(`/projects/${o}/merge_requests/${n}/notes/${l}`,{method:"PUT",body:{body:g}}),u=!0):await T(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:g}}),p=!0}catch{await T(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:g}}),p=!0}}let{toPost:m,skipped:f}=It(a,d),h=0,b=[];if(m.length>0&&c)for(let g of m){let _={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:g.path,old_path:g.oldPath||g.path};g.newLine!=null&&(_.new_line=Number(g.newLine)),g.oldLine!=null&&(_.old_line=Number(g.oldLine));try{await T(`/projects/${o}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(g.body),position:_}}),h+=1}catch(y){b.push(`${g.path}:${g.newLine??g.oldLine} \u2014 ${y.message}`)}}else m.length>0&&!c&&b.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:p,summaryUpdated:u,inlinePosted:h,inlineSkipped:f||void 0,inlineErrors:b.length?b:void 0})}case"gitlab_get_discussion":{let{projectId:e,iid:n,discussionId:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let s=await T(`/projects/${L(e)}/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:e,iid:n,discussionId:i,body:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await T(`/projects/${L(e)}/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:e,limit:n}=t||{},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))),e&&s.set("search",String(e));let o=async()=>{let u=await T(`/projects?${s.toString()}`);return Array.isArray(u)?u:[]},a=Ot(),c=vn(),d=[];for(let u of a||[null]){let m=u?await Tt.run(u,o):await o();for(let f of m)In(u?u.repos:c,f&&f.path_with_namespace)&&d.push({p:f,host:u?u.webHost:null})}let l=d.length>i,p=d.slice(0,i).map(({p:u,host:m})=>({fullPath:u.path_with_namespace,name:u.name,webUrl:u.web_url,defaultBranch:u.default_branch||null,visibility:u.visibility||null,...m?{host:m}:{}}));return JSON.stringify({count:p.length,truncated:l,projects:p})}case"gitlab_list_issues":{let{projectId:e,state:n,labels:i,assigneeUsername:s,authorUsername:o,updatedAfter:a,search:c,sort:d,orderBy:l,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||30)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("labels",Array.isArray(i)?i.join(","):i),s&&u.set("assignee_username",s),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await T(`/projects/${L(e)}/issues?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(b=>b.username),userNotesCount:h.user_notes_count,webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,issues:f})}case"gitlab_get_issue":{let{projectId:e,iid:n}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await T(`/projects/${L(e)}/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:e,iid:n,body:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await T(`/projects/${L(e)}/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}`})}}var Pe={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:I.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_URL","GITLAB_INSTANCE_URL","GITLAB_API_URL","GITLAB_ALLOWED_REPOS","GITLAB_INSTANCES","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
135
+ `)})}catch(k){let O=String(k.message||k).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${O}`})}}case"gitlab_create_mr":{let e=t?.project??t?.projectId,n=t?.source_branch??t?.sourceBranch,{title:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let s=L(e),o=t?.target_branch??t?.targetBranch;if(!o)try{o=(await R(`/projects/${s}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(n),target_branch:String(o),title:String(i),description:t?.description?String(t.description):""};try{let c=await R(`/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(e),provider:"gitlab",state:c.state})}catch(c){let l=String(c.message||c);if(/GitLab API (409|400)/.test(l))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",skippedReason:l});throw c}}case"gitlab_accept_mr":{let e=t?.project??t?.projectId,{iid:n}=t||{};if(!e||!n)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let i=L(e),s={};t.squash!=null&&(s.squash=!!t.squash),t.mergeCommitMessage&&(s.merge_commit_message=String(t.mergeCommitMessage)),t.mergeWhenPipelineSucceeds!=null&&(s.merge_when_pipeline_succeeds=!!t.mergeWhenPipelineSucceeds);try{let o=await R(`/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(e),provider:"gitlab",state:o.state})}catch(o){let a=String(o.message||o);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:n,project:String(e),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:e,iid:n}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await R(`/projects/${L(e)}/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:e,iid:n}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await R(`/projects/${L(e)}/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_commits":{let{projectId:e,since:n,until:i,refName:s,page:o,perPage:a,withStats:c}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let l=new URLSearchParams;l.set("per_page",String(Math.min(Number(a)||50,100))),l.set("page",String(Number(o)||1)),n&&l.set("since",n),i&&l.set("until",i),s&&l.set("ref_name",s),c!==!1&&l.set("with_stats","true");let d=await R(`/projects/${L(e)}/repository/commits?${l.toString()}`),p=(Array.isArray(d)?d:[]).map(u=>({id:u.id,shortId:u.short_id,title:u.title,authorName:u.author_name,authorEmail:u.author_email,authoredDate:u.authored_date,committedDate:u.committed_date,parentIds:Array.isArray(u.parent_ids)?u.parent_ids:[],stats:u.stats||null}));return JSON.stringify({page:Number(o)||1,count:p.length,hasMore:p.length>=Math.min(Number(a)||50,100),commits:p})}case"gitlab_get_commit":{let{projectId:e,sha:n,includeDiff:i,includeMrs:s}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and sha are required"});let o=await R(`/projects/${L(e)}/repository/commits/${encodeURIComponent(n)}`),a;if(s)try{let l=await R(`/projects/${L(e)}/repository/commits/${encodeURIComponent(n)}/merge_requests`);a=(Array.isArray(l)?l:[]).map(d=>({iid:d.iid,title:d.title,state:d.state,webUrl:d.web_url}))}catch{a=[]}let c;if(i!==!1){let l=await R(`/projects/${L(e)}/repository/commits/${encodeURIComponent(n)}/diff`);c=(Array.isArray(l)?l:[]).map(d=>({oldPath:d.old_path,newPath:d.new_path,newFile:!!d.new_file,deletedFile:!!d.deleted_file,renamedFile:!!d.renamed_file,diff:typeof d.diff=="string"?d.diff.slice(0,3e3):""}))}return JSON.stringify({id:o.id,shortId:o.short_id,title:o.title,message:typeof o.message=="string"?o.message.slice(0,2e3):"",authorName:o.author_name,authorEmail:o.author_email,authoredDate:o.authored_date,committedDate:o.committed_date,parentIds:Array.isArray(o.parent_ids)?o.parent_ids:[],stats:o.stats||null,webUrl:o.web_url,...c?{filesChanged:c.length,files:c}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:e,state:n,targetBranch:i,sourceBranch:s,authorUsername:o,labels:a,search:c,sort:l,orderBy:d,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||20)),u.set("order_by",d||"updated_at"),u.set("sort",l||"desc"),i&&u.set("target_branch",i),s&&u.set("source_branch",s),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await R(`/projects/${L(e)}/merge_requests?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:e,iid:n,limit:i}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await R(`/projects/${L(e)}/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:e,iid:n,body:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await R(`/projects/${L(e)}/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:e,iid:n,path:i,oldPath:s,newLine:o,oldLine:a,body:c}=t||{};if(!e||!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 l=L(e),d=t.diffRefs||null;if(d||(d=(await R(`/projects/${l}/merge_requests/${n}`)).diff_refs||null),!d||!d.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let p={base_sha:d.base_sha,start_sha:d.start_sha,head_sha:d.head_sha,position_type:"text",new_path:i,old_path:s||i};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await R(`/projects/${l}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(c),position:p}});return JSON.stringify({ok:!0,discussionId:u.id})}catch(u){return JSON.stringify({ok:!1,error:`inline anchor rejected (${u.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:e,iid:n,body:i,comments:s}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let o=L(e),a=Array.isArray(s)?s.filter(y=>y&&y.path&&y.body&&(y.newLine!=null||y.oldLine!=null)):[];if(!i&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=t.diffRefs||null;a.length>0&&!c&&(c=(await R(`/projects/${o}/merge_requests/${n}`)).diff_refs||null);let l=new Set,d=null;try{for(let y=1;y<=20;y+=1){let b=await R(`/projects/${o}/merge_requests/${n}/discussions?per_page=100&page=${y}`);if(!Array.isArray(b)||b.length===0)break;for(let g of b)for(let k of g.notes||[]){let O=xt(k.body);O&&l.add(O),d==null&&jt(k.body)&&(d=k.id)}if(b.length<100)break}}catch{}let p=!1,u=!1;if(i){let y=`${String(i)}${Et}`;try{d!=null?(await R(`/projects/${o}/merge_requests/${n}/notes/${d}`,{method:"PUT",body:{body:y}}),u=!0):await R(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:y}}),p=!0}catch{await R(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:y}}),p=!0}}let{toPost:m,skipped:f}=Lt(a,l),h=0,_=[];if(m.length>0&&c)for(let y of m){let b={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:y.path,old_path:y.oldPath||y.path};y.newLine!=null&&(b.new_line=Number(y.newLine)),y.oldLine!=null&&(b.old_line=Number(y.oldLine));try{await R(`/projects/${o}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(y.body),position:b}}),h+=1}catch(g){_.push(`${y.path}:${y.newLine??y.oldLine} \u2014 ${g.message}`)}}else m.length>0&&!c&&_.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:p,summaryUpdated:u,inlinePosted:h,inlineSkipped:f||void 0,inlineErrors:_.length?_:void 0})}case"gitlab_get_discussion":{let{projectId:e,iid:n,discussionId:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let s=await R(`/projects/${L(e)}/merge_requests/${n}/discussions/${encodeURIComponent(i)}`),o=Array.isArray(s.notes)?s.notes:[],a=o.find(l=>l.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(l=>({id:l.id,author:l.author?.username,body:(l.body||"").slice(0,4e3),system:!!l.system,createdAt:l.created_at}))})}case"gitlab_reply_discussion":{let{projectId:e,iid:n,discussionId:i,body:s}=t||{};if(!e||!n||!i||!s)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await R(`/projects/${L(e)}/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:e,limit:n}=t||{},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))),e&&s.set("search",String(e));let o=async()=>{let u=await R(`/projects?${s.toString()}`);return Array.isArray(u)?u:[]},a=Pt(),c=Un(),l=[];for(let u of a||[null]){let m=u?await Ct.run(u,o):await o();for(let f of m)Bn(u?u.repos:c,f&&f.path_with_namespace)&&l.push({p:f,host:u?u.webHost:null})}let d=l.length>i,p=l.slice(0,i).map(({p:u,host:m})=>({fullPath:u.path_with_namespace,name:u.name,webUrl:u.web_url,defaultBranch:u.default_branch||null,visibility:u.visibility||null,...m?{host:m}:{}}));return JSON.stringify({count:p.length,truncated:d,projects:p})}case"gitlab_list_issues":{let{projectId:e,state:n,labels:i,assigneeUsername:s,authorUsername:o,updatedAfter:a,search:c,sort:l,orderBy:d,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||30)),u.set("order_by",d||"updated_at"),u.set("sort",l||"desc"),i&&u.set("labels",Array.isArray(i)?i.join(","):i),s&&u.set("assignee_username",s),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await R(`/projects/${L(e)}/issues?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(_=>_.username),userNotesCount:h.user_notes_count,webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,issues:f})}case"gitlab_get_issue":{let{projectId:e,iid:n}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await R(`/projects/${L(e)}/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:e,iid:n,body:i}=t||{};if(!e||!n||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await R(`/projects/${L(e)}/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}`})}}var De={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:I.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_URL","GITLAB_INSTANCE_URL","GITLAB_API_URL","GITLAB_ALLOWED_REPOS","GITLAB_INSTANCES","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
136
136
  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:
137
137
 
138
138
  ### Discovery
@@ -158,7 +158,7 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
158
158
 
159
159
  ### Notes
160
160
  - 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.
161
- - 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=va();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/gitlab.js","gitlabSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{let e=Ot(),n=vn(),i=null;if(n){let s=Ra(t);if(s){let{path:o,instance:a}=await Ea(s,e);if(!In(n,o)||e&&!a)return JSON.stringify({error:`Repository "${o||s}" is not available to this project. This project's agents may only use: ${[...n].join(", ")}. An owner changes this in Project Settings \u2192 Repository access.`,allowedRepos:[...n]});i=a}}return i?await Tt.run(i,()=>Sn(r,t)):await Sn(r,t)}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_commits",description:"List a project's repository commits (the commit HISTORY \u2014 not MRs), optionally bounded by since/until ISO dates and a ref/branch, with per-commit stats (additions/deletions). Paginated: keep calling with page+1 while hasMore is true. This is the ONLY correct way to enumerate commits in a date window \u2014 gitlab_clone is shallow (depth 1) and its git log shows just one commit.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},since:{type:"string",description:'Only commits after this ISO-8601 date/time (inclusive), e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:'Only commits before this ISO-8601 date/time, e.g. "2026-07-01T00:00:00Z"'},refName:{type:"string",description:"Branch/tag to list (defaults to the default branch)"},page:{type:"number",description:"Page number, 1-based (default 1)"},perPage:{type:"number",description:"Commits per page, max 100 (default 50)"},withStats:{type:"boolean",description:"Include per-commit additions/deletions stats (default true)"}},required:["projectId"]}},{name:"gitlab_get_commit",description:"Get ONE commit's full detail \u2014 message, author, timestamps, stats, and (by default) its per-file diffs (each capped at 3000 chars) \u2014 so you can judge the nature/complexity of the change. Use after gitlab_list_commits.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},sha:{type:"string",description:"The commit sha (full or short)"},includeDiff:{type:"boolean",description:"Include per-file diffs (default true; set false for metadata-only)"},includeMrs:{type:"boolean",description:"Also return the merge request(s) containing this commit ({iid,title,state,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["projectId","sha"]}},{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 ja}from"fs";import{fileURLToPath as xa}from"url";import{dirname as La,resolve as $a}from"path";import{resolveIntegrationToken as Pa}from"@zibby/core/backend-client.js";function Ca(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=La(xa(import.meta.url)),t=$a(r,"..","bin","mcp-skill.mjs");return ja(t)?t:null}async function Z(r,t={}){let{token:e}=await Pa("figma"),n=r.startsWith("https://")?r:`https://api.figma.com${r}`,i={"X-Figma-Token":e,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Figma API ${s.status}: ${o.slice(0,300)}`)}return s.json()}function ae(r){let t=String(r||"").trim(),e=t.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return e?e[1]:t}function Rt(r){return r==null?void 0:(Array.isArray(r)?r:String(r).split(",")).map(e=>String(e).trim().replace(/-/g,":")).filter(Boolean).join(",")}function Ua(r){let t=String(r||"").match(/[?&]node-id=([^&]+)/i);return t?decodeURIComponent(t[1]).replace(/-/g,":"):void 0}var te=r=>typeof r=="number"?Math.round(r*100)/100:r;function pr(r){if(!r)return null;let t=n=>Math.round((n??0)*255).toString(16).padStart(2,"0"),e={hex:`#${t(r.r)}${t(r.g)}${t(r.b)}`.toUpperCase()};return r.a!=null&&r.a<1&&(e.opacity=te(r.a)),e}function Nn(r){return!r||r.visible===!1?null:r.type==="SOLID"?{type:"SOLID",...pr(r.color),...r.opacity!=null?{opacity:r.opacity}:{}}:{type:r.type,...r.opacity!=null?{opacity:r.opacity}:{},...r.gradientStops?{stops:r.gradientStops.map(t=>({position:te(t.position),...pr(t.color)}))}:{}}}function On(r,t){let e=r.absoluteBoundingBox,n={id:r.id,name:r.name,type:r.type};e&&(n.size={w:te(e.width),h:te(e.height)},n.position={x:te(e.x),y:te(e.y)}),r.opacity!=null&&r.opacity!==1&&(n.opacity=r.opacity),r.cornerRadius!=null&&(n.cornerRadius=r.cornerRadius),Array.isArray(r.rectangleCornerRadii)&&(n.cornerRadii=r.rectangleCornerRadii);let i=(r.fills||[]).map(Nn).filter(Boolean);i.length&&(n.fills=i);let s=(r.strokes||[]).map(Nn).filter(Boolean);s.length&&(n.strokes=s,r.strokeWeight!=null&&(n.strokeWeight=r.strokeWeight));let o=(r.effects||[]).filter(a=>a.visible!==!1).map(a=>({type:a.type,...a.radius!=null?{radius:a.radius}:{},...a.offset?{offset:{x:te(a.offset.x),y:te(a.offset.y)}}:{},...a.spread?{spread:a.spread}:{},...a.color?pr(a.color):{}}));if(o.length&&(n.effects=o),r.layoutMode&&r.layoutMode!=="NONE"&&(n.autoLayout={direction:r.layoutMode,padding:{l:r.paddingLeft??0,r:r.paddingRight??0,t:r.paddingTop??0,b:r.paddingBottom??0},gap:r.itemSpacing??0,align:{primary:r.primaryAxisAlignItems,counter:r.counterAxisAlignItems}}),r.type==="TEXT"){let a=r.style||{};n.text=r.characters,n.textStyle={fontFamily:a.fontFamily,fontWeight:a.fontWeight,fontSize:a.fontSize,lineHeightPx:a.lineHeightPx!=null?te(a.lineHeightPx):void 0,letterSpacing:a.letterSpacing!=null?te(a.letterSpacing):void 0,align:a.textAlignHorizontal,case:a.textCase}}return t>0&&Array.isArray(r.children)&&r.children.length&&(n.children=r.children.map(a=>On(a,t-1))),n}var Tn={id:"figma",callsBackend:!0,serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:I.FIGMA,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma
161
+ - 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=Xa();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/gitlab.js","gitlabSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{let e=Pt(),n=Un(),i=null;if(n){let s=ic(t);if(s){let{path:o,instance:a}=await sc(s,e);if(!Bn(n,o)||e&&!a)return JSON.stringify({error:`Repository "${o||s}" is not available to this project. This project's agents may only use: ${[...n].join(", ")}. An owner changes this in Project Settings \u2192 Repository access.`,allowedRepos:[...n]});i=a}}return i?await Ct.run(i,()=>Cn(r,t)):await Cn(r,t)}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_commits",description:"List a project's repository commits (the commit HISTORY \u2014 not MRs), optionally bounded by since/until ISO dates and a ref/branch, with per-commit stats (additions/deletions). Paginated: keep calling with page+1 while hasMore is true. This is the ONLY correct way to enumerate commits in a date window \u2014 gitlab_clone is shallow (depth 1) and its git log shows just one commit.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},since:{type:"string",description:'Only commits after this ISO-8601 date/time (inclusive), e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:'Only commits before this ISO-8601 date/time, e.g. "2026-07-01T00:00:00Z"'},refName:{type:"string",description:"Branch/tag to list (defaults to the default branch)"},page:{type:"number",description:"Page number, 1-based (default 1)"},perPage:{type:"number",description:"Commits per page, max 100 (default 50)"},withStats:{type:"boolean",description:"Include per-commit additions/deletions stats (default true)"}},required:["projectId"]}},{name:"gitlab_get_commit",description:"Get ONE commit's full detail \u2014 message, author, timestamps, stats, and (by default) its per-file diffs (each capped at 3000 chars) \u2014 so you can judge the nature/complexity of the change. Use after gitlab_list_commits.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},sha:{type:"string",description:"The commit sha (full or short)"},includeDiff:{type:"boolean",description:"Include per-file diffs (default true; set false for metadata-only)"},includeMrs:{type:"boolean",description:"Also return the merge request(s) containing this commit ({iid,title,state,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["projectId","sha"]}},{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 oc}from"fs";import{fileURLToPath as ac}from"url";import{dirname as cc,resolve as lc}from"path";import{resolveIntegrationToken as dc}from"@zibby/core/backend-client.js";function pc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=cc(ac(import.meta.url)),t=lc(r,"..","bin","mcp-skill.mjs");return oc(t)?t:null}async function Z(r,t={}){let{token:e}=await dc("figma"),n=r.startsWith("https://")?r:`https://api.figma.com${r}`,i={"X-Figma-Token":e,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Figma API ${s.status}: ${o.slice(0,300)}`)}return s.json()}function de(r){let t=String(r||"").trim(),e=t.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return e?e[1]:t}function Bt(r){return r==null?void 0:(Array.isArray(r)?r:String(r).split(",")).map(e=>String(e).trim().replace(/-/g,":")).filter(Boolean).join(",")}function uc(r){let t=String(r||"").match(/[?&]node-id=([^&]+)/i);return t?decodeURIComponent(t[1]).replace(/-/g,":"):void 0}var re=r=>typeof r=="number"?Math.round(r*100)/100:r;function Sr(r){if(!r)return null;let t=n=>Math.round((n??0)*255).toString(16).padStart(2,"0"),e={hex:`#${t(r.r)}${t(r.g)}${t(r.b)}`.toUpperCase()};return r.a!=null&&r.a<1&&(e.opacity=re(r.a)),e}function Jn(r){return!r||r.visible===!1?null:r.type==="SOLID"?{type:"SOLID",...Sr(r.color),...r.opacity!=null?{opacity:r.opacity}:{}}:{type:r.type,...r.opacity!=null?{opacity:r.opacity}:{},...r.gradientStops?{stops:r.gradientStops.map(t=>({position:re(t.position),...Sr(t.color)}))}:{}}}function Dn(r,t){let e=r.absoluteBoundingBox,n={id:r.id,name:r.name,type:r.type};e&&(n.size={w:re(e.width),h:re(e.height)},n.position={x:re(e.x),y:re(e.y)}),r.opacity!=null&&r.opacity!==1&&(n.opacity=r.opacity),r.cornerRadius!=null&&(n.cornerRadius=r.cornerRadius),Array.isArray(r.rectangleCornerRadii)&&(n.cornerRadii=r.rectangleCornerRadii);let i=(r.fills||[]).map(Jn).filter(Boolean);i.length&&(n.fills=i);let s=(r.strokes||[]).map(Jn).filter(Boolean);s.length&&(n.strokes=s,r.strokeWeight!=null&&(n.strokeWeight=r.strokeWeight));let o=(r.effects||[]).filter(a=>a.visible!==!1).map(a=>({type:a.type,...a.radius!=null?{radius:a.radius}:{},...a.offset?{offset:{x:re(a.offset.x),y:re(a.offset.y)}}:{},...a.spread?{spread:a.spread}:{},...a.color?Sr(a.color):{}}));if(o.length&&(n.effects=o),r.layoutMode&&r.layoutMode!=="NONE"&&(n.autoLayout={direction:r.layoutMode,padding:{l:r.paddingLeft??0,r:r.paddingRight??0,t:r.paddingTop??0,b:r.paddingBottom??0},gap:r.itemSpacing??0,align:{primary:r.primaryAxisAlignItems,counter:r.counterAxisAlignItems}}),r.type==="TEXT"){let a=r.style||{};n.text=r.characters,n.textStyle={fontFamily:a.fontFamily,fontWeight:a.fontWeight,fontSize:a.fontSize,lineHeightPx:a.lineHeightPx!=null?re(a.lineHeightPx):void 0,letterSpacing:a.letterSpacing!=null?re(a.letterSpacing):void 0,align:a.textAlignHorizontal,case:a.textCase}}return t>0&&Array.isArray(r.children)&&r.children.length&&(n.children=r.children.map(a=>Dn(a,t-1))),n}var qn={id:"figma",callsBackend:!0,serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:I.FIGMA,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma
162
162
  You have access to the user's Figma files via the Figma REST API. Every tool that takes a file accepts EITHER the raw file key OR a full figma.com URL (figma.com/file|design/<key>/...). Node ids accept URL form \`1-23\` or API form \`1:23\` interchangeably. Tools:
163
163
 
164
164
  ### Identity
@@ -189,7 +189,7 @@ You have access to the user's Figma files via the Figma REST API. Every tool tha
189
189
 
190
190
  ### Notes
191
191
  - The file key is NOT the file name \u2014 it's the opaque id segment in the URL (or just paste the URL).
192
- - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes / figma_parse_url output.`,resolve(){let r=Ca();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/figma.js","figmaSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"figma_get_me":{let e=await Z("/v1/me");return JSON.stringify({id:e.id,handle:e.handle,email:e.email,imgUrl:e.img_url})}case"figma_get_file":{let e=ae((t||{}).fileKey),{depth:n}=t||{};if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=`/v1/files/${encodeURIComponent(e)}`;if(n!=null){let a=Number(n);!Number.isNaN(a)&&a>0&&(i+=`?depth=${a}`)}let s=await Z(i),o=(s.document?.children||[]).map(a=>({id:a.id,name:a.name,type:a.type,childCount:Array.isArray(a.children)?a.children.length:0,children:(a.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:s.name,lastModified:s.lastModified,version:s.version,editorType:s.editorType,role:s.role,pages:o})}case"figma_get_nodes":{let e=ae((t||{}).fileKey),{ids:n,depth:i}=t||{};if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=Rt(n);if(!s)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=new URLSearchParams;if(o.set("ids",s),i!=null){let d=Number(i);!Number.isNaN(d)&&d>0&&o.set("depth",String(d))}let a=await Z(`/v1/files/${encodeURIComponent(e)}/nodes?${o.toString()}`),c={};for(let[d,l]of Object.entries(a.nodes||{}))c[d]=l?.document?{id:l.document.id,name:l.document.name,type:l.document.type,document:l.document}:l;return JSON.stringify({name:a.name,nodes:c})}case"figma_get_node_specs":{let e=ae((t||{}).file),{ids:n,depth:i}=t||{};if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let s=Rt(n);if(!s)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=Number(i);Number.isNaN(o)&&(o=2),o=Math.min(6,Math.max(0,Math.trunc(o)));let a=new URLSearchParams;a.set("ids",s),a.set("depth",String(o));let c=await Z(`/v1/files/${encodeURIComponent(e)}/nodes?${a.toString()}`),d={};for(let[l,p]of Object.entries(c.nodes||{}))d[l]=p&&p.document?On(p.document,o):null;return JSON.stringify(d)}case"figma_render_png":{let e=ae((t||{}).fileKey??(t||{}).file),{ids:n,scale:i,format:s,svg_include_id:o,version:a}=t||{};if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let c=Rt(n);if(!c)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let d=["png","jpg","svg","pdf"].includes(String(s||"").toLowerCase())?String(s).toLowerCase():"png",l=new URLSearchParams;l.set("ids",c),l.set("format",d);let p;(d==="png"||d==="jpg")&&(p=Number(i),(Number.isNaN(p)||p<=0)&&(p=1),p=Math.min(4,Math.max(.01,p)),l.set("scale",String(p))),d==="svg"&&o!=null&&l.set("svg_include_id",String(!!o)),a&&l.set("version",String(a));let u=await Z(`/v1/images/${encodeURIComponent(e)}?${l.toString()}`);return u.err?JSON.stringify({error:`Figma render error: ${u.err}`}):JSON.stringify({format:d,...p!=null?{scale:p}:{},images:u.images||{}})}case"figma_get_image_fills":{let e=ae((t||{}).file);if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let n=await Z(`/v1/files/${encodeURIComponent(e)}/images`);return JSON.stringify({images:n.meta?.images??n.images??{}})}case"figma_get_file_versions":{let e=ae((t||{}).file);if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let i=((await Z(`/v1/files/${encodeURIComponent(e)}/versions`)).versions||[]).map(s=>({id:s.id,label:s.label,description:s.description,createdAt:s.created_at,user:s.user?.handle}));return JSON.stringify({count:i.length,versions:i})}case"figma_get_comments":{let e=ae((t||{}).fileKey);if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=((await Z(`/v1/files/${encodeURIComponent(e)}/comments`)).comments||[]).map(s=>({id:s.id,message:s.message,user:s.user?.handle,createdAt:s.created_at,resolvedAt:s.resolved_at||null,parentId:s.parent_id||null}));return JSON.stringify({count:i.length,comments:i})}case"figma_post_comment":{let e=ae((t||{}).file),{message:n,comment_id:i,node_id:s,x:o,y:a}=t||{};if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});if(!n)return JSON.stringify({error:"message is required"});let c={message:n};i&&(c.comment_id=i),s?c.client_meta={node_id:Rt(s),node_offset:{x:o??0,y:a??0}}:(o!=null||a!=null)&&(c.client_meta={x:o??0,y:a??0});let d=await Z(`/v1/files/${encodeURIComponent(e)}/comments`,{method:"POST",body:c});return JSON.stringify({id:d.id,message:d.message,fileKey:e,createdAt:d.created_at,parentId:d.parent_id||null})}case"figma_get_team_projects":{let{team_id:e}=t||{};if(!e)return JSON.stringify({error:"team_id is required"});let n=await Z(`/v1/teams/${encodeURIComponent(e)}/projects`);return JSON.stringify({name:n.name,projects:n.projects||[]})}case"figma_get_project_files":{let{project_id:e,branch_data:n}=t||{};if(!e)return JSON.stringify({error:"project_id is required"});let i=new URLSearchParams;n&&i.set("branch_data","true");let s=i.toString(),o=await Z(`/v1/projects/${encodeURIComponent(e)}/files${s?`?${s}`:""}`);return JSON.stringify({name:o.name,files:o.files||[]})}case"figma_parse_url":{let{url:e}=t||{};return JSON.stringify({file_key:ae(e),node_id:Ua(e)??null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree. Accepts a file key OR a figma.com URL (figma.com/file|design/<key>/... \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes or figma_get_node_specs to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'A file key OR a figma.com URL (e.g. "aBcD1234" or figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch. Accepts URL form ["1-23"] or API form ["1:23"]. A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_get_node_specs",description:"Dev-Mode-style inspection computed from the REST tree: for the given nodes and their children returns size, position, colors (hex), fonts/text-style, spacing/auto-layout, corner radius, strokes and effects \u2014 a compact spec for reproducing a design in code. Prefer this over figma_get_nodes when your job is to build UI from a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to inspect (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},depth:{type:"number",description:"How many levels of children to walk (0-6, default 2)."}},required:["file","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to an image and return the URLs (a map of nodeId \u2192 URL). Despite the name it renders PNG/JPG/SVG/PDF (default png). Use to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},format:{type:"string",enum:["png","jpg","svg","pdf"],description:"Output format (default png)."},scale:{type:"number",description:"Render scale, 0.01\u20134 (raster formats only; default 1). 2 for retina/hi-dpi."},svg_include_id:{type:"boolean",description:"For SVG: include element ids as attributes."},version:{type:"string",description:"Render a specific file version id (from figma_get_file_versions)."}},required:["fileKey","ids"]}},{name:"figma_get_image_fills",description:"Get a map of imageRef \u2192 download URL for every image fill used in a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_file_versions",description:"List a Figma file's saved version history (version id, label, created_at, user). A version id can be passed to figma_render_png to render a past version.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"}},required:["fileKey"]}},{name:"figma_post_comment",description:"Post a comment on a Figma file (WRITE \u2014 needs a PAT with comment-write scope). Optionally reply to a comment (comment_id), pin it to a node (node_id, with optional x/y offset), or pin to a canvas point (x/y).",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},message:{type:"string",description:"The comment text."},comment_id:{type:"string",description:"Optional: reply to this parent comment id."},node_id:{type:"string",description:'Optional: pin the comment to this node ("1-23" or "1:23").'},x:{type:"number",description:"Optional: x position (node offset if node_id given, else canvas point)."},y:{type:"number",description:"Optional: y position (node offset if node_id given, else canvas point)."}},required:["file","message"]}},{name:"figma_get_team_projects",description:"List the projects in a Figma team. Get team_id from a Figma team URL (\u2026/files/team/<TEAM_ID>/\u2026).",input_schema:{type:"object",properties:{team_id:{type:"string",description:"The Figma team id."}},required:["team_id"]}},{name:"figma_get_project_files",description:"List the files in a Figma project (from figma_get_team_projects). Returns file key, name, thumbnail, last_modified.",input_schema:{type:"object",properties:{project_id:{type:"string",description:"The Figma project id."},branch_data:{type:"boolean",description:"Optional: include branch metadata for each file."}},required:["project_id"]}},{name:"figma_parse_url",description:"Local helper (no API call): extract the file key and node id (colon form) from a figma.com file/design URL. Returns { file_key, node_id }.",input_schema:{type:"object",properties:{url:{type:"string",description:"A full figma.com file/design URL."}},required:["url"]}}]};import{existsSync as Ba}from"fs";import{fileURLToPath as Ja}from"url";import{dirname as qa,resolve as Da}from"path";import{resolveIntegrationToken as Ma}from"@zibby/core/backend-client.js";function Ka(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=qa(Ja(import.meta.url)),t=Da(r,"..","bin","mcp-skill.mjs");return Ba(t)?t:null}async function re(r,t={}){let{token:e}=await Ma("hubspot");if(!e)throw new Error("HubSpot not connected \u2014 Connect HubSpot in Integrations.");let n=r.startsWith("https://")?r:`https://api.hubapi.com${r}`,i={Authorization:`Bearer ${e}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!s.ok){let a=await s.text().catch(()=>""),c=s.status===401||s.status===403?" \u2014 token invalid/expired or missing the required Private App scope for this object":"";throw new Error(`HubSpot API ${s.status}${c}: ${a.slice(0,300)}`)}let o=await s.text().catch(()=>"");if(!o)return{};try{return JSON.parse(o)}catch{return{raw:o}}}function he(r){return typeof r!="string"?null:r.trim()||null}function An(r,t={}){let e=new URLSearchParams;if(r!=null){let i=Array.isArray(r)?r.join(","):String(r);i&&e.set("properties",i)}for(let[i,s]of Object.entries(t))s!=null&&s!==""&&e.set(i,String(s));let n=e.toString();return n?`?${n}`:""}var Ce="The CRM object type \u2014 one of the common values `contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions` (customer feedback: NPS/CSAT/CES), or any custom object name/id.",Rn={id:"hubspot",callsBackend:!0,serverName:"hubspot",allowedTools:["mcp__hubspot__*"],requiresIntegration:I.HUBSPOT,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"HubSpot CRM \u2014 search/read/create/update contacts, companies, deals, tickets, notes and feedback submissions via the HubSpot REST API.",promptFragment:"## HubSpot CRM\nYou have access to the user's HubSpot CRM via the HubSpot REST API (OAuth \u2014 the user connects HubSpot in Integrations; the token is resolved and auto-refreshed for you). The connected app grants the CRM scopes for the objects you touch.\n\nHubSpot's object model is **uniform** \u2014 nearly every tool takes an `objectType` (`contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions`, or a custom object). Records are `{ id, properties }`; you set/read named properties.\n\n**Before you create/update/search, call `hubspot_list_properties` to learn the valid property names for that object type** (they're not guessable). `feedback_submissions` is where NPS/CSAT/CES customer-feedback survey responses live.\n\n### Identity\n- hubspot_whoami: Confirm the token works \u2014 returns the portal (hub) id, account type, time zone, UI domain.\n\n### Schema\n- hubspot_list_properties: List the defined properties (name, label, type, fieldType) for an objectType. Do this first so you use real property names.\n\n### Read\n- hubspot_search: Search an objectType by full-text `query` OR structured `filters` (array of {propertyName, operator, value}). Returns { total, results:[{id, properties}] }.\n- hubspot_get_object: Fetch one record by id (optionally selecting specific properties).\n- hubspot_list_objects: Page through all records of an objectType (limit + after cursor).\n\n### Write\n- hubspot_create_object: Create a record from a `properties` object.\n- hubspot_update_object: Patch a record's `properties` by id.\n- hubspot_create_note: Convenience \u2014 log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket.\n- hubspot_associate: Associate two records (fromType/fromId \u2194 toType/toId) with the default association type.",resolve(){let r=Ka();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/hubspot.js","hubspotSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{let e=t||{};switch(r){case"hubspot_whoami":{let n=await re("/account-info/v3/details");return JSON.stringify({portalId:n.portalId,accountType:n.accountType,timeZone:n.timeZone,uiDomain:n.uiDomain,companyCurrency:n.companyCurrency})}case"hubspot_list_properties":{let n=he(e.objectType);if(!n)return JSON.stringify({error:"objectType is required (e.g. contacts, companies, deals, tickets, feedback_submissions)"});let s=((await re(`/crm/v3/properties/${encodeURIComponent(n)}`)).results||[]).map(o=>({name:o.name,label:o.label,type:o.type,fieldType:o.fieldType}));return JSON.stringify({objectType:n,count:s.length,properties:s})}case"hubspot_search":{let n=he(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let s={limit:Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20};e.query&&(s.query=String(e.query)),Array.isArray(e.filters)&&e.filters.length&&(s.filterGroups=[{filters:e.filters}]),e.properties!=null&&(s.properties=Array.isArray(e.properties)?e.properties:String(e.properties).split(",").map(a=>a.trim()).filter(Boolean));let o=await re(`/crm/v3/objects/${encodeURIComponent(n)}/search`,{method:"POST",body:s});return JSON.stringify({total:o.total??(o.results?o.results.length:0),results:(o.results||[]).map(a=>({id:a.id,properties:a.properties}))})}case"hubspot_get_object":{let n=he(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});let i=An(e.properties,{associations:e.associations}),s=await re(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(e.id)}${i}`);return JSON.stringify({id:s.id,properties:s.properties,...s.associations?{associations:s.associations}:{}})}case"hubspot_list_objects":{let n=he(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let i=Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20,s=An(e.properties,{limit:i,after:e.after}),o=await re(`/crm/v3/objects/${encodeURIComponent(n)}${s}`);return JSON.stringify({results:(o.results||[]).map(a=>({id:a.id,properties:a.properties})),paging:o.paging||null})}case"hubspot_create_object":{let n=he(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value } \u2014 call hubspot_list_properties first for valid names)"});let i=await re(`/crm/v3/objects/${encodeURIComponent(n)}`,{method:"POST",body:{properties:e.properties}});return JSON.stringify({id:i.id,properties:i.properties})}case"hubspot_update_object":{let n=he(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value })"});let i=await re(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(e.id)}`,{method:"PATCH",body:{properties:e.properties}});return JSON.stringify({id:i.id,properties:i.properties})}case"hubspot_create_note":{if(!e.body||typeof e.body!="string")return JSON.stringify({error:"body is required (the note text)"});let n=typeof e.timestamp=="string"&&e.timestamp?e.timestamp:null;if(!n)try{n=new Date().toISOString()}catch{n=null}if(!n)return JSON.stringify({error:"timestamp is required (pass an ISO 8601 string, e.g. 2026-01-01T00:00:00.000Z)"});let i=await re("/crm/v3/objects/notes",{method:"POST",body:{properties:{hs_note_body:e.body,hs_timestamp:n}}}),s=i.id,o=[["contacts",e.contactId],["companies",e.companyId],["deals",e.dealId],["tickets",e.ticketId]].filter(([,c])=>c!=null&&c!==""),a=[];for(let[c,d]of o)try{await re(`/crm/v4/objects/notes/${encodeURIComponent(s)}/associations/default/${c}/${encodeURIComponent(d)}`,{method:"PUT"}),a.push({toType:c,toId:String(d)})}catch(l){a.push({toType:c,toId:String(d),error:l.message})}return JSON.stringify({id:s,properties:i.properties,associatedTo:a})}case"hubspot_associate":{let n=he(e.fromType),i=he(e.toType);return!n||!e.fromId||!i||!e.toId?JSON.stringify({error:"fromType, fromId, toType and toId are all required"}):(await re(`/crm/v4/objects/${encodeURIComponent(n)}/${encodeURIComponent(e.fromId)}/associations/default/${encodeURIComponent(i)}/${encodeURIComponent(e.toId)}`,{method:"PUT"}),JSON.stringify({ok:!0}))}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"hubspot_whoami",description:"Confirm the HubSpot token works: returns the portal (hub) id, account type, time zone and UI domain.",input_schema:{type:"object",properties:{}}},{name:"hubspot_list_properties",description:"List the defined properties (name, label, type, fieldType) for a CRM object type. Call this FIRST so you use valid property names when creating/updating/searching.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Ce}},required:["objectType"]}},{name:"hubspot_search",description:"Search a CRM object type. Pass a full-text `query` OR structured `filters` (array of {propertyName, operator, value}, e.g. operator EQ/CONTAINS_TOKEN/GT/\u2026). Returns { total, results:[{id, properties}] }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Ce},query:{type:"string",description:"Optional full-text search string."},filters:{type:"array",description:"Optional structured filters (ANDed). Each: { propertyName, operator, value }. Operators: EQ, NEQ, LT, LTE, GT, GTE, CONTAINS_TOKEN, HAS_PROPERTY, IN, \u2026",items:{type:"object",properties:{propertyName:{type:"string"},operator:{type:"string"},value:{type:"string"}}}},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each result."},limit:{type:"number",description:"Max results (default 20)."}},required:["objectType"]}},{name:"hubspot_get_object",description:"Fetch one CRM record by id. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Ce},id:{type:"string",description:"The record id."},properties:{type:"array",items:{type:"string"},description:"Optional: specific property names to return."},associations:{type:"string",description:'Optional: comma-separated object types to also return associations for (e.g. "companies,deals").'}},required:["objectType","id"]}},{name:"hubspot_list_objects",description:"Page through records of a CRM object type. Returns { results, paging } \u2014 pass paging.next.after back as `after` for the next page.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Ce},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each record."},limit:{type:"number",description:"Page size (default 20)."},after:{type:"string",description:"Optional paging cursor from a previous response (paging.next.after)."}},required:["objectType"]}},{name:"hubspot_create_object",description:"Create a CRM record. Pass `properties` as an object of { propertyName: value } (call hubspot_list_properties first for valid names). Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Ce},properties:{type:"object",description:"Object of { propertyName: value } to set on the new record."}},required:["objectType","properties"]}},{name:"hubspot_update_object",description:"Update (PATCH) a CRM record by id. Pass `properties` as an object of { propertyName: value }. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Ce},id:{type:"string",description:"The record id to update."},properties:{type:"object",description:"Object of { propertyName: value } to change."}},required:["objectType","id","properties"]}},{name:"hubspot_create_note",description:"Log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket. Returns { id, associatedTo }.",input_schema:{type:"object",properties:{body:{type:"string",description:"The note text (stored as hs_note_body)."},contactId:{type:"string",description:"Optional: associate the note to this contact id."},companyId:{type:"string",description:"Optional: associate the note to this company id."},dealId:{type:"string",description:"Optional: associate the note to this deal id."},ticketId:{type:"string",description:"Optional: associate the note to this ticket id."},timestamp:{type:"string",description:"Optional ISO 8601 timestamp for the note (defaults to now)."}},required:["body"]}},{name:"hubspot_associate",description:"Associate two CRM records with the default association type (e.g. a contact to a company). Returns { ok:true }.",input_schema:{type:"object",properties:{fromType:{type:"string",description:"Source object type (e.g. contacts)."},fromId:{type:"string",description:"Source record id."},toType:{type:"string",description:"Target object type (e.g. companies)."},toId:{type:"string",description:"Target record id."}},required:["fromType","fromId","toType","toId"]}}]};import{existsSync as Ga}from"fs";import{fileURLToPath as Fa}from"url";import{dirname as Ha,resolve as za}from"path";function Ya(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ha(Fa(import.meta.url)),t=za(r,"..","bin","mcp-skill.mjs");return Ga(t)?t:null}var Wa=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Za(){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 V(r,t={}){let e=await fetch(Wa,{method:"POST",headers:{Authorization:Za(),"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:t})});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`Linear API ${e.status}: ${i.slice(0,300)}`)}let n=await e.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 Xe(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Va(r,t){let e=Xe(r),n=Xe(t);if(!e||!n)return 0;if(e===n)return 1;if(e.length===1||n.length===1)return e===n?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=i(e),o=i(n),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of s.entries())a+=Math.min(p,o.get(l)||0);return 2*a/Math.max(1,c+d)}function Xa(r,t){let e=Array.isArray(r)?r:[];if(!e.length)return{state:null,strategy:"no-states"};let n=Xe(t);if(!n)return{state:null,strategy:"no-target"};let i=e.find(a=>Xe(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=>Xe(l)===n))continue;let d=e.find(l=>l.type===a);if(d)return{state:d,strategy:"type-alias"}}let o=e.map(a=>({s:a,score:Va(t,a.name)})).sort((a,c)=>c.score-a.score);return o[0]&&o[0].score>=.5?{state:o[0].s,strategy:"fuzzy"}:{state:null,strategy:"no-match"}}var Qa=`
192
+ - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes / figma_parse_url output.`,resolve(){let r=pc();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/figma.js","figmaSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"figma_get_me":{let e=await Z("/v1/me");return JSON.stringify({id:e.id,handle:e.handle,email:e.email,imgUrl:e.img_url})}case"figma_get_file":{let e=de((t||{}).fileKey),{depth:n}=t||{};if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=`/v1/files/${encodeURIComponent(e)}`;if(n!=null){let a=Number(n);!Number.isNaN(a)&&a>0&&(i+=`?depth=${a}`)}let s=await Z(i),o=(s.document?.children||[]).map(a=>({id:a.id,name:a.name,type:a.type,childCount:Array.isArray(a.children)?a.children.length:0,children:(a.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:s.name,lastModified:s.lastModified,version:s.version,editorType:s.editorType,role:s.role,pages:o})}case"figma_get_nodes":{let e=de((t||{}).fileKey),{ids:n,depth:i}=t||{};if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=Bt(n);if(!s)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=new URLSearchParams;if(o.set("ids",s),i!=null){let l=Number(i);!Number.isNaN(l)&&l>0&&o.set("depth",String(l))}let a=await Z(`/v1/files/${encodeURIComponent(e)}/nodes?${o.toString()}`),c={};for(let[l,d]of Object.entries(a.nodes||{}))c[l]=d?.document?{id:d.document.id,name:d.document.name,type:d.document.type,document:d.document}:d;return JSON.stringify({name:a.name,nodes:c})}case"figma_get_node_specs":{let e=de((t||{}).file),{ids:n,depth:i}=t||{};if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let s=Bt(n);if(!s)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=Number(i);Number.isNaN(o)&&(o=2),o=Math.min(6,Math.max(0,Math.trunc(o)));let a=new URLSearchParams;a.set("ids",s),a.set("depth",String(o));let c=await Z(`/v1/files/${encodeURIComponent(e)}/nodes?${a.toString()}`),l={};for(let[d,p]of Object.entries(c.nodes||{}))l[d]=p&&p.document?Dn(p.document,o):null;return JSON.stringify(l)}case"figma_render_png":{let e=de((t||{}).fileKey??(t||{}).file),{ids:n,scale:i,format:s,svg_include_id:o,version:a}=t||{};if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let c=Bt(n);if(!c)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let l=["png","jpg","svg","pdf"].includes(String(s||"").toLowerCase())?String(s).toLowerCase():"png",d=new URLSearchParams;d.set("ids",c),d.set("format",l);let p;(l==="png"||l==="jpg")&&(p=Number(i),(Number.isNaN(p)||p<=0)&&(p=1),p=Math.min(4,Math.max(.01,p)),d.set("scale",String(p))),l==="svg"&&o!=null&&d.set("svg_include_id",String(!!o)),a&&d.set("version",String(a));let u=await Z(`/v1/images/${encodeURIComponent(e)}?${d.toString()}`);return u.err?JSON.stringify({error:`Figma render error: ${u.err}`}):JSON.stringify({format:l,...p!=null?{scale:p}:{},images:u.images||{}})}case"figma_get_image_fills":{let e=de((t||{}).file);if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let n=await Z(`/v1/files/${encodeURIComponent(e)}/images`);return JSON.stringify({images:n.meta?.images??n.images??{}})}case"figma_get_file_versions":{let e=de((t||{}).file);if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let i=((await Z(`/v1/files/${encodeURIComponent(e)}/versions`)).versions||[]).map(s=>({id:s.id,label:s.label,description:s.description,createdAt:s.created_at,user:s.user?.handle}));return JSON.stringify({count:i.length,versions:i})}case"figma_get_comments":{let e=de((t||{}).fileKey);if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=((await Z(`/v1/files/${encodeURIComponent(e)}/comments`)).comments||[]).map(s=>({id:s.id,message:s.message,user:s.user?.handle,createdAt:s.created_at,resolvedAt:s.resolved_at||null,parentId:s.parent_id||null}));return JSON.stringify({count:i.length,comments:i})}case"figma_post_comment":{let e=de((t||{}).file),{message:n,comment_id:i,node_id:s,x:o,y:a}=t||{};if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});if(!n)return JSON.stringify({error:"message is required"});let c={message:n};i&&(c.comment_id=i),s?c.client_meta={node_id:Bt(s),node_offset:{x:o??0,y:a??0}}:(o!=null||a!=null)&&(c.client_meta={x:o??0,y:a??0});let l=await Z(`/v1/files/${encodeURIComponent(e)}/comments`,{method:"POST",body:c});return JSON.stringify({id:l.id,message:l.message,fileKey:e,createdAt:l.created_at,parentId:l.parent_id||null})}case"figma_get_team_projects":{let{team_id:e}=t||{};if(!e)return JSON.stringify({error:"team_id is required"});let n=await Z(`/v1/teams/${encodeURIComponent(e)}/projects`);return JSON.stringify({name:n.name,projects:n.projects||[]})}case"figma_get_project_files":{let{project_id:e,branch_data:n}=t||{};if(!e)return JSON.stringify({error:"project_id is required"});let i=new URLSearchParams;n&&i.set("branch_data","true");let s=i.toString(),o=await Z(`/v1/projects/${encodeURIComponent(e)}/files${s?`?${s}`:""}`);return JSON.stringify({name:o.name,files:o.files||[]})}case"figma_parse_url":{let{url:e}=t||{};return JSON.stringify({file_key:de(e),node_id:uc(e)??null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree. Accepts a file key OR a figma.com URL (figma.com/file|design/<key>/... \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes or figma_get_node_specs to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'A file key OR a figma.com URL (e.g. "aBcD1234" or figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch. Accepts URL form ["1-23"] or API form ["1:23"]. A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_get_node_specs",description:"Dev-Mode-style inspection computed from the REST tree: for the given nodes and their children returns size, position, colors (hex), fonts/text-style, spacing/auto-layout, corner radius, strokes and effects \u2014 a compact spec for reproducing a design in code. Prefer this over figma_get_nodes when your job is to build UI from a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to inspect (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},depth:{type:"number",description:"How many levels of children to walk (0-6, default 2)."}},required:["file","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to an image and return the URLs (a map of nodeId \u2192 URL). Despite the name it renders PNG/JPG/SVG/PDF (default png). Use to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},format:{type:"string",enum:["png","jpg","svg","pdf"],description:"Output format (default png)."},scale:{type:"number",description:"Render scale, 0.01\u20134 (raster formats only; default 1). 2 for retina/hi-dpi."},svg_include_id:{type:"boolean",description:"For SVG: include element ids as attributes."},version:{type:"string",description:"Render a specific file version id (from figma_get_file_versions)."}},required:["fileKey","ids"]}},{name:"figma_get_image_fills",description:"Get a map of imageRef \u2192 download URL for every image fill used in a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_file_versions",description:"List a Figma file's saved version history (version id, label, created_at, user). A version id can be passed to figma_render_png to render a past version.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"}},required:["fileKey"]}},{name:"figma_post_comment",description:"Post a comment on a Figma file (WRITE \u2014 needs a PAT with comment-write scope). Optionally reply to a comment (comment_id), pin it to a node (node_id, with optional x/y offset), or pin to a canvas point (x/y).",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},message:{type:"string",description:"The comment text."},comment_id:{type:"string",description:"Optional: reply to this parent comment id."},node_id:{type:"string",description:'Optional: pin the comment to this node ("1-23" or "1:23").'},x:{type:"number",description:"Optional: x position (node offset if node_id given, else canvas point)."},y:{type:"number",description:"Optional: y position (node offset if node_id given, else canvas point)."}},required:["file","message"]}},{name:"figma_get_team_projects",description:"List the projects in a Figma team. Get team_id from a Figma team URL (\u2026/files/team/<TEAM_ID>/\u2026).",input_schema:{type:"object",properties:{team_id:{type:"string",description:"The Figma team id."}},required:["team_id"]}},{name:"figma_get_project_files",description:"List the files in a Figma project (from figma_get_team_projects). Returns file key, name, thumbnail, last_modified.",input_schema:{type:"object",properties:{project_id:{type:"string",description:"The Figma project id."},branch_data:{type:"boolean",description:"Optional: include branch metadata for each file."}},required:["project_id"]}},{name:"figma_parse_url",description:"Local helper (no API call): extract the file key and node id (colon form) from a figma.com file/design URL. Returns { file_key, node_id }.",input_schema:{type:"object",properties:{url:{type:"string",description:"A full figma.com file/design URL."}},required:["url"]}}]};import{existsSync as mc}from"fs";import{fileURLToPath as fc}from"url";import{dirname as hc,resolve as yc}from"path";import{resolveIntegrationToken as gc}from"@zibby/core/backend-client.js";function bc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=hc(fc(import.meta.url)),t=yc(r,"..","bin","mcp-skill.mjs");return mc(t)?t:null}async function ne(r,t={}){let{token:e}=await gc("hubspot");if(!e)throw new Error("HubSpot not connected \u2014 Connect HubSpot in Integrations.");let n=r.startsWith("https://")?r:`https://api.hubapi.com${r}`,i={Authorization:`Bearer ${e}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!s.ok){let a=await s.text().catch(()=>""),c=s.status===401||s.status===403?" \u2014 token invalid/expired or missing the required Private App scope for this object":"";throw new Error(`HubSpot API ${s.status}${c}: ${a.slice(0,300)}`)}let o=await s.text().catch(()=>"");if(!o)return{};try{return JSON.parse(o)}catch{return{raw:o}}}function ke(r){return typeof r!="string"?null:r.trim()||null}function Mn(r,t={}){let e=new URLSearchParams;if(r!=null){let i=Array.isArray(r)?r.join(","):String(r);i&&e.set("properties",i)}for(let[i,s]of Object.entries(t))s!=null&&s!==""&&e.set(i,String(s));let n=e.toString();return n?`?${n}`:""}var qe="The CRM object type \u2014 one of the common values `contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions` (customer feedback: NPS/CSAT/CES), or any custom object name/id.",Fn={id:"hubspot",callsBackend:!0,serverName:"hubspot",allowedTools:["mcp__hubspot__*"],requiresIntegration:I.HUBSPOT,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"HubSpot CRM \u2014 search/read/create/update contacts, companies, deals, tickets, notes and feedback submissions via the HubSpot REST API.",promptFragment:"## HubSpot CRM\nYou have access to the user's HubSpot CRM via the HubSpot REST API (OAuth \u2014 the user connects HubSpot in Integrations; the token is resolved and auto-refreshed for you). The connected app grants the CRM scopes for the objects you touch.\n\nHubSpot's object model is **uniform** \u2014 nearly every tool takes an `objectType` (`contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions`, or a custom object). Records are `{ id, properties }`; you set/read named properties.\n\n**Before you create/update/search, call `hubspot_list_properties` to learn the valid property names for that object type** (they're not guessable). `feedback_submissions` is where NPS/CSAT/CES customer-feedback survey responses live.\n\n### Identity\n- hubspot_whoami: Confirm the token works \u2014 returns the portal (hub) id, account type, time zone, UI domain.\n\n### Schema\n- hubspot_list_properties: List the defined properties (name, label, type, fieldType) for an objectType. Do this first so you use real property names.\n\n### Read\n- hubspot_search: Search an objectType by full-text `query` OR structured `filters` (array of {propertyName, operator, value}). Returns { total, results:[{id, properties}] }.\n- hubspot_get_object: Fetch one record by id (optionally selecting specific properties).\n- hubspot_list_objects: Page through all records of an objectType (limit + after cursor).\n\n### Write\n- hubspot_create_object: Create a record from a `properties` object.\n- hubspot_update_object: Patch a record's `properties` by id.\n- hubspot_create_note: Convenience \u2014 log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket.\n- hubspot_associate: Associate two records (fromType/fromId \u2194 toType/toId) with the default association type.",resolve(){let r=bc();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/hubspot.js","hubspotSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{let e=t||{};switch(r){case"hubspot_whoami":{let n=await ne("/account-info/v3/details");return JSON.stringify({portalId:n.portalId,accountType:n.accountType,timeZone:n.timeZone,uiDomain:n.uiDomain,companyCurrency:n.companyCurrency})}case"hubspot_list_properties":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required (e.g. contacts, companies, deals, tickets, feedback_submissions)"});let s=((await ne(`/crm/v3/properties/${encodeURIComponent(n)}`)).results||[]).map(o=>({name:o.name,label:o.label,type:o.type,fieldType:o.fieldType}));return JSON.stringify({objectType:n,count:s.length,properties:s})}case"hubspot_search":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let s={limit:Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20};e.query&&(s.query=String(e.query)),Array.isArray(e.filters)&&e.filters.length&&(s.filterGroups=[{filters:e.filters}]),e.properties!=null&&(s.properties=Array.isArray(e.properties)?e.properties:String(e.properties).split(",").map(a=>a.trim()).filter(Boolean));let o=await ne(`/crm/v3/objects/${encodeURIComponent(n)}/search`,{method:"POST",body:s});return JSON.stringify({total:o.total??(o.results?o.results.length:0),results:(o.results||[]).map(a=>({id:a.id,properties:a.properties}))})}case"hubspot_get_object":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});let i=Mn(e.properties,{associations:e.associations}),s=await ne(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(e.id)}${i}`);return JSON.stringify({id:s.id,properties:s.properties,...s.associations?{associations:s.associations}:{}})}case"hubspot_list_objects":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let i=Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20,s=Mn(e.properties,{limit:i,after:e.after}),o=await ne(`/crm/v3/objects/${encodeURIComponent(n)}${s}`);return JSON.stringify({results:(o.results||[]).map(a=>({id:a.id,properties:a.properties})),paging:o.paging||null})}case"hubspot_create_object":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value } \u2014 call hubspot_list_properties first for valid names)"});let i=await ne(`/crm/v3/objects/${encodeURIComponent(n)}`,{method:"POST",body:{properties:e.properties}});return JSON.stringify({id:i.id,properties:i.properties})}case"hubspot_update_object":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value })"});let i=await ne(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(e.id)}`,{method:"PATCH",body:{properties:e.properties}});return JSON.stringify({id:i.id,properties:i.properties})}case"hubspot_create_note":{if(!e.body||typeof e.body!="string")return JSON.stringify({error:"body is required (the note text)"});let n=typeof e.timestamp=="string"&&e.timestamp?e.timestamp:null;if(!n)try{n=new Date().toISOString()}catch{n=null}if(!n)return JSON.stringify({error:"timestamp is required (pass an ISO 8601 string, e.g. 2026-01-01T00:00:00.000Z)"});let i=await ne("/crm/v3/objects/notes",{method:"POST",body:{properties:{hs_note_body:e.body,hs_timestamp:n}}}),s=i.id,o=[["contacts",e.contactId],["companies",e.companyId],["deals",e.dealId],["tickets",e.ticketId]].filter(([,c])=>c!=null&&c!==""),a=[];for(let[c,l]of o)try{await ne(`/crm/v4/objects/notes/${encodeURIComponent(s)}/associations/default/${c}/${encodeURIComponent(l)}`,{method:"PUT"}),a.push({toType:c,toId:String(l)})}catch(d){a.push({toType:c,toId:String(l),error:d.message})}return JSON.stringify({id:s,properties:i.properties,associatedTo:a})}case"hubspot_associate":{let n=ke(e.fromType),i=ke(e.toType);return!n||!e.fromId||!i||!e.toId?JSON.stringify({error:"fromType, fromId, toType and toId are all required"}):(await ne(`/crm/v4/objects/${encodeURIComponent(n)}/${encodeURIComponent(e.fromId)}/associations/default/${encodeURIComponent(i)}/${encodeURIComponent(e.toId)}`,{method:"PUT"}),JSON.stringify({ok:!0}))}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"hubspot_whoami",description:"Confirm the HubSpot token works: returns the portal (hub) id, account type, time zone and UI domain.",input_schema:{type:"object",properties:{}}},{name:"hubspot_list_properties",description:"List the defined properties (name, label, type, fieldType) for a CRM object type. Call this FIRST so you use valid property names when creating/updating/searching.",input_schema:{type:"object",properties:{objectType:{type:"string",description:qe}},required:["objectType"]}},{name:"hubspot_search",description:"Search a CRM object type. Pass a full-text `query` OR structured `filters` (array of {propertyName, operator, value}, e.g. operator EQ/CONTAINS_TOKEN/GT/\u2026). Returns { total, results:[{id, properties}] }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:qe},query:{type:"string",description:"Optional full-text search string."},filters:{type:"array",description:"Optional structured filters (ANDed). Each: { propertyName, operator, value }. Operators: EQ, NEQ, LT, LTE, GT, GTE, CONTAINS_TOKEN, HAS_PROPERTY, IN, \u2026",items:{type:"object",properties:{propertyName:{type:"string"},operator:{type:"string"},value:{type:"string"}}}},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each result."},limit:{type:"number",description:"Max results (default 20)."}},required:["objectType"]}},{name:"hubspot_get_object",description:"Fetch one CRM record by id. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:qe},id:{type:"string",description:"The record id."},properties:{type:"array",items:{type:"string"},description:"Optional: specific property names to return."},associations:{type:"string",description:'Optional: comma-separated object types to also return associations for (e.g. "companies,deals").'}},required:["objectType","id"]}},{name:"hubspot_list_objects",description:"Page through records of a CRM object type. Returns { results, paging } \u2014 pass paging.next.after back as `after` for the next page.",input_schema:{type:"object",properties:{objectType:{type:"string",description:qe},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each record."},limit:{type:"number",description:"Page size (default 20)."},after:{type:"string",description:"Optional paging cursor from a previous response (paging.next.after)."}},required:["objectType"]}},{name:"hubspot_create_object",description:"Create a CRM record. Pass `properties` as an object of { propertyName: value } (call hubspot_list_properties first for valid names). Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:qe},properties:{type:"object",description:"Object of { propertyName: value } to set on the new record."}},required:["objectType","properties"]}},{name:"hubspot_update_object",description:"Update (PATCH) a CRM record by id. Pass `properties` as an object of { propertyName: value }. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:qe},id:{type:"string",description:"The record id to update."},properties:{type:"object",description:"Object of { propertyName: value } to change."}},required:["objectType","id","properties"]}},{name:"hubspot_create_note",description:"Log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket. Returns { id, associatedTo }.",input_schema:{type:"object",properties:{body:{type:"string",description:"The note text (stored as hs_note_body)."},contactId:{type:"string",description:"Optional: associate the note to this contact id."},companyId:{type:"string",description:"Optional: associate the note to this company id."},dealId:{type:"string",description:"Optional: associate the note to this deal id."},ticketId:{type:"string",description:"Optional: associate the note to this ticket id."},timestamp:{type:"string",description:"Optional ISO 8601 timestamp for the note (defaults to now)."}},required:["body"]}},{name:"hubspot_associate",description:"Associate two CRM records with the default association type (e.g. a contact to a company). Returns { ok:true }.",input_schema:{type:"object",properties:{fromType:{type:"string",description:"Source object type (e.g. contacts)."},fromId:{type:"string",description:"Source record id."},toType:{type:"string",description:"Target object type (e.g. companies)."},toId:{type:"string",description:"Target record id."}},required:["fromType","fromId","toType","toId"]}}]};import{existsSync as _c}from"fs";import{fileURLToPath as kc}from"url";import{dirname as wc,resolve as Sc}from"path";function vc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=wc(kc(import.meta.url)),t=Sc(r,"..","bin","mcp-skill.mjs");return _c(t)?t:null}var Ic=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Nc(){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 V(r,t={}){let e=await fetch(Ic,{method:"POST",headers:{Authorization:Nc(),"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:t})});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`Linear API ${e.status}: ${i.slice(0,300)}`)}let n=await e.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 it(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Oc(r,t){let e=it(r),n=it(t);if(!e||!n)return 0;if(e===n)return 1;if(e.length===1||n.length===1)return e===n?1:0;let i=d=>{let p=new Map;for(let u=0;u<d.length-1;u++){let m=d.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=i(e),o=i(n),a=0,c=0,l=0;for(let d of s.values())c+=d;for(let d of o.values())l+=d;for(let[d,p]of s.entries())a+=Math.min(p,o.get(d)||0);return 2*a/Math.max(1,c+l)}function Tc(r,t){let e=Array.isArray(r)?r:[];if(!e.length)return{state:null,strategy:"no-states"};let n=it(t);if(!n)return{state:null,strategy:"no-target"};let i=e.find(a=>it(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(d=>it(d)===n))continue;let l=e.find(d=>d.type===a);if(l)return{state:l,strategy:"type-alias"}}let o=e.map(a=>({s:a,score:Oc(t,a.name)})).sort((a,c)=>c.score-a.score);return o[0]&&o[0].score>=.5?{state:o[0].s,strategy:"fuzzy"}:{state:null,strategy:"no-match"}}var Rc=`
193
193
  id
194
194
  identifier
195
195
  number
@@ -203,7 +203,7 @@ You have access to the user's Figma files via the Figma REST API. Every tool tha
203
203
  assignee { id name displayName email }
204
204
  labels { nodes { id name color } }
205
205
  team { id key name }
206
- `,jn={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:I.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear
206
+ `,Gn={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:I.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear
207
207
  You have direct access to the user's Linear workspace (GraphQL API). Tools:
208
208
 
209
209
  ### Discovery
@@ -221,20 +221,20 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
221
221
 
222
222
  ### Notes
223
223
  - 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.
224
- - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);process.env.LINEAR_API_URL&&(r.LINEAR_API_URL=process.env.LINEAR_API_URL);let t=Ya();return t?{type:"stdio",command:"node",args:[t,"../dist/linear.js","linearSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,t){try{switch(r){case"linear_list_teams":{let n=(await V(`
224
+ - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);process.env.LINEAR_API_URL&&(r.LINEAR_API_URL=process.env.LINEAR_API_URL);let t=vc();return t?{type:"stdio",command:"node",args:[t,"../dist/linear.js","linearSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,t){try{switch(r){case"linear_list_teams":{let n=(await V(`
225
225
  query Teams($first: Int) {
226
226
  teams(first: $first) {
227
227
  nodes { id key name description }
228
228
  }
229
229
  }
230
- `,{first:t?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:n.length,teams:n})}case"linear_list_states":{let{teamId:e,teamKey:n}=t||{},i=e;if(!i&&n&&(i=await En(n)),i){let c=(await V(`
230
+ `,{first:t?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:n.length,teams:n})}case"linear_list_states":{let{teamId:e,teamKey:n}=t||{},i=e;if(!i&&n&&(i=await Kn(n)),i){let c=(await V(`
231
231
  query States($teamId: String!) {
232
232
  team(id: $teamId) {
233
233
  id key name
234
234
  states { nodes { id name type color position } }
235
235
  }
236
236
  }
237
- `,{teamId:i}))?.team,d=(c?.states?.nodes||[]).slice().sort((l,p)=>(l.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:d.length,states:d})}let o=(await V(`
237
+ `,{teamId:i}))?.team,l=(c?.states?.nodes||[]).slice().sort((d,p)=>(d.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:l.length,states:l})}let o=(await V(`
238
238
  query AllStates($first: Int) {
239
239
  workflowStates(first: $first) {
240
240
  nodes { id name type color team { id key name } }
@@ -246,7 +246,7 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
246
246
  nodes { id name color team { id key } }
247
247
  }
248
248
  }
249
- `,{first:t?.limit||100,filter:e?{team:{id:{eq:e}}}:void 0}))?.issueLabels?.nodes||[];return JSON.stringify({count:i.length,labels:i})}case"linear_list_issues":{let{teamId:e,teamKey:n,stateId:i,stateName:s,label:o,assigneeId:a,updatedAfter:c,limit:d}=t||{},l={},p=e;!p&&n&&(p=await En(n)),p&&(l.team={id:{eq:p}}),i?l.state={id:{eq:i}}:s&&(l.state={name:{eqIgnoreCase:s}}),o&&(l.labels={name:{eqIgnoreCase:o}}),a&&(l.assignee={id:{eq:a}}),c&&(l.updatedAt={gt:c});let m=((await V(`
249
+ `,{first:t?.limit||100,filter:e?{team:{id:{eq:e}}}:void 0}))?.issueLabels?.nodes||[];return JSON.stringify({count:i.length,labels:i})}case"linear_list_issues":{let{teamId:e,teamKey:n,stateId:i,stateName:s,label:o,assigneeId:a,updatedAfter:c,limit:l}=t||{},d={},p=e;!p&&n&&(p=await Kn(n)),p&&(d.team={id:{eq:p}}),i?d.state={id:{eq:i}}:s&&(d.state={name:{eqIgnoreCase:s}}),o&&(d.labels={name:{eqIgnoreCase:o}}),a&&(d.assignee={id:{eq:a}}),c&&(d.updatedAt={gt:c});let m=((await V(`
250
250
  query Issues($first: Int, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
251
251
  issues(first: $first, filter: $filter, orderBy: $orderBy) {
252
252
  nodes {
@@ -258,41 +258,41 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
258
258
  }
259
259
  }
260
260
  }
261
- `,{first:d||30,filter:Object.keys(l).length?l:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(f=>({id:f.id,identifier:f.identifier,number:f.number,title:f.title,url:f.url,priority:f.priority,state:f.state?.name,stateType:f.state?.type,assignee:f.assignee?.displayName||null,labels:(f.labels?.nodes||[]).map(h=>h.name),team:f.team?.key,createdAt:f.createdAt,updatedAt:f.updatedAt}));return JSON.stringify({count:m.length,issues:m})}case"linear_get_issue":{let e=t?.issueId||t?.identifier||t?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let n=await Ve(e);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: ${e}`})}case"linear_get_comments":{let e=t?.issueId||t?.identifier||t?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let n=await Ve(e,`
261
+ `,{first:l||30,filter:Object.keys(d).length?d:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(f=>({id:f.id,identifier:f.identifier,number:f.number,title:f.title,url:f.url,priority:f.priority,state:f.state?.name,stateType:f.state?.type,assignee:f.assignee?.displayName||null,labels:(f.labels?.nodes||[]).map(h=>h.name),team:f.team?.key,createdAt:f.createdAt,updatedAt:f.updatedAt}));return JSON.stringify({count:m.length,issues:m})}case"linear_get_issue":{let e=t?.issueId||t?.identifier||t?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let n=await nt(e);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: ${e}`})}case"linear_get_comments":{let e=t?.issueId||t?.identifier||t?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let n=await nt(e,`
262
262
  id identifier
263
263
  comments(first: ${Number(t?.limit)||50}) {
264
264
  nodes { id body createdAt updatedAt user { id name displayName } }
265
265
  }
266
- `);if(!n)return JSON.stringify({error:`Issue not found: ${e}`});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 e=t?.issueId||t?.identifier||t?.issueKey,n=t?.body;if(!e||!n)return JSON.stringify({error:"issueId/identifier and body are required"});let i=await Ve(e,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await V(`
266
+ `);if(!n)return JSON.stringify({error:`Issue not found: ${e}`});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 e=t?.issueId||t?.identifier||t?.issueKey,n=t?.body;if(!e||!n)return JSON.stringify({error:"issueId/identifier and body are required"});let i=await nt(e,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await V(`
267
267
  mutation AddComment($input: CommentCreateInput!) {
268
268
  commentCreate(input: $input) {
269
269
  success
270
270
  comment { id url createdAt }
271
271
  }
272
272
  }
273
- `,{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 e=t?.issueId||t?.identifier||t?.issueKey,{stateId:n,stateName:i,toStatus:s,status:o}=t||{};if(!e)return JSON.stringify({error:"issueId or identifier is required"});let a=await Ve(e,`
273
+ `,{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 e=t?.issueId||t?.identifier||t?.issueKey,{stateId:n,stateName:i,toStatus:s,status:o}=t||{};if(!e)return JSON.stringify({error:"issueId or identifier is required"});let a=await nt(e,`
274
274
  id identifier
275
275
  state { id name type }
276
276
  team { id key states { nodes { id name type position } } }
277
- `);if(!a)return JSON.stringify({error:`Issue not found: ${e}`});let c=n,d=n?{strategy:"explicit-id"}:null;if(!c){let u=String(i||s||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((h,b)=>(h.position||0)-(b.position||0));if(!u)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});let f=Xa(m,u);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${u}" in team ${a.team?.key}`,issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});c=f.state.id,d={strategy:f.strategy,matchedName:f.state.name}}let p=(await V(`
277
+ `);if(!a)return JSON.stringify({error:`Issue not found: ${e}`});let c=n,l=n?{strategy:"explicit-id"}:null;if(!c){let u=String(i||s||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((h,_)=>(h.position||0)-(_.position||0));if(!u)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});let f=Tc(m,u);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${u}" in team ${a.team?.key}`,issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});c=f.state.id,l={strategy:f.strategy,matchedName:f.state.name}}let p=(await V(`
278
278
  mutation MoveIssue($id: String!, $input: IssueUpdateInput!) {
279
279
  issueUpdate(id: $id, input: $input) {
280
280
  success
281
281
  issue { id identifier state { id name type } }
282
282
  }
283
283
  }
284
- `,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!p?.success,issue:p?.issue?.identifier||a.identifier,stateAfter:p?.issue?.state?.name||null,stateTypeAfter:p?.issue?.state?.type||null,resolution:d})}case"linear_link_attachment":{let e=t?.issueId||t?.identifier||t?.issueKey,{url:n,title:i,subtitle:s}=t||{};if(!e||!n)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await Ve(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let c=(await V(`
284
+ `,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!p?.success,issue:p?.issue?.identifier||a.identifier,stateAfter:p?.issue?.state?.name||null,stateTypeAfter:p?.issue?.state?.type||null,resolution:l})}case"linear_link_attachment":{let e=t?.issueId||t?.identifier||t?.issueKey,{url:n,title:i,subtitle:s}=t||{};if(!e||!n)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await nt(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let c=(await V(`
285
285
  mutation LinkAttachment($input: AttachmentCreateInput!) {
286
286
  attachmentCreate(input: $input) {
287
287
  success
288
288
  attachment { id url title }
289
289
  }
290
290
  }
291
- `,{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(e){return JSON.stringify({error:e.message})}},tools:[{name:"linear_list_teams",description:"List Linear teams (id, key, name). Needed to scope workflow states and issue queries.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Max teams (default: 50)"}}}},{name:"linear_list_states",description:"List a team's workflow states (id, name, type: backlog|unstarted|started|completed|canceled|triage). Linear states are PER-TEAM. Omit team to list all states across the workspace.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved to an id if teamId omitted"},limit:{type:"number",description:"Max states when listing workspace-wide (default: 200)"}}}},{name:"linear_list_labels",description:"List issue labels, optionally scoped to a team.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Optional team uuid to scope labels"},limit:{type:"number",description:"Max labels (default: 100)"}}}},{name:"linear_list_issues",description:"List/poll Linear issues filtered by team, state, label, assignee, and an updatedAfter cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved if teamId omitted"},stateId:{type:"string",description:"Filter by workflow state uuid"},stateName:{type:"string",description:"Filter by state name (case-insensitive)"},label:{type:"string",description:"Filter by label name (case-insensitive)"},assigneeId:{type:"string",description:"Filter by assignee uuid"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},limit:{type:"number",description:"Max issues (default: 30)"}}}},{name:"linear_get_issue",description:"Get a single Linear issue by identifier (e.g. ENG-123) or internal uuid \u2014 title, description, state, labels, assignee, url.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"}}}},{name:"linear_get_comments",description:"Get comments on a Linear issue (newest first).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},limit:{type:"number",description:"Max comments (default: 50)"}}}},{name:"linear_add_comment",description:"Add a comment to a Linear issue (markdown supported).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},body:{type:"string",description:"Comment body (markdown)"}},required:["body"]}},{name:"linear_update_state",description:"Move a Linear issue to a different workflow state. Pass a state NAME (toStatus/stateName) and the tool resolves it to the issue's team's matching state id (exact -> type-alias -> fuzzy), or pass stateId directly. Linear has no transitions \u2014 this sets the state.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},stateId:{type:"string",description:"Target workflow state uuid (skips name resolution)"},stateName:{type:"string",description:'Target state name (e.g. "In Progress", "Done")'},toStatus:{type:"string",description:"Alias for stateName"}}}},{name:"linear_link_attachment",description:"Attach a URL (e.g. a GitHub PR) to a Linear issue via native attachments. Use this for PR links; fall back to linear_add_comment if it fails.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},url:{type:"string",description:"The URL to attach (e.g. a PR link)"},title:{type:"string",description:"Attachment title (defaults to the URL)"},subtitle:{type:"string",description:"Optional attachment subtitle"}},required:["url"]}}]};async function En(r){return(await V(`
291
+ `,{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(e){return JSON.stringify({error:e.message})}},tools:[{name:"linear_list_teams",description:"List Linear teams (id, key, name). Needed to scope workflow states and issue queries.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Max teams (default: 50)"}}}},{name:"linear_list_states",description:"List a team's workflow states (id, name, type: backlog|unstarted|started|completed|canceled|triage). Linear states are PER-TEAM. Omit team to list all states across the workspace.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved to an id if teamId omitted"},limit:{type:"number",description:"Max states when listing workspace-wide (default: 200)"}}}},{name:"linear_list_labels",description:"List issue labels, optionally scoped to a team.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Optional team uuid to scope labels"},limit:{type:"number",description:"Max labels (default: 100)"}}}},{name:"linear_list_issues",description:"List/poll Linear issues filtered by team, state, label, assignee, and an updatedAfter cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved if teamId omitted"},stateId:{type:"string",description:"Filter by workflow state uuid"},stateName:{type:"string",description:"Filter by state name (case-insensitive)"},label:{type:"string",description:"Filter by label name (case-insensitive)"},assigneeId:{type:"string",description:"Filter by assignee uuid"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},limit:{type:"number",description:"Max issues (default: 30)"}}}},{name:"linear_get_issue",description:"Get a single Linear issue by identifier (e.g. ENG-123) or internal uuid \u2014 title, description, state, labels, assignee, url.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"}}}},{name:"linear_get_comments",description:"Get comments on a Linear issue (newest first).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},limit:{type:"number",description:"Max comments (default: 50)"}}}},{name:"linear_add_comment",description:"Add a comment to a Linear issue (markdown supported).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},body:{type:"string",description:"Comment body (markdown)"}},required:["body"]}},{name:"linear_update_state",description:"Move a Linear issue to a different workflow state. Pass a state NAME (toStatus/stateName) and the tool resolves it to the issue's team's matching state id (exact -> type-alias -> fuzzy), or pass stateId directly. Linear has no transitions \u2014 this sets the state.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},stateId:{type:"string",description:"Target workflow state uuid (skips name resolution)"},stateName:{type:"string",description:'Target state name (e.g. "In Progress", "Done")'},toStatus:{type:"string",description:"Alias for stateName"}}}},{name:"linear_link_attachment",description:"Attach a URL (e.g. a GitHub PR) to a Linear issue via native attachments. Use this for PR links; fall back to linear_add_comment if it fails.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},url:{type:"string",description:"The URL to attach (e.g. a PR link)"},title:{type:"string",description:"Attachment title (defaults to the URL)"},subtitle:{type:"string",description:"Optional attachment subtitle"}},required:["url"]}}]};async function Kn(r){return(await V(`
292
292
  query TeamByKey($filter: TeamFilter) {
293
293
  teams(first: 1, filter: $filter) { nodes { id key } }
294
294
  }
295
- `,{filter:{key:{eq:r}}}))?.teams?.nodes?.[0]?.id||null}async function Ve(r,t=Qa){let e=String(r).trim(),n=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(e);if(n){let s=n[1].toUpperCase(),o=Number(n[2]);return(await V(`
295
+ `,{filter:{key:{eq:r}}}))?.teams?.nodes?.[0]?.id||null}async function nt(r,t=Rc){let e=String(r).trim(),n=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(e);if(n){let s=n[1].toUpperCase(),o=Number(n[2]);return(await V(`
296
296
  query IssueByIdentifier($filter: IssueFilter) {
297
297
  issues(first: 1, filter: $filter) {
298
298
  nodes { ${t} }
@@ -302,12 +302,12 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
302
302
  query IssueById($id: String!) {
303
303
  issue(id: $id) { ${t} }
304
304
  }
305
- `,{id:e}))?.issue||null}import{existsSync as ec}from"fs";import{fileURLToPath as tc}from"url";import{dirname as rc,resolve as nc}from"path";import{resolveIntegrationToken as ic}from"@zibby/core/backend-client.js";function sc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=rc(tc(import.meta.url)),t=nc(r,"..","bin","mcp-skill.mjs");return ec(t)?t:null}function xn(r){return String(r||"").trim().replace(/\/+$/,"").replace(/\/api\/v1$/,"")}var Ue=null;async function Qe(){if(Ue)return Ue;let r=xn(process.env.VIKUNJA_URL),t=(process.env.VIKUNJA_TOKEN||"").trim();try{let e=await ic("vikunja"),n=String(e?.token||"").trim(),i=xn(e?.instanceUrl);if(n&&i)return Ue={origin:i,token:n},Ue;if(n&&!i)throw new Error("The connected Vikunja integration has no instance URL \u2014 reconnect it in Integrations \u2192 Vikunja.")}catch(e){if(!(r&&t))throw e}if(!(r&&t))throw new Error("No Vikunja credentials. Connect the board under Integrations \u2192 Vikunja (instance URL + an API token minted in the board's Settings \u2192 API Tokens).");return Ue={origin:r,token:t},Ue}async function $(r,t,e={}){let{origin:n,token:i}=await Qe(),s=`${n}/api/v1${t}`;if(e.query&&Object.keys(e.query).length){let c=new URLSearchParams;for(let[l,p]of Object.entries(e.query))p!=null&&p!==""&&c.set(l,String(p));let d=c.toString();d&&(s+=`?${d}`)}let o=await fetch(s,{method:r,headers:{Authorization:`Bearer ${i}`,...e.body?{"Content-Type":"application/json"}:{}},...e.body?{body:JSON.stringify(e.body)}:{}}),a=await o.text();if(!o.ok)throw new Error(`Vikunja ${r} ${t} \u2192 ${o.status}: ${a.slice(0,300)}`);if(!a)return null;try{return JSON.parse(a)}catch{return a}}function Pn(r){return typeof r!="string"||!r?"":r.replace(/<br\s*\/?>/gi,`
305
+ `,{id:e}))?.issue||null}import{existsSync as Ac}from"fs";import{fileURLToPath as Ec}from"url";import{dirname as xc,resolve as jc}from"path";import{resolveIntegrationToken as Lc}from"@zibby/core/backend-client.js";function $c(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=xc(Ec(import.meta.url)),t=jc(r,"..","bin","mcp-skill.mjs");return Ac(t)?t:null}function Hn(r){return String(r||"").trim().replace(/\/+$/,"").replace(/\/api\/v1$/,"")}var Me=null;async function st(){if(Me)return Me;let r=Hn(process.env.VIKUNJA_URL),t=(process.env.VIKUNJA_TOKEN||"").trim();try{let e=await Lc("vikunja"),n=String(e?.token||"").trim(),i=Hn(e?.instanceUrl);if(n&&i)return Me={origin:i,token:n},Me;if(n&&!i)throw new Error("The connected Vikunja integration has no instance URL \u2014 reconnect it in Integrations \u2192 Vikunja.")}catch(e){if(!(r&&t))throw e}if(!(r&&t))throw new Error("No Vikunja credentials. Connect the board under Integrations \u2192 Vikunja (instance URL + an API token minted in the board's Settings \u2192 API Tokens).");return Me={origin:r,token:t},Me}async function $(r,t,e={}){let{origin:n,token:i}=await st(),s=`${n}/api/v1${t}`;if(e.query&&Object.keys(e.query).length){let c=new URLSearchParams;for(let[d,p]of Object.entries(e.query))p!=null&&p!==""&&c.set(d,String(p));let l=c.toString();l&&(s+=`?${l}`)}let o=await fetch(s,{method:r,headers:{Authorization:`Bearer ${i}`,...e.body?{"Content-Type":"application/json"}:{}},...e.body?{body:JSON.stringify(e.body)}:{}}),a=await o.text();if(!o.ok)throw new Error(`Vikunja ${r} ${t} \u2192 ${o.status}: ${a.slice(0,300)}`);if(!a)return null;try{return JSON.parse(a)}catch{return a}}function Wn(r){return typeof r!="string"||!r?"":r.replace(/<br\s*\/?>/gi,`
306
306
  `).replace(/<\/p>/gi,`
307
307
 
308
308
  `).replace(/<[^>]+>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/\n{3,}/g,`
309
309
 
310
- `).trim()}function Ln(r){if(r==null||r==="")return null;if(typeof r=="number"&&Number.isFinite(r))return Math.max(0,Math.min(5,Math.round(r)));let t=String(r).trim().toLowerCase(),e={unset:0,none:0,low:1,medium:2,normal:2,high:3,urgent:4,now:5,critical:5,blocker:5,do_now:5,"do now":5};return Object.prototype.hasOwnProperty.call(e,t)?e[t]:null}function Et(r,t){return r?{id:String(r.id),identifier:r.identifier||null,projectId:r.project_id??null,title:r.title||"",description:Pn(r.description),done:!!r.done,priority:r.priority??0,labels:(Array.isArray(r.labels)?r.labels:[]).map(e=>e?.title).filter(Boolean),assignees:(Array.isArray(r.assignees)?r.assignees:[]).map(e=>e?.username).filter(Boolean),dueDate:r.due_date&&!String(r.due_date).startsWith("0001-")?r.due_date:null,url:t?`${t}/tasks/${r.id}`:void 0}:null}async function jt(r,{create:t=!1}={}){let e=String(r||"").trim();if(!e)return null;let n=await $("GET","/labels",{query:{s:e}}),i=(Array.isArray(n)?n:[]).find(o=>(o?.title||"").trim().toLowerCase()===e.toLowerCase());return i?.id?i.id:t?(await $("PUT","/labels",{body:{title:e}}))?.id??null:null}async function $n(r){let t=encodeURIComponent(String(r)),e=await $("GET",`/projects/${t}/views`),n=(Array.isArray(e)?e:[]).find(s=>s?.view_kind==="kanban");if(!n?.id)throw new Error(`Project ${r} has no kanban view \u2014 there are no columns to move between.`);let i=await $("GET",`/projects/${t}/views/${n.id}/buckets`);return{viewId:n.id,buckets:Array.isArray(i)?i:[]}}var Cn={id:"vikunja",serverName:"vikunja",allowedTools:["mcp__vikunja__*"],requiresIntegration:I.VIKUNJA,callsBackend:!0,envKeys:["VIKUNJA_URL","VIKUNJA_TOKEN"],description:"Vikunja \u2014 kanban board: tasks, columns, labels, comments (API token)",promptFragment:`## Vikunja
310
+ `).trim()}function zn(r){if(r==null||r==="")return null;if(typeof r=="number"&&Number.isFinite(r))return Math.max(0,Math.min(5,Math.round(r)));let t=String(r).trim().toLowerCase(),e={unset:0,none:0,low:1,medium:2,normal:2,high:3,urgent:4,now:5,critical:5,blocker:5,do_now:5,"do now":5};return Object.prototype.hasOwnProperty.call(e,t)?e[t]:null}function Jt(r,t){return r?{id:String(r.id),identifier:r.identifier||null,projectId:r.project_id??null,title:r.title||"",description:Wn(r.description),done:!!r.done,priority:r.priority??0,labels:(Array.isArray(r.labels)?r.labels:[]).map(e=>e?.title).filter(Boolean),assignees:(Array.isArray(r.assignees)?r.assignees:[]).map(e=>e?.username).filter(Boolean),dueDate:r.due_date&&!String(r.due_date).startsWith("0001-")?r.due_date:null,url:t?`${t}/tasks/${r.id}`:void 0}:null}async function Dt(r,{create:t=!1}={}){let e=String(r||"").trim();if(!e)return null;let n=await $("GET","/labels",{query:{s:e}}),i=(Array.isArray(n)?n:[]).find(o=>(o?.title||"").trim().toLowerCase()===e.toLowerCase());return i?.id?i.id:t?(await $("PUT","/labels",{body:{title:e}}))?.id??null:null}async function Yn(r){let t=encodeURIComponent(String(r)),e=await $("GET",`/projects/${t}/views`),n=(Array.isArray(e)?e:[]).find(s=>s?.view_kind==="kanban");if(!n?.id)throw new Error(`Project ${r} has no kanban view \u2014 there are no columns to move between.`);let i=await $("GET",`/projects/${t}/views/${n.id}/buckets`);return{viewId:n.id,buckets:Array.isArray(i)?i:[]}}var Zn={id:"vikunja",serverName:"vikunja",allowedTools:["mcp__vikunja__*"],requiresIntegration:I.VIKUNJA,callsBackend:!0,envKeys:["VIKUNJA_URL","VIKUNJA_TOKEN"],description:"Vikunja \u2014 kanban board: tasks, columns, labels, comments (API token)",promptFragment:`## Vikunja
311
311
  You can operate the user's Vikunja board directly. Tools:
312
312
 
313
313
  ### Discovery
@@ -328,13 +328,13 @@ You can operate the user's Vikunja board directly. Tools:
328
328
  ### Notes
329
329
  - Address tasks by their NUMERIC id. The '#1' identifier shown in the UI is per-project and not unique.
330
330
  - Descriptions may come back as plain text converted from HTML \u2014 that is expected.
331
- - Priority accepts a number 0-5 or a word: low, medium, high, urgent, now.`,resolve(){let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);let t=sc();return t?{type:"stdio",command:"node",args:[t,"../dist/vikunja.js","vikunjaSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,t){try{let e=t||{};switch(r){case"vikunja_list_projects":{let n=await $("GET","/projects"),i=(Array.isArray(n)?n:[]).map(s=>({id:String(s.id),title:s.title||"",description:Pn(s.description)}));return JSON.stringify({count:i.length,projects:i})}case"vikunja_list_buckets":{let{viewId:n,buckets:i}=await $n(e.projectId);return JSON.stringify({viewId:n,count:i.length,buckets:i.map(s=>({id:s.id,title:s.title,taskCount:s.count??null}))})}case"vikunja_list_labels":{let n=await $("GET","/labels",{query:{s:e.search}}),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,title:s.title}));return JSON.stringify({count:i.length,labels:i})}case"vikunja_list_tasks":{let{origin:n}=await Qe(),i=[];if(e.label){let a=await jt(e.label);if(!a)return JSON.stringify({count:0,tasks:[],note:`No label named "${e.label}" exists.`});i.push(`labels in ${a}`)}(e.done===!0||e.done===!1)&&i.push(`done = ${e.done}`);let s=await $("GET",`/projects/${encodeURIComponent(String(e.projectId))}/tasks`,{query:{...i.length?{filter:i.join(" && ")}:{},sort_by:"updated",order_by:"desc",per_page:Math.min(Number(e.limit)||25,50)}}),o=(Array.isArray(s)?s:[]).map(a=>Et(a,n));return JSON.stringify({count:o.length,tasks:o})}case"vikunja_get_task":{let{origin:n}=await Qe(),i=await $("GET",`/tasks/${encodeURIComponent(String(e.taskId))}`);return JSON.stringify({task:Et(i,n)})}case"vikunja_create_task":{let{origin:n}=await Qe(),i=Ln(e.priority),s=await $("PUT",`/projects/${encodeURIComponent(String(e.projectId))}/tasks`,{body:{title:e.title,...e.description?{description:e.description}:{},...i!==null?{priority:i}:{},...e.dueDate?{due_date:e.dueDate}:{}}});if(!s?.id)throw new Error("Vikunja created no task (no id in the response)");let o=[];for(let c of Array.isArray(e.labels)?e.labels:[])try{let d=await jt(c,{create:!0});d&&await $("PUT",`/tasks/${s.id}/labels`,{body:{label_id:d}})}catch(d){o.push(`${c}: ${d?.message||d}`)}let a=await $("GET",`/tasks/${s.id}`);return JSON.stringify({created:Et(a||s,n),...o.length?{labelErrors:o}:{}})}case"vikunja_update_task":{let{origin:n}=await Qe(),i=encodeURIComponent(String(e.taskId)),s=await $("GET",`/tasks/${i}`);if(!s?.id)throw new Error(`No task ${e.taskId}`);let o=Ln(e.priority),a=await $("POST",`/tasks/${i}`,{body:{...s,...e.title!==void 0?{title:e.title}:{},...e.description!==void 0?{description:e.description}:{},...o!==null?{priority:o}:{},...e.done!==void 0?{done:!!e.done}:{},...e.dueDate!==void 0?{due_date:e.dueDate}:{}}});return JSON.stringify({updated:Et(a,n)})}case"vikunja_move_task":{let n=await $("GET",`/tasks/${encodeURIComponent(String(e.taskId))}`);if(!n?.id)throw new Error(`No task ${e.taskId}`);let i=e.projectId??n.project_id,s=String(e.column||"").trim().toLowerCase();if(!s)throw new Error("No target column given.");let{viewId:o,buckets:a}=await $n(i),c=a.find(d=>(d?.title||"").trim().toLowerCase()===s);return c?.id?(await $("POST",`/projects/${encodeURIComponent(String(i))}/views/${o}/buckets/${c.id}/tasks`,{body:{task_id:Number(n.id)}}),JSON.stringify({moved:!0,taskId:String(n.id),column:c.title})):JSON.stringify({moved:!1,error:`No column named "${e.column}".`,availableColumns:a.map(d=>d.title)})}case"vikunja_add_label":{let n=await jt(e.label,{create:e.create!==!1});return n?(await $("PUT",`/tasks/${encodeURIComponent(String(e.taskId))}/labels`,{body:{label_id:n}}),JSON.stringify({ok:!0,taskId:String(e.taskId),label:e.label})):JSON.stringify({ok:!1,error:`No label named "${e.label}" and creating it was declined.`})}case"vikunja_remove_label":{let n=await jt(e.label);return n?(await $("DELETE",`/tasks/${encodeURIComponent(String(e.taskId))}/labels/${n}`),JSON.stringify({ok:!0,taskId:String(e.taskId),label:e.label})):JSON.stringify({ok:!1,error:`No label named "${e.label}".`})}case"vikunja_add_comment":{let n=await $("PUT",`/tasks/${encodeURIComponent(String(e.taskId))}/comments`,{body:{comment:e.comment}});return JSON.stringify({ok:!0,commentId:n?.id??null})}case"vikunja_assign":{let n=await $("GET","/users",{query:{s:e.username}}),i=(Array.isArray(n)?n:[]).find(s=>(s?.username||"").toLowerCase()===String(e.username||"").toLowerCase());return i?.id?(await $("PUT",`/tasks/${encodeURIComponent(String(e.taskId))}/assignees`,{body:{user_id:i.id}}),JSON.stringify({ok:!0,taskId:String(e.taskId),assignee:i.username})):JSON.stringify({ok:!1,error:`No user "${e.username}".`})}default:return JSON.stringify({error:`Unknown vikunja tool: ${r}`})}}catch(e){return JSON.stringify({error:e?.message||String(e)})}},tools:[{name:"vikunja_list_projects",description:"List Vikunja projects/boards (id, title). Everything else is project-scoped \u2014 start here when you do not already have a project id.",input_schema:{type:"object",properties:{}}},{name:"vikunja_list_buckets",description:"List a project's kanban COLUMNS (bucket id + title). Call this before moving a card so you use a column that exists.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project id"}},required:["projectId"]}},{name:"vikunja_list_labels",description:"List labels (id, title). Optionally narrow with a search string.",input_schema:{type:"object",properties:{search:{type:"string",description:"Optional server-side search on the label title"}}}},{name:"vikunja_list_tasks",description:"List a project's tasks, newest-updated first. Optionally filter by label title and/or done-state.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project id"},label:{type:"string",description:"Only tasks carrying this label title"},done:{type:"boolean",description:"Filter on completion state"},limit:{type:"number",description:"Max tasks (default 25, max 50)"}},required:["projectId"]}},{name:"vikunja_get_task",description:'Get one task by its NUMERIC id (the "#1" identifier shown in the UI is per-project and not unique).',input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"}},required:["taskId"]}},{name:"vikunja_create_task",description:"Create a task in a project. Labels are attached after creation and fail soft \u2014 the task survives a label error.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project id"},title:{type:"string",description:"Task title"},description:{type:"string",description:"Task body"},priority:{type:"string",description:"A number 0-5 or a word: low, medium, high, urgent, now"},labels:{type:"array",items:{type:"string"},description:"Label titles; created if missing"},dueDate:{type:"string",description:"RFC3339 timestamp"}},required:["projectId","title"]}},{name:"vikunja_update_task",description:"Change a task's title, description, priority, due date, or done state. To move it to another COLUMN use vikunja_move_task \u2014 a column is not a field on the task.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},title:{type:"string"},description:{type:"string"},priority:{type:"string",description:"A number 0-5 or a word: low, medium, high, urgent, now"},done:{type:"boolean"},dueDate:{type:"string",description:"RFC3339 timestamp"}},required:["taskId"]}},{name:"vikunja_move_task",description:`Move a card to a kanban COLUMN by name (e.g. "Doing"). Vikunja has no task.status: a column is a bucket on the project's kanban view, so this resolves the view and puts the task in the matching bucket. Returns the available column names when the name does not match.`,input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},column:{type:"string",description:"Target column (bucket) title"},projectId:{type:"string",description:"Optional; defaults to the task's own project"}},required:["taskId","column"]}},{name:"vikunja_add_label",description:"Attach a label to a task by title. Creates the label when it does not exist (pass create=false to refuse instead).",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},label:{type:"string",description:"Label title"},create:{type:"boolean",description:"Create the label if missing (default true)"}},required:["taskId","label"]}},{name:"vikunja_remove_label",description:"Detach a label from a task by title.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},label:{type:"string",description:"Label title"}},required:["taskId","label"]}},{name:"vikunja_add_comment",description:"Add a comment to a task.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},comment:{type:"string",description:"Comment body"}},required:["taskId","comment"]}},{name:"vikunja_assign",description:"Assign a user to a task by username.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},username:{type:"string",description:"Vikunja username"}},required:["taskId","username"]}}]};var Un={id:"plane",serverName:"plane",allowedTools:["mcp__plane__*"],requiresIntegration:I.PLANE,envKeys:["PLANE_API_KEY","PLANE_WORKSPACE_SLUG","PLANE_BASE_URL"],description:"Plane \u2014 projects, work items, cycles, modules, epics, comments (official MCP, API key)",tools:[],promptFragment:`## Plane
331
+ - Priority accepts a number 0-5 or a word: low, medium, high, urgent, now.`,resolve(){let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);let t=$c();return t?{type:"stdio",command:"node",args:[t,"../dist/vikunja.js","vikunjaSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,t){try{let e=t||{};switch(r){case"vikunja_list_projects":{let n=await $("GET","/projects"),i=(Array.isArray(n)?n:[]).map(s=>({id:String(s.id),title:s.title||"",description:Wn(s.description)}));return JSON.stringify({count:i.length,projects:i})}case"vikunja_list_buckets":{let{viewId:n,buckets:i}=await Yn(e.projectId);return JSON.stringify({viewId:n,count:i.length,buckets:i.map(s=>({id:s.id,title:s.title,taskCount:s.count??null}))})}case"vikunja_list_labels":{let n=await $("GET","/labels",{query:{s:e.search}}),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,title:s.title}));return JSON.stringify({count:i.length,labels:i})}case"vikunja_list_tasks":{let{origin:n}=await st(),i=[];if(e.label){let a=await Dt(e.label);if(!a)return JSON.stringify({count:0,tasks:[],note:`No label named "${e.label}" exists.`});i.push(`labels in ${a}`)}(e.done===!0||e.done===!1)&&i.push(`done = ${e.done}`);let s=await $("GET",`/projects/${encodeURIComponent(String(e.projectId))}/tasks`,{query:{...i.length?{filter:i.join(" && ")}:{},sort_by:"updated",order_by:"desc",per_page:Math.min(Number(e.limit)||25,50)}}),o=(Array.isArray(s)?s:[]).map(a=>Jt(a,n));return JSON.stringify({count:o.length,tasks:o})}case"vikunja_get_task":{let{origin:n}=await st(),i=await $("GET",`/tasks/${encodeURIComponent(String(e.taskId))}`);return JSON.stringify({task:Jt(i,n)})}case"vikunja_create_task":{let{origin:n}=await st(),i=zn(e.priority),s=await $("PUT",`/projects/${encodeURIComponent(String(e.projectId))}/tasks`,{body:{title:e.title,...e.description?{description:e.description}:{},...i!==null?{priority:i}:{},...e.dueDate?{due_date:e.dueDate}:{}}});if(!s?.id)throw new Error("Vikunja created no task (no id in the response)");let o=[];for(let c of Array.isArray(e.labels)?e.labels:[])try{let l=await Dt(c,{create:!0});l&&await $("PUT",`/tasks/${s.id}/labels`,{body:{label_id:l}})}catch(l){o.push(`${c}: ${l?.message||l}`)}let a=await $("GET",`/tasks/${s.id}`);return JSON.stringify({created:Jt(a||s,n),...o.length?{labelErrors:o}:{}})}case"vikunja_update_task":{let{origin:n}=await st(),i=encodeURIComponent(String(e.taskId)),s=await $("GET",`/tasks/${i}`);if(!s?.id)throw new Error(`No task ${e.taskId}`);let o=zn(e.priority),a=await $("POST",`/tasks/${i}`,{body:{...s,...e.title!==void 0?{title:e.title}:{},...e.description!==void 0?{description:e.description}:{},...o!==null?{priority:o}:{},...e.done!==void 0?{done:!!e.done}:{},...e.dueDate!==void 0?{due_date:e.dueDate}:{}}});return JSON.stringify({updated:Jt(a,n)})}case"vikunja_move_task":{let n=await $("GET",`/tasks/${encodeURIComponent(String(e.taskId))}`);if(!n?.id)throw new Error(`No task ${e.taskId}`);let i=e.projectId??n.project_id,s=String(e.column||"").trim().toLowerCase();if(!s)throw new Error("No target column given.");let{viewId:o,buckets:a}=await Yn(i),c=a.find(l=>(l?.title||"").trim().toLowerCase()===s);return c?.id?(await $("POST",`/projects/${encodeURIComponent(String(i))}/views/${o}/buckets/${c.id}/tasks`,{body:{task_id:Number(n.id)}}),JSON.stringify({moved:!0,taskId:String(n.id),column:c.title})):JSON.stringify({moved:!1,error:`No column named "${e.column}".`,availableColumns:a.map(l=>l.title)})}case"vikunja_add_label":{let n=await Dt(e.label,{create:e.create!==!1});return n?(await $("PUT",`/tasks/${encodeURIComponent(String(e.taskId))}/labels`,{body:{label_id:n}}),JSON.stringify({ok:!0,taskId:String(e.taskId),label:e.label})):JSON.stringify({ok:!1,error:`No label named "${e.label}" and creating it was declined.`})}case"vikunja_remove_label":{let n=await Dt(e.label);return n?(await $("DELETE",`/tasks/${encodeURIComponent(String(e.taskId))}/labels/${n}`),JSON.stringify({ok:!0,taskId:String(e.taskId),label:e.label})):JSON.stringify({ok:!1,error:`No label named "${e.label}".`})}case"vikunja_add_comment":{let n=await $("PUT",`/tasks/${encodeURIComponent(String(e.taskId))}/comments`,{body:{comment:e.comment}});return JSON.stringify({ok:!0,commentId:n?.id??null})}case"vikunja_assign":{let n=await $("GET","/users",{query:{s:e.username}}),i=(Array.isArray(n)?n:[]).find(s=>(s?.username||"").toLowerCase()===String(e.username||"").toLowerCase());return i?.id?(await $("PUT",`/tasks/${encodeURIComponent(String(e.taskId))}/assignees`,{body:{user_id:i.id}}),JSON.stringify({ok:!0,taskId:String(e.taskId),assignee:i.username})):JSON.stringify({ok:!1,error:`No user "${e.username}".`})}default:return JSON.stringify({error:`Unknown vikunja tool: ${r}`})}}catch(e){return JSON.stringify({error:e?.message||String(e)})}},tools:[{name:"vikunja_list_projects",description:"List Vikunja projects/boards (id, title). Everything else is project-scoped \u2014 start here when you do not already have a project id.",input_schema:{type:"object",properties:{}}},{name:"vikunja_list_buckets",description:"List a project's kanban COLUMNS (bucket id + title). Call this before moving a card so you use a column that exists.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project id"}},required:["projectId"]}},{name:"vikunja_list_labels",description:"List labels (id, title). Optionally narrow with a search string.",input_schema:{type:"object",properties:{search:{type:"string",description:"Optional server-side search on the label title"}}}},{name:"vikunja_list_tasks",description:"List a project's tasks, newest-updated first. Optionally filter by label title and/or done-state.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project id"},label:{type:"string",description:"Only tasks carrying this label title"},done:{type:"boolean",description:"Filter on completion state"},limit:{type:"number",description:"Max tasks (default 25, max 50)"}},required:["projectId"]}},{name:"vikunja_get_task",description:'Get one task by its NUMERIC id (the "#1" identifier shown in the UI is per-project and not unique).',input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"}},required:["taskId"]}},{name:"vikunja_create_task",description:"Create a task in a project. Labels are attached after creation and fail soft \u2014 the task survives a label error.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project id"},title:{type:"string",description:"Task title"},description:{type:"string",description:"Task body"},priority:{type:"string",description:"A number 0-5 or a word: low, medium, high, urgent, now"},labels:{type:"array",items:{type:"string"},description:"Label titles; created if missing"},dueDate:{type:"string",description:"RFC3339 timestamp"}},required:["projectId","title"]}},{name:"vikunja_update_task",description:"Change a task's title, description, priority, due date, or done state. To move it to another COLUMN use vikunja_move_task \u2014 a column is not a field on the task.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},title:{type:"string"},description:{type:"string"},priority:{type:"string",description:"A number 0-5 or a word: low, medium, high, urgent, now"},done:{type:"boolean"},dueDate:{type:"string",description:"RFC3339 timestamp"}},required:["taskId"]}},{name:"vikunja_move_task",description:`Move a card to a kanban COLUMN by name (e.g. "Doing"). Vikunja has no task.status: a column is a bucket on the project's kanban view, so this resolves the view and puts the task in the matching bucket. Returns the available column names when the name does not match.`,input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},column:{type:"string",description:"Target column (bucket) title"},projectId:{type:"string",description:"Optional; defaults to the task's own project"}},required:["taskId","column"]}},{name:"vikunja_add_label",description:"Attach a label to a task by title. Creates the label when it does not exist (pass create=false to refuse instead).",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},label:{type:"string",description:"Label title"},create:{type:"boolean",description:"Create the label if missing (default true)"}},required:["taskId","label"]}},{name:"vikunja_remove_label",description:"Detach a label from a task by title.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},label:{type:"string",description:"Label title"}},required:["taskId","label"]}},{name:"vikunja_add_comment",description:"Add a comment to a task.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},comment:{type:"string",description:"Comment body"}},required:["taskId","comment"]}},{name:"vikunja_assign",description:"Assign a user to a task by username.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},username:{type:"string",description:"Vikunja username"}},required:["taskId","username"]}}]};var Vn={id:"plane",serverName:"plane",allowedTools:["mcp__plane__*"],requiresIntegration:I.PLANE,envKeys:["PLANE_API_KEY","PLANE_WORKSPACE_SLUG","PLANE_BASE_URL"],description:"Plane \u2014 projects, work items, cycles, modules, epics, comments (official MCP, API key)",tools:[],promptFragment:`## Plane
332
332
  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.
333
333
 
334
334
  - List/get projects and work items, then create/update/delete or search work items as needed.
335
335
  - For status changes, read the project's available states first, then set the work item's state.
336
336
  - Cycles and modules group work items \u2014 list them to scope queries before drilling into items.
337
- - 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 t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);return{type:"stdio",command:"uvx",args:["plane-mcp-server","stdio"],env:r,description:this.description}}};import{existsSync as oc}from"fs";import{fileURLToPath as ac}from"url";import{dirname as cc,resolve as lc}from"path";import{resolveIntegrationToken as dc}from"@zibby/core/backend-client.js";function pc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=cc(ac(import.meta.url)),t=lc(r,"..","bin","mcp-skill.mjs");return oc(t)?t:null}async function Bn(){let r=await dc(I.OPEN_DESIGN),t=r?.token,e=r?.baseUrl;if(!t||typeof t!="string")throw new Error("OpenDesign is not connected: missing token. Connect it in Integrations.");if(!e||typeof e!="string")throw new Error("OpenDesign is not connected: missing baseUrl. Connect it in Integrations.");let n=e.replace(/\/+$/,"");return{token:t,baseUrl:n}}async function ye(r,t={}){let{token:e,baseUrl:n}=await Bn(),i=`${n}/api${r}`;if(t.query&&typeof t.query=="object"){let a=new URLSearchParams;for(let[d,l]of Object.entries(t.query))l!=null&&l!==""&&a.set(d,String(l));let c=a.toString();c&&(i+=(i.includes("?")?"&":"?")+c)}let s={Authorization:`Bearer ${e}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},o=await fetch(i,{method:t.method||"GET",headers:s,body:t.body?JSON.stringify(t.body):void 0});return Jn(o,"OpenDesign")}async function Jn(r,t){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(`${t} API ${r.status}: ${i}`)}let e=await r.text().catch(()=>"");if(!e)return{};try{return JSON.parse(e)}catch{return{raw:e}}}var qn={id:"open-design",callsBackend:!0,serverName:"opendesign",allowedTools:["mcp__opendesign__*"],envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"OpenDesign \u2014 list projects/designs, run the design agent, and export decks to PDF/HTML",promptFragment:`## OpenDesign (optional)
337
+ - 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 t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);return{type:"stdio",command:"uvx",args:["plane-mcp-server","stdio"],env:r,description:this.description}}};import{existsSync as Pc}from"fs";import{fileURLToPath as Cc}from"url";import{dirname as Uc,resolve as Bc}from"path";import{resolveIntegrationToken as Jc}from"@zibby/core/backend-client.js";function Dc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Uc(Cc(import.meta.url)),t=Bc(r,"..","bin","mcp-skill.mjs");return Pc(t)?t:null}async function Xn(){let r=await Jc(I.OPEN_DESIGN),t=r?.token,e=r?.baseUrl;if(!t||typeof t!="string")throw new Error("OpenDesign is not connected: missing token. Connect it in Integrations.");if(!e||typeof e!="string")throw new Error("OpenDesign is not connected: missing baseUrl. Connect it in Integrations.");let n=e.replace(/\/+$/,"");return{token:t,baseUrl:n}}async function we(r,t={}){let{token:e,baseUrl:n}=await Xn(),i=`${n}/api${r}`;if(t.query&&typeof t.query=="object"){let a=new URLSearchParams;for(let[l,d]of Object.entries(t.query))d!=null&&d!==""&&a.set(l,String(d));let c=a.toString();c&&(i+=(i.includes("?")?"&":"?")+c)}let s={Authorization:`Bearer ${e}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},o=await fetch(i,{method:t.method||"GET",headers:s,body:t.body?JSON.stringify(t.body):void 0});return Qn(o,"OpenDesign")}async function Qn(r,t){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(`${t} API ${r.status}: ${i}`)}let e=await r.text().catch(()=>"");if(!e)return{};try{return JSON.parse(e)}catch{return{raw:e}}}var ei={id:"open-design",callsBackend:!0,serverName:"opendesign",allowedTools:["mcp__opendesign__*"],envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"OpenDesign \u2014 list projects/designs, run the design agent, and export decks to PDF/HTML",promptFragment:`## OpenDesign (optional)
338
338
  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__*):
339
339
 
340
340
  ### Connectivity
@@ -356,30 +356,30 @@ You may have access to the user's OpenDesign workspace (the Zibby-managed design
356
356
 
357
357
  ### Notes
358
358
  - A design artifact lookup ALWAYS needs its projectId (it scopes the query).
359
- - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let r=pc();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/opendesign.js","opendesignSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"opendesign_health":{let{baseUrl:e}=await Bn(),n=await fetch(`${e}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),i=await Jn(n,"OpenDesign");return JSON.stringify({ok:!0,health:i})}case"opendesign_list_projects":{let e=await ye("/projects");return JSON.stringify(e)}case"opendesign_get_project":{let e=t?.id||t?.projectId;if(!e)return JSON.stringify({error:"id is required"});let n=await ye(`/projects/${encodeURIComponent(e)}`);return JSON.stringify(n)}case"opendesign_list_designs":{let e=t?.projectId;if(!e)return JSON.stringify({error:"projectId is required"});let n=await ye("/live-artifacts",{query:{projectId:e}});return JSON.stringify(n)}case"opendesign_get_design":{let e=t?.id,n=t?.projectId;if(!e)return JSON.stringify({error:"id is required"});if(!n)return JSON.stringify({error:"projectId is required"});let i=await ye(`/live-artifacts/${encodeURIComponent(e)}`,{query:{projectId:n}});return JSON.stringify(i)}case"opendesign_export_pdf":{let e=t?.projectId||t?.id,{fileName:n,title:i,deck:s}=t||{};if(!e)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 ye(`/projects/${encodeURIComponent(e)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(a)}case"opendesign_export_html":{let e=t?.projectId||t?.id,n=t?.path;if(!e)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 ye(`/projects/${encodeURIComponent(e)}/export/${s}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:e,message:n,projectId:i,conversationId:s,model:o}=t||{};if(!e)return JSON.stringify({error:"agentId is required"});if(!n)return JSON.stringify({error:"message is required"});let a={agentId:e,message:n};i!==void 0&&(a.projectId=i),s!==void 0&&(a.conversationId=s),o!==void 0&&(a.model=o);let c=await ye("/runs",{method:"POST",body:a});return JSON.stringify(c)}case"opendesign_cli_status":{let e=t?.id||t?.runId;if(!e)return JSON.stringify({error:"id (runId) is required"});let n=await ye(`/runs/${encodeURIComponent(e)}`);return JSON.stringify(n)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"opendesign_health",description:"Probe the OpenDesign instance (GET /api/health, no auth). Use to confirm connectivity before other calls.",input_schema:{type:"object",properties:{}}},{name:"opendesign_list_projects",description:"List the projects in the OpenDesign workspace.",input_schema:{type:"object",properties:{}}},{name:"opendesign_get_project",description:"Get a single OpenDesign project by id.",input_schema:{type:"object",properties:{id:{type:"string",description:"The project id."}},required:["id"]}},{name:"opendesign_list_designs",description:"List the live design artifacts in an OpenDesign project. Requires the projectId, which scopes the query.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id whose designs to list."}},required:["projectId"]}},{name:"opendesign_get_design",description:"Get a single live design artifact by id. Requires both the design id and its projectId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The live-artifact (design) id."},projectId:{type:"string",description:"The project id the design belongs to (scopes the lookup)."}},required:["id","projectId"]}},{name:"opendesign_export_pdf",description:"Export an OpenDesign project deck to PDF. Returns the export result (e.g. a download URL/path).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},fileName:{type:"string",description:"The output PDF file name."},title:{type:"string",description:"Optional deck title for the PDF."},deck:{description:"Optional deck payload/override to render instead of the project's current deck."}},required:["projectId","fileName"]}},{name:"opendesign_export_html",description:"Fetch an OpenDesign project's HTML export by sub-path (requested inline). Requires projectId and the export path.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},path:{type:"string",description:'The export sub-path under /projects/:id/export/ (e.g. "index.html" or a slide path).'}},required:["projectId","path"]}},{name:"opendesign_cli_run",description:"Start an OpenDesign agent run. Returns a runId; poll opendesign_cli_status with it until the run finishes.",input_schema:{type:"object",properties:{agentId:{type:"string",description:"The OpenDesign agent id to run."},message:{type:"string",description:"The instruction/message to send to the agent."},projectId:{type:"string",description:"Optional project id to scope the run to."},conversationId:{type:"string",description:"Optional conversation id to continue an existing thread."},model:{type:"string",description:"Optional model id override for the run."}},required:["agentId","message"]}},{name:"opendesign_cli_status",description:"Poll the status of an OpenDesign agent run by its runId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The runId returned by opendesign_cli_run."}},required:["id"]}}]};import{existsSync as uc}from"fs";import{fileURLToPath as mc}from"url";import{dirname as fc,resolve as hc}from"path";import{resolveIntegrationToken as yc}from"@zibby/core/backend-client.js";function gc(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let r=fc(mc(import.meta.url)),t=hc(r,"..","bin","mcp-slack.mjs");return uc(t)?t:null}async function H(r,t={}){let{token:e}=await yc("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 ${e}`},o;if(n){let d=new URLSearchParams(t).toString();d&&(i+=`?${d}`)}else s["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(t);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",callsBackend:!0,serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:I.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack
359
+ - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let r=Dc();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/opendesign.js","opendesignSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"opendesign_health":{let{baseUrl:e}=await Xn(),n=await fetch(`${e}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),i=await Qn(n,"OpenDesign");return JSON.stringify({ok:!0,health:i})}case"opendesign_list_projects":{let e=await we("/projects");return JSON.stringify(e)}case"opendesign_get_project":{let e=t?.id||t?.projectId;if(!e)return JSON.stringify({error:"id is required"});let n=await we(`/projects/${encodeURIComponent(e)}`);return JSON.stringify(n)}case"opendesign_list_designs":{let e=t?.projectId;if(!e)return JSON.stringify({error:"projectId is required"});let n=await we("/live-artifacts",{query:{projectId:e}});return JSON.stringify(n)}case"opendesign_get_design":{let e=t?.id,n=t?.projectId;if(!e)return JSON.stringify({error:"id is required"});if(!n)return JSON.stringify({error:"projectId is required"});let i=await we(`/live-artifacts/${encodeURIComponent(e)}`,{query:{projectId:n}});return JSON.stringify(i)}case"opendesign_export_pdf":{let e=t?.projectId||t?.id,{fileName:n,title:i,deck:s}=t||{};if(!e)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 we(`/projects/${encodeURIComponent(e)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(a)}case"opendesign_export_html":{let e=t?.projectId||t?.id,n=t?.path;if(!e)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 we(`/projects/${encodeURIComponent(e)}/export/${s}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:e,message:n,projectId:i,conversationId:s,model:o}=t||{};if(!e)return JSON.stringify({error:"agentId is required"});if(!n)return JSON.stringify({error:"message is required"});let a={agentId:e,message:n};i!==void 0&&(a.projectId=i),s!==void 0&&(a.conversationId=s),o!==void 0&&(a.model=o);let c=await we("/runs",{method:"POST",body:a});return JSON.stringify(c)}case"opendesign_cli_status":{let e=t?.id||t?.runId;if(!e)return JSON.stringify({error:"id (runId) is required"});let n=await we(`/runs/${encodeURIComponent(e)}`);return JSON.stringify(n)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"opendesign_health",description:"Probe the OpenDesign instance (GET /api/health, no auth). Use to confirm connectivity before other calls.",input_schema:{type:"object",properties:{}}},{name:"opendesign_list_projects",description:"List the projects in the OpenDesign workspace.",input_schema:{type:"object",properties:{}}},{name:"opendesign_get_project",description:"Get a single OpenDesign project by id.",input_schema:{type:"object",properties:{id:{type:"string",description:"The project id."}},required:["id"]}},{name:"opendesign_list_designs",description:"List the live design artifacts in an OpenDesign project. Requires the projectId, which scopes the query.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id whose designs to list."}},required:["projectId"]}},{name:"opendesign_get_design",description:"Get a single live design artifact by id. Requires both the design id and its projectId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The live-artifact (design) id."},projectId:{type:"string",description:"The project id the design belongs to (scopes the lookup)."}},required:["id","projectId"]}},{name:"opendesign_export_pdf",description:"Export an OpenDesign project deck to PDF. Returns the export result (e.g. a download URL/path).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},fileName:{type:"string",description:"The output PDF file name."},title:{type:"string",description:"Optional deck title for the PDF."},deck:{description:"Optional deck payload/override to render instead of the project's current deck."}},required:["projectId","fileName"]}},{name:"opendesign_export_html",description:"Fetch an OpenDesign project's HTML export by sub-path (requested inline). Requires projectId and the export path.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},path:{type:"string",description:'The export sub-path under /projects/:id/export/ (e.g. "index.html" or a slide path).'}},required:["projectId","path"]}},{name:"opendesign_cli_run",description:"Start an OpenDesign agent run. Returns a runId; poll opendesign_cli_status with it until the run finishes.",input_schema:{type:"object",properties:{agentId:{type:"string",description:"The OpenDesign agent id to run."},message:{type:"string",description:"The instruction/message to send to the agent."},projectId:{type:"string",description:"Optional project id to scope the run to."},conversationId:{type:"string",description:"Optional conversation id to continue an existing thread."},model:{type:"string",description:"Optional model id override for the run."}},required:["agentId","message"]}},{name:"opendesign_cli_status",description:"Poll the status of an OpenDesign agent run by its runId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The runId returned by opendesign_cli_run."}},required:["id"]}}]};import{existsSync as qc}from"fs";import{fileURLToPath as Mc}from"url";import{dirname as Fc,resolve as Kc}from"path";import{resolveIntegrationToken as Gc}from"@zibby/core/backend-client.js";function Hc(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let r=Fc(Mc(import.meta.url)),t=Kc(r,"..","bin","mcp-slack.mjs");return qc(t)?t:null}async function z(r,t={}){let{token:e}=await Gc("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 ${e}`},o;if(n){let l=new URLSearchParams(t).toString();l&&(i+=`?${l}`)}else s["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(t);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",callsBackend:!0,serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:I.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack
360
360
  You have access to the user's Slack workspace. Use these tools:
361
361
  - slack_list_channels, slack_post_message, slack_reply_to_thread
362
362
  - slack_add_reaction, slack_get_channel_history, slack_get_thread_replies
363
363
  - slack_get_users, slack_get_user_profile
364
364
  - slack_lookup_user_by_email (precise email\u2192user_id, prefer this over scanning slack_get_users)
365
- - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=gc();if(!r)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r],env:t,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"slack_list_channels":{let e=await H("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(e.channels||[]).map(n=>({id:n.id,name:n.name,topic:n.topic?.value}))})}case"slack_post_message":{if(!t.channel||!t.text)return JSON.stringify({error:"channel and text are required"});let e=await H("chat.postMessage",{channel:t.channel,text:t.text,...t.blocks?{blocks:t.blocks}:{}});return JSON.stringify({ok:!0,ts:e.ts,channel:e.channel})}case"slack_reply_to_thread":{if(!t.channel||!t.thread_ts||!t.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let e=await H("chat.postMessage",{channel:t.channel,thread_ts:t.thread_ts,text:t.text});return JSON.stringify({ok:!0,ts:e.ts})}case"slack_add_reaction":return!t.channel||!t.timestamp||!t.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await H("reactions.add",{channel:t.channel,timestamp:t.timestamp,name:t.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!t.channel)return JSON.stringify({error:"channel is required"});let e=await H("conversations.history",{channel:t.channel,limit:t.limit||20});return JSON.stringify({messages:(e.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_thread_replies":{if(!t.channel||!t.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let e=await H("conversations.replies",{channel:t.channel,ts:t.thread_ts});return JSON.stringify({messages:(e.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_users":{let e=await H("users.list",{limit:100});return JSON.stringify({users:(e.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(!t.user_id)return JSON.stringify({error:"user_id is required"});let e=await H("users.profile.get",{user:t.user_id});return JSON.stringify({profile:e.profile})}case"slack_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});try{let e=await H("users.lookupByEmail",{email:t.email});return JSON.stringify({ok:!0,user:{id:e.user?.id,name:e.user?.real_name||e.user?.name,email:e.user?.profile?.email||t.email}})}catch(e){if(/users_not_found/.test(e.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw e}}case"slack_list_usergroups":{let e=await H("usergroups.list",{});return JSON.stringify({usergroups:(e.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(!t.usergroup)return JSON.stringify({error:"usergroup id is required"});let e=await H("usergroups.users.list",{usergroup:t.usergroup});return JSON.stringify({users:e.users||[]})}case"slack_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(t.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 H("users.list",d);for(let p of l.members||[])p.deleted||p.is_bot||i.push(p);if(s=l.response_metadata?.next_cursor,!s)break}let a=[];for(let c of i){let d=(c.real_name||"").toLowerCase(),l=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;d.includes(e)&&(u+=100-Math.abs(d.length-e.length)),l.includes(e)&&(u+=60-Math.abs(l.length-e.length)),p.includes(e)&&(u+=30-Math.abs(p.length-e.length)),(d===e||l===e)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,n).map(({_score:c,...d})=>d),scanned:i.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as _c}from"fs";import{fileURLToPath as bc}from"url";import{dirname as kc,resolve as wc}from"path";import{resolveIntegrationToken as Sc}from"@zibby/core/backend-client.js";function vc(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=kc(bc(import.meta.url)),t=wc(r,"..","bin","mcp-lark.mjs");return _c(t)?t:null}var Ic=6e3*1e3,et=null;async function Nc(){let{appId:r,appSecret:t,host:e}=await Sc("lark");if(et&&et.appId===r&&et.expiresAt>Date.now())return{token:et.token,host:e};let i=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:t})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return et={token:i.tenant_access_token,expiresAt:Date.now()+Ic,appId:r},{token:i.tenant_access_token,host:e}}async function ke(r,t,e={}){let{token:n,host:i}=await Nc(),s=`${i}${t}`,o={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(o.body=JSON.stringify(e));let c=await(await fetch(s,o)).json();if(c.code!==0)throw new Error(`Lark API ${t} error: ${c.msg||c.code}`);return c.data||{}}function Dn(r){return JSON.stringify({text:r})}function Oc(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 M={id:"lark",callsBackend:!0,serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:I.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],promptFragment:`## Lark
365
+ - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=Hc();if(!r)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r],env:t,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"slack_list_channels":{let e=await z("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(e.channels||[]).map(n=>({id:n.id,name:n.name,topic:n.topic?.value}))})}case"slack_post_message":{if(!t.channel||!t.text)return JSON.stringify({error:"channel and text are required"});let e=await z("chat.postMessage",{channel:t.channel,text:t.text,...t.blocks?{blocks:t.blocks}:{}});return JSON.stringify({ok:!0,ts:e.ts,channel:e.channel})}case"slack_reply_to_thread":{if(!t.channel||!t.thread_ts||!t.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let e=await z("chat.postMessage",{channel:t.channel,thread_ts:t.thread_ts,text:t.text});return JSON.stringify({ok:!0,ts:e.ts})}case"slack_add_reaction":return!t.channel||!t.timestamp||!t.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await z("reactions.add",{channel:t.channel,timestamp:t.timestamp,name:t.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!t.channel)return JSON.stringify({error:"channel is required"});let e=await z("conversations.history",{channel:t.channel,limit:t.limit||20});return JSON.stringify({messages:(e.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_thread_replies":{if(!t.channel||!t.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let e=await z("conversations.replies",{channel:t.channel,ts:t.thread_ts});return JSON.stringify({messages:(e.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_users":{let e=await z("users.list",{limit:100});return JSON.stringify({users:(e.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(!t.user_id)return JSON.stringify({error:"user_id is required"});let e=await z("users.profile.get",{user:t.user_id});return JSON.stringify({profile:e.profile})}case"slack_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});try{let e=await z("users.lookupByEmail",{email:t.email});return JSON.stringify({ok:!0,user:{id:e.user?.id,name:e.user?.real_name||e.user?.name,email:e.user?.profile?.email||t.email}})}catch(e){if(/users_not_found/.test(e.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw e}}case"slack_list_usergroups":{let e=await z("usergroups.list",{});return JSON.stringify({usergroups:(e.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(!t.usergroup)return JSON.stringify({error:"usergroup id is required"});let e=await z("usergroups.users.list",{usergroup:t.usergroup});return JSON.stringify({users:e.users||[]})}case"slack_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(t.limit)||5,25)),i=[],s,o=5;for(let c=0;c<o;c+=1){let l={limit:200};s&&(l.cursor=s);let d=await z("users.list",l);for(let p of d.members||[])p.deleted||p.is_bot||i.push(p);if(s=d.response_metadata?.next_cursor,!s)break}let a=[];for(let c of i){let l=(c.real_name||"").toLowerCase(),d=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;l.includes(e)&&(u+=100-Math.abs(l.length-e.length)),d.includes(e)&&(u+=60-Math.abs(d.length-e.length)),p.includes(e)&&(u+=30-Math.abs(p.length-e.length)),(l===e||d===e)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,l)=>l._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,n).map(({_score:c,...l})=>l),scanned:i.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as zc}from"fs";import{fileURLToPath as Yc}from"url";import{dirname as Wc,resolve as Zc}from"path";import{resolveIntegrationToken as Vc}from"@zibby/core/backend-client.js";function Xc(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=Wc(Yc(import.meta.url)),t=Zc(r,"..","bin","mcp-lark.mjs");return zc(t)?t:null}var Qc=6e3*1e3,ot=null;async function el(){let{appId:r,appSecret:t,host:e}=await Vc("lark");if(ot&&ot.appId===r&&ot.expiresAt>Date.now())return{token:ot.token,host:e};let i=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:t})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return ot={token:i.tenant_access_token,expiresAt:Date.now()+Qc,appId:r},{token:i.tenant_access_token,host:e}}async function Ne(r,t,e={}){let{token:n,host:i}=await el(),s=`${i}${t}`,o={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(o.body=JSON.stringify(e));let c=await(await fetch(s,o)).json();if(c.code!==0)throw new Error(`Lark API ${t} error: ${c.msg||c.code}`);return c.data||{}}function ti(r){return JSON.stringify({text:r})}function tl(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 F={id:"lark",callsBackend:!0,serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:I.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],promptFragment:`## Lark
366
366
  You can send messages and replies on Lark. Use:
367
367
  - lark_send_message: post a message to a chat, user, or DM
368
368
  - lark_reply: reply to an existing message (threaded)
369
369
  - lark_list_chats: list chats the bot is a member of
370
370
  - lark_get_chat_history: fetch recent messages in a chat
371
371
  - 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)
372
- When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=vc();if(!r)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r],env:t,alwaysLoad:!0}},tools:[{name:"lark_send_message",description:"Send a text message to a Lark chat, user, or DM. receive_id can be a chat_id (oc_*), open_id (ou_*), union_id (on_*), or email.",input_schema:{type:"object",properties:{receive_id:{type:"string",description:"Target id: chat_id (oc_*), open_id (ou_*), union_id (on_*), or email"},text:{type:"string",description:"Message text"}},required:["receive_id","text"]}},{name:"lark_reply",description:"Reply to an existing Lark message (creates a thread). Use the message_id from the inbound event.",input_schema:{type:"object",properties:{message_id:{type:"string",description:"Lark message id (om_*) to reply to"},text:{type:"string",description:"Reply text"}},required:["message_id","text"]}},{name:"lark_list_chats",description:"List chats (groups + DMs) the bot is a member of.",input_schema:{type:"object",properties:{page_size:{type:"number",description:"Max results (default 50)"}}}},{name:"lark_get_chat_history",description:"Fetch recent messages in a chat.",input_schema:{type:"object",properties:{chat_id:{type:"string",description:"Chat id (oc_*)"},page_size:{type:"number",description:"Max messages (default 20)"}},required:["chat_id"]}},{name:"lark_lookup_user_by_email",description:"Resolve an email address to a Lark user id (open_id). Returns { ok:true, user:{open_id,email,name} } on hit, { ok:false } if no Lark user has that email. Use the open_id as `receive_id` in lark_send_message to DM.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"lark_search_users",description:'Fuzzy-search users by name across chats the bot is a member of. Lark has no public org-wide user search API for bots \u2014 this walks the bot\'s chat memberships and matches names client-side. Best for "send to Sam" style routing where you have a name but no email. Returns up to `limit` ranked matches { open_id, name }.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against user names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}],async handleToolCall(r,t){try{switch(r){case"lark_send_message":{if(!t.receive_id||!t.text)return JSON.stringify({error:"receive_id and text are required"});let e=Oc(t.receive_id),n=await ke("POST",`/open-apis/im/v1/messages?receive_id_type=${e}`,{receive_id:t.receive_id,msg_type:"text",content:Dn(t.text)});return JSON.stringify({ok:!0,message_id:n.message_id})}case"lark_reply":{if(!t.message_id||!t.text)return JSON.stringify({error:"message_id and text are required"});let e=await ke("POST",`/open-apis/im/v1/messages/${encodeURIComponent(t.message_id)}/reply`,{msg_type:"text",content:Dn(t.text)});return JSON.stringify({ok:!0,message_id:e.message_id})}case"lark_list_chats":{let e=t.page_size||50,i=((await ke("GET",`/open-apis/im/v1/chats?page_size=${e}`)).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(!t.chat_id)return JSON.stringify({error:"chat_id is required"});let e=t.page_size||20,i=((await ke("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(t.chat_id)}&page_size=${e}&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(!t.email)return JSON.stringify({error:"email is required"});let n=((await ke("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[t.email]})).user_list||[]).find(i=>i.email===t.email&&i.user_id);return JSON.stringify(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(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(t.limit)||5,25)),i=200,o=((await ke("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(l=>l.chat_id),a=new Set,c=[];for(let l of o){if(c.length>=i)break;try{let p=await ke("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=i))break}catch(p){console.warn(`[lark] member scan failed for ${l}: ${p.message}`)}}let d=[];for(let l of c){let p=(l.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(e)&&(u+=100-Math.abs(p.length-e.length)),p===e&&(u+=200),u>0&&d.push({open_id:l.open_id,name:l.name,_score:u})}return d.sort((l,p)=>p._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,n).map(({_score:l,...p})=>p),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}}};import{existsSync as Tc}from"fs";import{fileURLToPath as Ac}from"url";import{dirname as Rc,resolve as Ec}from"path";import{resolveIntegrationToken as jc}from"@zibby/core/backend-client.js";function xc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Rc(Ac(import.meta.url)),t=Ec(r,"..","bin","mcp-skill.mjs");return Tc(t)?t:null}var Lc=process.env.DISCORD_API_URL||"https://discord.com/api/v10",$c=2e3;function Pc(r,t=$c){let e=String(r??"");if(!e.trim())return[];if(e.length<=t)return[e];let n=[],i=e;for(;i.length>t;){let o=i.slice(0,t).lastIndexOf(`
373
- `),a=o>t/2?o+1:t;n.push(i.slice(0,a)),i=i.slice(a)}return i&&n.push(i),n}async function Mn(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let t=await jc(I.DISCORD),e=(t&&t.token?String(t.token):"").trim();if(!e)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:e,guildId:(t.guildId||"").trim()}}async function ur(r,t,{token:e,body:n}={}){let i=e.startsWith("Bot ")?e:`Bot ${e}`,s=await fetch(`${Lc}${t}`,{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 Cc({token:r,guildId:t},e){let n=String(e||"").trim()||t||(process.env.DISCORD_GUILD_ID||"").trim();if(n)return n;let i=await ur("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 Kn={id:"discord",callsBackend:!0,serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:I.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord
372
+ When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=Xc();if(!r)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r],env:t,alwaysLoad:!0}},tools:[{name:"lark_send_message",description:"Send a text message to a Lark chat, user, or DM. receive_id can be a chat_id (oc_*), open_id (ou_*), union_id (on_*), or email.",input_schema:{type:"object",properties:{receive_id:{type:"string",description:"Target id: chat_id (oc_*), open_id (ou_*), union_id (on_*), or email"},text:{type:"string",description:"Message text"}},required:["receive_id","text"]}},{name:"lark_reply",description:"Reply to an existing Lark message (creates a thread). Use the message_id from the inbound event.",input_schema:{type:"object",properties:{message_id:{type:"string",description:"Lark message id (om_*) to reply to"},text:{type:"string",description:"Reply text"}},required:["message_id","text"]}},{name:"lark_list_chats",description:"List chats (groups + DMs) the bot is a member of.",input_schema:{type:"object",properties:{page_size:{type:"number",description:"Max results (default 50)"}}}},{name:"lark_get_chat_history",description:"Fetch recent messages in a chat.",input_schema:{type:"object",properties:{chat_id:{type:"string",description:"Chat id (oc_*)"},page_size:{type:"number",description:"Max messages (default 20)"}},required:["chat_id"]}},{name:"lark_lookup_user_by_email",description:"Resolve an email address to a Lark user id (open_id). Returns { ok:true, user:{open_id,email,name} } on hit, { ok:false } if no Lark user has that email. Use the open_id as `receive_id` in lark_send_message to DM.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"lark_search_users",description:'Fuzzy-search users by name across chats the bot is a member of. Lark has no public org-wide user search API for bots \u2014 this walks the bot\'s chat memberships and matches names client-side. Best for "send to Sam" style routing where you have a name but no email. Returns up to `limit` ranked matches { open_id, name }.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against user names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}],async handleToolCall(r,t){try{switch(r){case"lark_send_message":{if(!t.receive_id||!t.text)return JSON.stringify({error:"receive_id and text are required"});let e=tl(t.receive_id),n=await Ne("POST",`/open-apis/im/v1/messages?receive_id_type=${e}`,{receive_id:t.receive_id,msg_type:"text",content:ti(t.text)});return JSON.stringify({ok:!0,message_id:n.message_id})}case"lark_reply":{if(!t.message_id||!t.text)return JSON.stringify({error:"message_id and text are required"});let e=await Ne("POST",`/open-apis/im/v1/messages/${encodeURIComponent(t.message_id)}/reply`,{msg_type:"text",content:ti(t.text)});return JSON.stringify({ok:!0,message_id:e.message_id})}case"lark_list_chats":{let e=t.page_size||50,i=((await Ne("GET",`/open-apis/im/v1/chats?page_size=${e}`)).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(!t.chat_id)return JSON.stringify({error:"chat_id is required"});let e=t.page_size||20,i=((await Ne("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(t.chat_id)}&page_size=${e}&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(!t.email)return JSON.stringify({error:"email is required"});let n=((await Ne("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[t.email]})).user_list||[]).find(i=>i.email===t.email&&i.user_id);return JSON.stringify(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(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(t.limit)||5,25)),i=200,o=((await Ne("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(d=>d.chat_id),a=new Set,c=[];for(let d of o){if(c.length>=i)break;try{let p=await Ne("GET",`/open-apis/im/v1/chats/${encodeURIComponent(d)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=i))break}catch(p){console.warn(`[lark] member scan failed for ${d}: ${p.message}`)}}let l=[];for(let d of c){let p=(d.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(e)&&(u+=100-Math.abs(p.length-e.length)),p===e&&(u+=200),u>0&&l.push({open_id:d.open_id,name:d.name,_score:u})}return l.sort((d,p)=>p._score-d._score),JSON.stringify({ok:!0,matches:l.slice(0,n).map(({_score:d,...p})=>p),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}}};import{existsSync as rl}from"fs";import{fileURLToPath as nl}from"url";import{dirname as il,resolve as sl}from"path";import{resolveIntegrationToken as ol}from"@zibby/core/backend-client.js";function al(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=il(nl(import.meta.url)),t=sl(r,"..","bin","mcp-skill.mjs");return rl(t)?t:null}var cl=process.env.DISCORD_API_URL||"https://discord.com/api/v10",ll=2e3;function dl(r,t=ll){let e=String(r??"");if(!e.trim())return[];if(e.length<=t)return[e];let n=[],i=e;for(;i.length>t;){let o=i.slice(0,t).lastIndexOf(`
373
+ `),a=o>t/2?o+1:t;n.push(i.slice(0,a)),i=i.slice(a)}return i&&n.push(i),n}async function ri(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let t=await ol(I.DISCORD),e=(t&&t.token?String(t.token):"").trim();if(!e)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:e,guildId:(t.guildId||"").trim()}}async function vr(r,t,{token:e,body:n}={}){let i=e.startsWith("Bot ")?e:`Bot ${e}`,s=await fetch(`${cl}${t}`,{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 pl({token:r,guildId:t},e){let n=String(e||"").trim()||t||(process.env.DISCORD_GUILD_ID||"").trim();if(n)return n;let i=await vr("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 ni={id:"discord",callsBackend:!0,serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:I.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord
374
374
  You can post to the user's Discord server as their bot. Tools:
375
375
  - discord_send_message(channelId, text) \u2014 post a message to a channel (long text is auto-chunked to Discord's 2000-char limit)
376
- - 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 e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_SELF_HOST","DISCORD_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(r[e]=process.env[e]);let t=xc();return t?{type:"stdio",command:"node",args:[t,"../dist/discord.js","discordSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,t={}){try{switch(r){case"discord_send_message":{let e=String(t.channelId||"").trim(),n=String(t.text||"");if(!e||!n.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let i=await Mn(),s=Pc(n),o=[];for(let a of s){let c=await ur("POST",`/channels/${encodeURIComponent(e)}/messages`,{token:i.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:e,messageIds:o,chunks:s.length})}case"discord_list_channels":{let e=await Mn(),n=await Cc(e,t.guildId),i=await ur("GET",`/guilds/${encodeURIComponent(n)}/channels`,{token:e.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(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"discord_send_message",description:"Post a message to a Discord channel as the connected bot. Text over 2000 chars is automatically split into sequential messages.",input_schema:{type:"object",properties:{channelId:{type:"string",description:"Discord channel id (snowflake). Use discord_list_channels to find it."},text:{type:"string",description:"Message text (Discord markdown supported)"}},required:["channelId","text"]}},{name:"discord_list_channels",description:"List the text channels of the connected Discord server (id + name). Pass guildId only when the bot is in multiple servers.",input_schema:{type:"object",properties:{guildId:{type:"string",description:"Discord server (guild) id \u2014 optional when the bot is in exactly one server or one was captured at connect time"}}}}]};import{existsSync as Wn,statSync as Uc,readFileSync as Bc}from"fs";import{fileURLToPath as Jc}from"url";import{basename as qc,dirname as Dc,resolve as Mc}from"path";import{resolveIntegrationToken as Kc,clearTokenCache as Gc}from"@zibby/core/backend-client.js";function Fc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Dc(Jc(import.meta.url)),t=Mc(r,"..","bin","mcp-skill.mjs");return Wn(t)?t:null}var Hc="2022-06-28",zc="https://api.notion.com/v1",xt=2e4,Gn=25,Yc=25,Lt=100,Fn=500,Wc=20*1024*1024;function ce(r){if(!r||typeof r!="string")return null;let e=r.trim().split(/[?#]/)[0],n=e.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);if(n)return n[0].toLowerCase();let i=e.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 ne(r,t={}){let e=async()=>{let{token:n}=await Kc("notion");if(typeof n!="string"||!n)throw new Error(`Invalid notion token type: ${typeof n}`);let i=await fetch(`${zc}${r}`,{method:t.method||"GET",headers:{Authorization:`Bearer ${n}`,"Notion-Version":Hc,Accept:"application/json",...t.body&&!t.formData?{"Content-Type":"application/json"}:{},...t.headers},body:t.formData?t.formData:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Notion API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await e()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Gc("notion"),e()}}function Be(r){if(!Array.isArray(r))return"";let t="";for(let e of r){let n=e?.plain_text??e?.text?.content??"";if(!n)continue;let i=e.annotations||{};i.code&&(n=`\`${n}\``),i.bold&&(n=`**${n}**`),i.italic&&(n=`_${n}_`),i.strikethrough&&(n=`~~${n}~~`);let s=e?.href||e?.text?.link?.url;s&&(n=`[${n}](${s})`),t+=n}return t}function Zc(r,t,e){let n=r?.type,i=r?.[n]||{},s=" ".repeat(Math.max(0,t)),o=(d="rich_text")=>Be(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||""}
376
+ - 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 e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_SELF_HOST","DISCORD_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(r[e]=process.env[e]);let t=al();return t?{type:"stdio",command:"node",args:[t,"../dist/discord.js","discordSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,t={}){try{switch(r){case"discord_send_message":{let e=String(t.channelId||"").trim(),n=String(t.text||"");if(!e||!n.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let i=await ri(),s=dl(n),o=[];for(let a of s){let c=await vr("POST",`/channels/${encodeURIComponent(e)}/messages`,{token:i.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:e,messageIds:o,chunks:s.length})}case"discord_list_channels":{let e=await ri(),n=await pl(e,t.guildId),i=await vr("GET",`/guilds/${encodeURIComponent(n)}/channels`,{token:e.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(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"discord_send_message",description:"Post a message to a Discord channel as the connected bot. Text over 2000 chars is automatically split into sequential messages.",input_schema:{type:"object",properties:{channelId:{type:"string",description:"Discord channel id (snowflake). Use discord_list_channels to find it."},text:{type:"string",description:"Message text (Discord markdown supported)"}},required:["channelId","text"]}},{name:"discord_list_channels",description:"List the text channels of the connected Discord server (id + name). Pass guildId only when the bot is in multiple servers.",input_schema:{type:"object",properties:{guildId:{type:"string",description:"Discord server (guild) id \u2014 optional when the bot is in exactly one server or one was captured at connect time"}}}}]};import{existsSync as li,statSync as ul,readFileSync as ml}from"fs";import{fileURLToPath as fl}from"url";import{basename as hl,dirname as yl,resolve as gl}from"path";import{resolveIntegrationToken as bl,clearTokenCache as _l}from"@zibby/core/backend-client.js";function kl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=yl(fl(import.meta.url)),t=gl(r,"..","bin","mcp-skill.mjs");return li(t)?t:null}var wl="2022-06-28",Sl="https://api.notion.com/v1",qt=2e4,ii=25,vl=25,Mt=100,si=500,Il=20*1024*1024;function pe(r){if(!r||typeof r!="string")return null;let e=r.trim().split(/[?#]/)[0],n=e.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);if(n)return n[0].toLowerCase();let i=e.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 ie(r,t={}){let e=async()=>{let{token:n}=await bl("notion");if(typeof n!="string"||!n)throw new Error(`Invalid notion token type: ${typeof n}`);let i=await fetch(`${Sl}${r}`,{method:t.method||"GET",headers:{Authorization:`Bearer ${n}`,"Notion-Version":wl,Accept:"application/json",...t.body&&!t.formData?{"Content-Type":"application/json"}:{},...t.headers},body:t.formData?t.formData:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Notion API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await e()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return _l("notion"),e()}}function Fe(r){if(!Array.isArray(r))return"";let t="";for(let e of r){let n=e?.plain_text??e?.text?.content??"";if(!n)continue;let i=e.annotations||{};i.code&&(n=`\`${n}\``),i.bold&&(n=`**${n}**`),i.italic&&(n=`_${n}_`),i.strikethrough&&(n=`~~${n}~~`);let s=e?.href||e?.text?.link?.url;s&&(n=`[${n}](${s})`),t+=n}return t}function Nl(r,t,e){let n=r?.type,i=r?.[n]||{},s=" ".repeat(Math.max(0,t)),o=(l="rich_text")=>Fe(i[l]),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||""}
377
377
  ${o()}
378
- \`\`\``;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=>Be(l).trim());a=`${s}| ${d.join(" | ")} |`;break}default:a=o();break}let c=[];return a&&a.trim()&&c.push(a),e&&e.trim()&&c.push(e),c.join(`
379
- `)}async function Zn(r,t,e){let n=[],i,s=0;do{if(e.used>=xt)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let a=await ne(`/blocks/${r}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await Zn(d.id,t+1,e));let p=Zc(d,t,l);if(p&&(n.push(p),e.used+=p.length+1),e.used>=xt)break}i=a.has_more?a.next_cursor:void 0,s+=1}while(i&&s<Yc);return n.join(`
380
- `)}function Hn(r){let t=r?.properties||{};for(let e of Object.values(t))if(e?.type==="title"){let n=Be(e.title).trim();if(n)return n}return""}function tt(r){let t=String(r??"");if(!t)return[{type:"text",text:{content:""}}];let e=[];for(let n=0;n<t.length;n+=2e3)e.push({type:"text",text:{content:t.slice(n,n+2e3)}});return e}function Vc(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:Be(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function Xc(r){if(!r||!r.type)return"";switch(r.type){case"title":return Be(r.title).trim();case"rich_text":return Be(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(e=>e.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(e=>e.name||e.id).join(", ");default:return""}}function mr(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function Qc(r){let t=String(r??"").replace(/\r\n/g,`
378
+ \`\`\``;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 l=(i.cells||[]).map(d=>Fe(d).trim());a=`${s}| ${l.join(" | ")} |`;break}default:a=o();break}let c=[];return a&&a.trim()&&c.push(a),e&&e.trim()&&c.push(e),c.join(`
379
+ `)}async function di(r,t,e){let n=[],i,s=0;do{if(e.used>=qt)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let a=await ie(`/blocks/${r}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let l of c){let d="";l.has_children&&(d=await di(l.id,t+1,e));let p=Nl(l,t,d);if(p&&(n.push(p),e.used+=p.length+1),e.used>=qt)break}i=a.has_more?a.next_cursor:void 0,s+=1}while(i&&s<vl);return n.join(`
380
+ `)}function oi(r){let t=r?.properties||{};for(let e of Object.values(t))if(e?.type==="title"){let n=Fe(e.title).trim();if(n)return n}return""}function at(r){let t=String(r??"");if(!t)return[{type:"text",text:{content:""}}];let e=[];for(let n=0;n<t.length;n+=2e3)e.push({type:"text",text:{content:t.slice(n,n+2e3)}});return e}function Ol(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:Fe(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function Tl(r){if(!r||!r.type)return"";switch(r.type){case"title":return Fe(r.title).trim();case"rich_text":return Fe(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(e=>e.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(e=>e.name||e.id).join(", ");default:return""}}function Ir(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function Rl(r){let t=String(r??"").replace(/\r\n/g,`
381
381
  `),e=[];for(let n of t.split(`
382
- `)){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),e.push({object:"block",type:c,[c]:{rich_text:tt(d)}})}return e}function zn(r){return Array.isArray(r?.blocks)&&r.blocks.length?r.blocks.slice(0,Fn):typeof r?.markdown=="string"&&r.markdown.trim()?Qc(r.markdown).slice(0,Fn):null}async function Yn(r,t){for(let e=0;e<t.length;e+=Lt)await ne(`/blocks/${r}/children`,{method:"PATCH",body:{children:t.slice(e,e+Lt)}})}function el(r){let t=typeof r=="string"?r.trim():"";if(!t)throw new Error("imagePath is required");if(!Wn(t)||!Uc(t).isFile())throw new Error(`imagePath not found (or not a file): ${t}`);if(!/\.(png|jpe?g)$/i.test(t))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let e=Bc(t);if(e.length>Wc)throw new Error(`image is ${(e.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return e}async function tl(r){let t=el(r),e=qc(r.trim()),n=/\.png$/i.test(e)?"image/png":"image/jpeg",s=(await ne("/file_uploads",{method:"POST",body:{mode:"single_part",filename:e}}))?.id;if(!s)throw new Error("Notion file upload create returned no id");let o=new FormData;return o.set("file",new Blob([t],{type:n}),e),await ne(`/file_uploads/${s}/send`,{method:"POST",formData:o}),s}var Vn={id:"notion",callsBackend:!0,serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:I.NOTION,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion
382
+ `)){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,l;s?(c=`heading_${s[1].length}`,l=s[2]):o?(c="bulleted_list_item",l=o[1]):a?(c="numbered_list_item",l=a[1]):(c="paragraph",l=i),e.push({object:"block",type:c,[c]:{rich_text:at(l)}})}return e}function ai(r){return Array.isArray(r?.blocks)&&r.blocks.length?r.blocks.slice(0,si):typeof r?.markdown=="string"&&r.markdown.trim()?Rl(r.markdown).slice(0,si):null}async function ci(r,t){for(let e=0;e<t.length;e+=Mt)await ie(`/blocks/${r}/children`,{method:"PATCH",body:{children:t.slice(e,e+Mt)}})}function Al(r){let t=typeof r=="string"?r.trim():"";if(!t)throw new Error("imagePath is required");if(!li(t)||!ul(t).isFile())throw new Error(`imagePath not found (or not a file): ${t}`);if(!/\.(png|jpe?g)$/i.test(t))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let e=ml(t);if(e.length>Il)throw new Error(`image is ${(e.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return e}async function El(r){let t=Al(r),e=hl(r.trim()),n=/\.png$/i.test(e)?"image/png":"image/jpeg",s=(await ie("/file_uploads",{method:"POST",body:{mode:"single_part",filename:e}}))?.id;if(!s)throw new Error("Notion file upload create returned no id");let o=new FormData;return o.set("file",new Blob([t],{type:n}),e),await ie(`/file_uploads/${s}/send`,{method:"POST",formData:o}),s}var pi={id:"notion",callsBackend:!0,serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:I.NOTION,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion
383
383
  You can read Notion content as context AND write to Notion (create pages, append blocks, insert images).
384
384
  - 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.
385
385
  - 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.
@@ -388,7 +388,7 @@ You can read Notion content as context AND write to Notion (create pages, append
388
388
  - 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 }.
389
389
  - 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.
390
390
  - 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.
391
- 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=Fc();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"notion_get_page":{let e=t?.pageId||t?.page||t?.url||t?.id,n=ce(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await ne(`/pages/${n}`),s=Hn(i),o=i?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,c=await Zn(n,0,{used:0}),d=!1;return c.length>xt&&(c=c.slice(0,xt),d=!0),JSON.stringify({ok:!0,id:n,title:s,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let e=t?.databaseId||t?.database||t?.url||t?.id,n=ce(e);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(t?.maxResults)||Gn,Gn))};t?.filter&&typeof t.filter=="object"&&(s.filter=t.filter);let o=await ne(`/databases/${n}/query`,{method:"POST",body:s}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[p,u]of Object.entries(d.properties||{})){let m=Xc(u);m&&(l[p]=m)}return{id:d.id,title:Hn(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 e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let n=t?.databaseId?ce(t.databaseId):null,i=t?.parentPageId?ce(t.parentPageId):ce(t?.parent||t?.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:tt(e)}},a=zn(t)||[],c=a.slice(0,Lt),d=await ne("/pages",{method:"POST",body:{parent:s,properties:o,...c.length?{children:c}:{}}}),l=d?.id;if(!l)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let p=a.slice(Lt);return p.length&&await Yn(l,p),JSON.stringify({ok:!0,pageId:l,url:d?.url||mr(l)})}case"notion_append_blocks":{let e=ce(t?.pageId||t?.blockId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=zn(t);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await Yn(e,n),JSON.stringify({ok:!0,pageId:e,url:mr(e)}))}case"notion_insert_image":{let e=ce(t?.pageId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=typeof t?.caption=="string"&&t.caption.trim()?tt(t.caption.trim()):null,i,s;if(typeof t?.imagePath=="string"&&t.imagePath.trim())s=await tl(t.imagePath),i={type:"file_upload",file_upload:{id:s}};else if(typeof t?.imageUrl=="string"&&t.imageUrl.trim())i={type:"external",external:{url:t.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return n&&(i.caption=n),await ne(`/blocks/${e}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:i}]}}),JSON.stringify({ok:!0,pageId:e,url:mr(e),...s?{fileUploadId:s}:{}})}case"notion_list_comments":{let e=t?.blockId||t?.pageId||t?.block||t?.page||t?.url||t?.id,n=ce(e);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 ne(`/comments?${i.toString()}`),a=(Array.isArray(s.results)?s.results:[]).map(Vc);return JSON.stringify({ok:!0,id:n,count:a.length,comments:a})}case"notion_add_comment":{let e=typeof t?.text=="string"?t.text:typeof t?.body=="string"?t.body:"";if(!e||!e.trim())return JSON.stringify({ok:!1,error:"text is required"});let n=t?.discussionId||t?.discussion_id||null,i;if(n)i={discussion_id:String(n),rich_text:tt(e)};else{let o=t?.pageId||t?.page||t?.url||t?.id,a=ce(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:tt(e)}}let s=await ne("/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(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}},{name:"notion_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 rl,readFileSync as nl}from"fs";import{fileURLToPath as il}from"url";import{dirname as sl,resolve as ol}from"path";import{resolveIntegrationToken as fr,clearTokenCache as al}from"@zibby/core/backend-client.js";function cl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=sl(il(import.meta.url)),t=ol(r,"..","bin","mcp-skill.mjs");return rl(t)?t:null}function ll(){let r=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!r)return null;let t=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:r,memberId:t}}function dl(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function pl(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var ul="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 hr(){let r=ll();if(r)return r;if(dl()||pl())throw new Error(ul);return null}var ml="202506",fl="https://api.linkedin.com";function Xn(r){if(r==null)return null;let t=String(r).trim();if(!t)return null;let e=t.match(/urn:li:organization:(\d+)/i);return e?e[1]:/^\d+$/.test(t)?t:null}function Qn(r){if(!r)return"";if(r.localizedName)return String(r.localizedName);let t=r.name&&r.name.localized;if(t&&typeof t=="object"){let e=Object.values(t)[0];if(e)return String(e)}return""}function $t(r,t){return r?typeof r.get=="function"?r.get(t):r[t]||r[t.toLowerCase()]||null:null}async function we(r,t={},e="linkedin_business"){let n=async()=>{let i;if(e==="linkedin_personal"){let d=hr();d&&(i=d.token)}if(i||({token:i}=await fr(e)),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:`${fl}${r}`,o=await fetch(s,{method:t.method||"GET",headers:{Authorization:`Bearer ${i}`,"LinkedIn-Version":ml,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${d.slice(0,300)}`)}let a=await o.text().catch(()=>""),c={};if(a&&a.trim())try{c=JSON.parse(a)}catch{c={raw:a}}return{status:o.status,headers:o.headers,body:c}};try{return await n()}catch(i){let s=String(i?.message||i||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw i;return al(e),n()}}async function hl(r){let t;if(r==="linkedin_personal"){let e=hr();e&&(t=e.token)}if(t||({token:t}=await fr(r)),typeof t!="string"||!t)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return t}function yl(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 ei(r,t,e,n){if(typeof e!="string"||!e.trim())throw new Error("imagePath (a local image file path) is required to upload an image");let{body:i}=await we("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:t}}},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=nl(e),c=await hl(r),d=await fetch(s,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":n||yl(e)},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 ti={id:"linkedin",callsBackend:!0,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
391
+ 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=kl();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"notion_get_page":{let e=t?.pageId||t?.page||t?.url||t?.id,n=pe(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await ie(`/pages/${n}`),s=oi(i),o=i?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,c=await di(n,0,{used:0}),l=!1;return c.length>qt&&(c=c.slice(0,qt),l=!0),JSON.stringify({ok:!0,id:n,title:s,url:o,text:c,...l?{truncated:!0}:{}})}case"notion_query_database":{let e=t?.databaseId||t?.database||t?.url||t?.id,n=pe(e);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(t?.maxResults)||ii,ii))};t?.filter&&typeof t.filter=="object"&&(s.filter=t.filter);let o=await ie(`/databases/${n}/query`,{method:"POST",body:s}),c=(Array.isArray(o.results)?o.results:[]).map(l=>{let d={};for(let[p,u]of Object.entries(l.properties||{})){let m=Tl(u);m&&(d[p]=m)}return{id:l.id,title:oi(l),url:l.url||`https://www.notion.so/${String(l.id||"").replace(/-/g,"")}`,props:d}});return JSON.stringify({ok:!0,id:n,count:c.length,hasMore:!!o.has_more,rows:c})}case"notion_create_page":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let n=t?.databaseId?pe(t.databaseId):null,i=t?.parentPageId?pe(t.parentPageId):pe(t?.parent||t?.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:at(e)}},a=ai(t)||[],c=a.slice(0,Mt),l=await ie("/pages",{method:"POST",body:{parent:s,properties:o,...c.length?{children:c}:{}}}),d=l?.id;if(!d)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let p=a.slice(Mt);return p.length&&await ci(d,p),JSON.stringify({ok:!0,pageId:d,url:l?.url||Ir(d)})}case"notion_append_blocks":{let e=pe(t?.pageId||t?.blockId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=ai(t);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await ci(e,n),JSON.stringify({ok:!0,pageId:e,url:Ir(e)}))}case"notion_insert_image":{let e=pe(t?.pageId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=typeof t?.caption=="string"&&t.caption.trim()?at(t.caption.trim()):null,i,s;if(typeof t?.imagePath=="string"&&t.imagePath.trim())s=await El(t.imagePath),i={type:"file_upload",file_upload:{id:s}};else if(typeof t?.imageUrl=="string"&&t.imageUrl.trim())i={type:"external",external:{url:t.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return n&&(i.caption=n),await ie(`/blocks/${e}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:i}]}}),JSON.stringify({ok:!0,pageId:e,url:Ir(e),...s?{fileUploadId:s}:{}})}case"notion_list_comments":{let e=t?.blockId||t?.pageId||t?.block||t?.page||t?.url||t?.id,n=pe(e);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 ie(`/comments?${i.toString()}`),a=(Array.isArray(s.results)?s.results:[]).map(Ol);return JSON.stringify({ok:!0,id:n,count:a.length,comments:a})}case"notion_add_comment":{let e=typeof t?.text=="string"?t.text:typeof t?.body=="string"?t.body:"";if(!e||!e.trim())return JSON.stringify({ok:!1,error:"text is required"});let n=t?.discussionId||t?.discussion_id||null,i;if(n)i={discussion_id:String(n),rich_text:at(e)};else{let o=t?.pageId||t?.page||t?.url||t?.id,a=pe(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:at(e)}}let s=await ie("/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(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}},{name:"notion_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 xl,readFileSync as jl}from"fs";import{fileURLToPath as Ll}from"url";import{dirname as $l,resolve as Pl}from"path";import{resolveIntegrationToken as Nr,clearTokenCache as Cl}from"@zibby/core/backend-client.js";function Ul(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=$l(Ll(import.meta.url)),t=Pl(r,"..","bin","mcp-skill.mjs");return xl(t)?t:null}function Bl(){let r=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!r)return null;let t=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:r,memberId:t}}function Jl(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function Dl(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var ql="You haven't connected your own LinkedIn account \u2014 connect it at https://studio.zibby.dev/integrations (LinkedIn). For privacy, I can't post or act as anyone else's LinkedIn (including the project owner's) on your behalf.";function Or(){let r=Bl();if(r)return r;if(Jl()||Dl())throw new Error(ql);return null}var Ml="202506",Fl="https://api.linkedin.com";function ui(r){if(r==null)return null;let t=String(r).trim();if(!t)return null;let e=t.match(/urn:li:organization:(\d+)/i);return e?e[1]:/^\d+$/.test(t)?t:null}function mi(r){if(!r)return"";if(r.localizedName)return String(r.localizedName);let t=r.name&&r.name.localized;if(t&&typeof t=="object"){let e=Object.values(t)[0];if(e)return String(e)}return""}function Ft(r,t){return r?typeof r.get=="function"?r.get(t):r[t]||r[t.toLowerCase()]||null:null}async function Oe(r,t={},e="linkedin_business"){let n=async()=>{let i;if(e==="linkedin_personal"){let l=Or();l&&(i=l.token)}if(i||({token:i}=await Nr(e)),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:`${Fl}${r}`,o=await fetch(s,{method:t.method||"GET",headers:{Authorization:`Bearer ${i}`,"LinkedIn-Version":Ml,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${l.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 Cl(e),n()}}async function Kl(r){let t;if(r==="linkedin_personal"){let e=Or();e&&(t=e.token)}if(t||({token:t}=await Nr(r)),typeof t!="string"||!t)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return t}function Gl(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 fi(r,t,e,n){if(typeof e!="string"||!e.trim())throw new Error("imagePath (a local image file path) is required to upload an image");let{body:i}=await Oe("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:t}}},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=jl(e),c=await Kl(r),l=await fetch(s,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":n||Gl(e)},body:a});if(!l.ok){let d=await l.text().catch(()=>"");throw new Error(`LinkedIn image upload ${l.status}: ${d.slice(0,300)}`)}return o}var hi={id:"linkedin",callsBackend:!0,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
392
392
  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.
393
393
 
394
394
  Business (company Page) \u2014 DRAFT only:
@@ -404,10 +404,10 @@ Attaching an image (optional, both tools):
404
404
  Notes:
405
405
  - Org-page posts are ALWAYS created as a DRAFT; personal-profile posts are ALWAYS published live \u2014 choose the tool accordingly.
406
406
  - 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.
407
- - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=cl();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/linkedin.js","linkedinSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"linkedin_list_organizations":{let{body:e}=await we("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(e.elements)?e.elements:[],i=[];for(let s of n){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=Xn(o);if(!a)continue;let c="",d="";try{let l=(await we(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=Qn(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 e=t?.organizationUrn||t?.organizationId||t?.organization||t?.orgId,n=Xn(e);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let i=t?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof t?.imagePath=="string"?t.imagePath.trim():"",c=typeof t?.imageAltText=="string"?t.imageAltText:"";if(t?.dry_run===!0)try{let u="";try{let m=(await we(`/rest/organizations/${n}`,{},"linkedin_business")).body;u=Qn(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:n,urn:o},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await ei("linkedin_business",o,a);d.content={media:{id:u,altText:c||""}}}let l=await we("/rest/posts",{method:"POST",body:d},"linkedin_business"),p=$t(l.headers,"x-restli-id")||$t(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"DRAFT",visibility:s,status:l.status})}case"linkedin_publish_post":{let e=hr(),n=e?e.memberId:(await fr("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=t?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof t?.imagePath=="string"?t.imagePath.trim():"",c=typeof t?.imageAltText=="string"?t.imageAltText:"";if(t?.dry_run===!0)try{let u=(await we("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",f=u?.sub?String(u.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await ei("linkedin_personal",o,a);d.content={media:{id:u,altText:c||""}}}let l=await we("/rest/posts",{method:"POST",body:d},"linkedin_personal"),p=$t(l.headers,"x-restli-id")||$t(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"PUBLISHED",visibility:s,status:l.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. 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 si,statSync as gl,readFileSync as _l}from"fs";import{fileURLToPath as bl}from"url";import{basename as kl,dirname as wl,resolve as Sl}from"path";import{resolveIntegrationToken as vl,clearTokenCache as Il}from"@zibby/core/backend-client.js";function Nl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=wl(bl(import.meta.url)),t=Sl(r,"..","bin","mcp-skill.mjs");return si(t)?t:null}var Se="https://docs.googleapis.com/v1",ri="https://www.googleapis.com/drive/v3",Ol="https://www.googleapis.com/upload/drive/v3",Tl=5*1024*1024;function Al(){let r=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!r)return null;let t=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:r,email:t}}function Rl(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function El(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var jl="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.",gr=2e4,xl=25;function yr(r){if(!r||typeof r!="string")return null;let t=r.trim(),e=t.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return e?e[1]:/^[a-zA-Z0-9_-]{20,}$/.test(t)?t:null}async function Ll(){let r,t=Al();if(t)r=t.token;else{if(El()||Rl())throw new Error(jl);({token:r}=await vl("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function ie(r,t={}){let e=async()=>{let n=await Ll(),i=await fetch(r,{method:t.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...t.rawBody&&t.contentType?{"Content-Type":t.contentType}:t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.rawBody?t.rawBody:t.body?JSON.stringify(t.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 e()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Il("google"),e()}}function $l(r){let t=[],e="",n=0;for(;n<r.length;){let i=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(i){t.push({start:e.length,end:e.length+i[1].length,link:i[2]}),e+=i[1],n+=i[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(s){t.push({start:e.length,end:e.length+s[1].length,bold:!0}),e+=s[1],n+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(n));if(o){t.push({start:e.length,end:e.length+o[1].length,code:!0}),e+=o[1],n+=o[0].length;continue}e+=r[n],n+=1}return{text:e,styles:t}}function ni(r,t){let e=String(r??"").replace(/\r\n/g,`
407
+ - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=Ul();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/linkedin.js","linkedinSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"linkedin_list_organizations":{let{body:e}=await Oe("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(e.elements)?e.elements:[],i=[];for(let s of n){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=ui(o);if(!a)continue;let c="",l="";try{let d=(await Oe(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=mi(d),l=d.vanityName||""}catch{}i.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:l})}return JSON.stringify({ok:!0,count:i.length,organizations:i})}case"linkedin_create_draft_post":{let e=t?.organizationUrn||t?.organizationId||t?.organization||t?.orgId,n=ui(e);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let i=t?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof t?.imagePath=="string"?t.imagePath.trim():"",c=typeof t?.imageAltText=="string"?t.imageAltText:"";if(t?.dry_run===!0)try{let u="";try{let m=(await Oe(`/rest/organizations/${n}`,{},"linkedin_business")).body;u=mi(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:n,urn:o},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let l={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await fi("linkedin_business",o,a);l.content={media:{id:u,altText:c||""}}}let d=await Oe("/rest/posts",{method:"POST",body:l},"linkedin_business"),p=Ft(d.headers,"x-restli-id")||Ft(d.headers,"x-linkedin-id")||d.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"DRAFT",visibility:s,status:d.status})}case"linkedin_publish_post":{let e=Or(),n=e?e.memberId:(await Nr("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=t?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof t?.imagePath=="string"?t.imagePath.trim():"",c=typeof t?.imageAltText=="string"?t.imageAltText:"";if(t?.dry_run===!0)try{let u=(await Oe("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",f=u?.sub?String(u.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let l={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await fi("linkedin_personal",o,a);l.content={media:{id:u,altText:c||""}}}let d=await Oe("/rest/posts",{method:"POST",body:l},"linkedin_personal"),p=Ft(d.headers,"x-restli-id")||Ft(d.headers,"x-linkedin-id")||d.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"PUBLISHED",visibility:s,status:d.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. 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 _i,statSync as Hl,readFileSync as zl}from"fs";import{fileURLToPath as Yl}from"url";import{basename as Wl,dirname as Zl,resolve as Vl}from"path";import{resolveIntegrationToken as Xl,clearTokenCache as Ql}from"@zibby/core/backend-client.js";function ed(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Zl(Yl(import.meta.url)),t=Vl(r,"..","bin","mcp-skill.mjs");return _i(t)?t:null}var Te="https://docs.googleapis.com/v1",yi="https://www.googleapis.com/drive/v3",td="https://www.googleapis.com/upload/drive/v3",rd=5*1024*1024;function nd(){let r=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!r)return null;let t=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:r,email:t}}function id(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function sd(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var od="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.",Rr=2e4,ad=25;function Tr(r){if(!r||typeof r!="string")return null;let t=r.trim(),e=t.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return e?e[1]:/^[a-zA-Z0-9_-]{20,}$/.test(t)?t:null}async function cd(){let r,t=nd();if(t)r=t.token;else{if(sd()||id())throw new Error(od);({token:r}=await Xl("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function se(r,t={}){let e=async()=>{let n=await cd(),i=await fetch(r,{method:t.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...t.rawBody&&t.contentType?{"Content-Type":t.contentType}:t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.rawBody?t.rawBody:t.body?JSON.stringify(t.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 e()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Ql("google"),e()}}function ld(r){let t=[],e="",n=0;for(;n<r.length;){let i=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(i){t.push({start:e.length,end:e.length+i[1].length,link:i[2]}),e+=i[1],n+=i[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(s){t.push({start:e.length,end:e.length+s[1].length,bold:!0}),e+=s[1],n+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(n));if(o){t.push({start:e.length,end:e.length+o[1].length,code:!0}),e+=o[1],n+=o[0].length;continue}e+=r[n],n+=1}return{text:e,styles:t}}function gi(r,t){let e=String(r??"").replace(/\r\n/g,`
408
408
  `);if(!e.trim())return{requests:[],endIndex:t};let n=e.split(`
409
- `),i="",s=[],o=[];for(let l of n){let p=l,u=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(p),h=/^\s*[-*]\s+(.*)$/.exec(p),b=/^\s*\d+[.)]\s+(.*)$/.exec(p);f?(u=`HEADING_${f[1].length}`,p=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",p=h[1]):b&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",p=b[1]);let{text:g,styles:_}=$l(p),y=t+i.length;for(let k of _)o.push({...k,start:y+k.start,end:y+k.end});i+=`${g}
410
- `,s.push({start:y,end:t+i.length,named:u,bullet:m})}if(!i)return{requests:[],endIndex:t};let a=[{insertText:{location:{index:t},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:t+i.length}}function Pl(r){let t="",e=n=>{for(let i of Array.isArray(n)?n:[]){if(t.length>=gr)return;if(i.paragraph)for(let s of i.paragraph.elements||[])t+=s?.textRun?.content||"";else if(i.table)for(let s of i.table.tableRows||[])for(let o of s.tableCells||[])e(o.content);else i.tableOfContents&&e(i.tableOfContents.content)}};return e(r?.content),t.slice(0,gr)}var rt=r=>`https://docs.google.com/document/d/${r}/edit`;function Cl(r){let t=typeof r=="string"?r.trim():"";if(!t)throw new Error("imagePath is required");if(!si(t)||!gl(t).isFile())throw new Error(`imagePath not found (or not a file): ${t}`);if(!/\.(png|jpe?g)$/i.test(t))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let e=_l(t);if(e.length>Tl)throw new Error(`image is ${(e.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:e,fileName:kl(t),mimeType:/\.png$/i.test(t)?"image/png":"image/jpeg"}}function Ul(r,t,e){let n=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${n}\r
409
+ `),i="",s=[],o=[];for(let d of n){let p=d,u=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(p),h=/^\s*[-*]\s+(.*)$/.exec(p),_=/^\s*\d+[.)]\s+(.*)$/.exec(p);f?(u=`HEADING_${f[1].length}`,p=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",p=h[1]):_&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",p=_[1]);let{text:y,styles:b}=ld(p),g=t+i.length;for(let k of b)o.push({...k,start:g+k.start,end:g+k.end});i+=`${y}
410
+ `,s.push({start:g,end:t+i.length,named:u,bullet:m})}if(!i)return{requests:[],endIndex:t};let a=[{insertText:{location:{index:t},text:i}}];for(let d of s)d.named&&a.push({updateParagraphStyle:{range:{startIndex:d.start,endIndex:d.end},paragraphStyle:{namedStyleType:d.named},fields:"namedStyleType"}});let c=null,l=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let d of s)d.bullet?c&&c.preset===d.bullet?c.end=d.end:(l(),c={start:d.start,end:d.end,preset:d.bullet}):l();l();for(let d of o)d.end<=d.start||(d.bold?a.push({updateTextStyle:{range:{startIndex:d.start,endIndex:d.end},textStyle:{bold:!0},fields:"bold"}}):d.link?a.push({updateTextStyle:{range:{startIndex:d.start,endIndex:d.end},textStyle:{link:{url:d.link}},fields:"link"}}):d.code&&a.push({updateTextStyle:{range:{startIndex:d.start,endIndex:d.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:t+i.length}}function dd(r){let t="",e=n=>{for(let i of Array.isArray(n)?n:[]){if(t.length>=Rr)return;if(i.paragraph)for(let s of i.paragraph.elements||[])t+=s?.textRun?.content||"";else if(i.table)for(let s of i.table.tableRows||[])for(let o of s.tableCells||[])e(o.content);else i.tableOfContents&&e(i.tableOfContents.content)}};return e(r?.content),t.slice(0,Rr)}var ct=r=>`https://docs.google.com/document/d/${r}/edit`;function pd(r){let t=typeof r=="string"?r.trim():"";if(!t)throw new Error("imagePath is required");if(!_i(t)||!Hl(t).isFile())throw new Error(`imagePath not found (or not a file): ${t}`);if(!/\.(png|jpe?g)$/i.test(t))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let e=zl(t);if(e.length>rd)throw new Error(`image is ${(e.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:e,fileName:Wl(t),mimeType:/\.png$/i.test(t)?"image/png":"image/jpeg"}}function ud(r,t,e){let n=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${n}\r
411
411
  Content-Type: application/json; charset=UTF-8\r
412
412
  \r
413
413
  ${JSON.stringify(r)}\r
@@ -416,7 +416,7 @@ Content-Type: ${e}\r
416
416
  \r
417
417
  `,"utf8"),t,Buffer.from(`\r
418
418
  --${n}--\r
419
- `,"utf8")]),contentType:`multipart/related; boundary=${n}`}}var ii=r=>{let t=typeof r?.markdown=="string"?r.markdown:null,e=typeof r?.text=="string"?r.text:null;return t??e},oi={id:"google-docs",callsBackend:!0,serverName:"gdocs",allowedTools:["mcp__gdocs__*"],requiresIntegration:I.GOOGLE,description:"Google Docs \u2014 create, append to, insert images into, and read Google Docs (drive.file scoped)",promptFragment:`## Google Docs
419
+ `,"utf8")]),contentType:`multipart/related; boundary=${n}`}}var bi=r=>{let t=typeof r?.markdown=="string"?r.markdown:null,e=typeof r?.text=="string"?r.text:null;return t??e},ki={id:"google-docs",callsBackend:!0,serverName:"gdocs",allowedTools:["mcp__gdocs__*"],requiresIntegration:I.GOOGLE,description:"Google Docs \u2014 create, append to, insert images into, and read Google Docs (drive.file scoped)",promptFragment:`## Google Docs
420
420
  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.
421
421
  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.
422
422
  - 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.
@@ -424,17 +424,17 @@ Docs access is PER-USER: each teammate connects their OWN Google account (Integr
424
424
  - 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 }.
425
425
  - gdocs_get: read a doc back as plain text (works for app-created/user-picked docs only; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker \u2014 drive.file has no access to un-picked files).
426
426
  - gdocs_list_created: list the Google Docs visible to this app (drive.file \u2192 only docs it created or the user picked).
427
- 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=Nl();if(!r)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/googleDocs.js","googleDocsSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"gdocs_create_doc":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let i=(await ie(`${Se}/documents`,{method:"POST",body:{title:e}}))?.documentId;if(!i)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=ii(t);if(s&&s.trim()){let{requests:o}=ni(s,1);o.length&&await ie(`${Se}/documents/${i}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:i,title:e,url:rt(i)})}case"gdocs_append":{let e=yr(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=ii(t);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await ie(`${Se}/documents/${e}`))?.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:`
428
- `}}),l=c+1);let p=ni(n,l);return d.push(...p.requests),await ie(`${Se}/documents/${e}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:e,url:rt(e)})}case"gdocs_insert_image":{let e=yr(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!t?.imagePath||typeof t.imagePath!="string"||!t.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:n,fileName:i,mimeType:s}=Cl(t.imagePath),{rawBody:o,contentType:a}=Ul({name:i,mimeType:s},n,s),d=(await ie(`${Ol}/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 ie(`${ri}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await ie(`${Se}/documents/${e}`),p=Array.isArray(l?.body?.content)?l.body.content:[],u=p.length&&p[p.length-1].endIndex||2,f={location:{index:Math.max(1,u-1)},uri:`https://drive.google.com/uc?export=download&id=${d}`},h=Number(t?.width),b=Number(t?.height);return(Number.isFinite(h)&&h>0||Number.isFinite(b)&&b>0)&&(f.objectSize={...Number.isFinite(h)&&h>0?{width:{magnitude:h,unit:"PT"}}:{},...Number.isFinite(b)&&b>0?{height:{magnitude:b,unit:"PT"}}:{}}),await ie(`${Se}/documents/${e}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:e,fileId:d,url:rt(e)})}case"gdocs_get":{let e=yr(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=await ie(`${Se}/documents/${e}`),i=Pl(n?.body);return JSON.stringify({ok:!0,documentId:e,title:n?.title||"",url:rt(e),text:i,...i.length>=gr?{truncated:!0}:{}})}case"gdocs_list_created":{let e=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(xl),orderBy:"modifiedTime desc"}),n=await ie(`${ri}/files?${e.toString()}`),i=(Array.isArray(n?.files)?n.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||rt(s.id)}));return JSON.stringify({ok:!0,count:i.length,files:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). The drive.file scope grants access ONLY to docs this app created or the user explicitly picked; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker (drive.file cannot see un-picked files). Returns { ok, documentId, title, url, text }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."}},required:["documentId"]}},{name:"gdocs_list_created",description:"List the Google Docs visible to this integration, newest first (max 25). NOTE: under the drive.file scope this lists ONLY docs the app created or the user explicitly picked \u2014 it is NOT a full Drive search. Returns { ok, count, files:[{ documentId, title, modifiedTime, url }] }.",input_schema:{type:"object",properties:{}}}]};import{existsSync as pi,statSync as Bl,readFileSync as Jl}from"fs";import{fileURLToPath as ql}from"url";import{basename as Dl,dirname as Ml,resolve as Kl}from"path";import{resolveIntegrationToken as ai}from"@zibby/core/backend-client.js";function Gl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ml(ql(import.meta.url)),t=Kl(r,"..","bin","mcp-skill.mjs");return pi(t)?t:null}var ci=2e4,li=50,Fl=50,Hl=20,zl=10*1024*1024,Yl=6e3*1e3,nt=null,Wl="https://open.larksuite.com",ui=Object.freeze([Object.freeze({appId:"LARK_DOCS_APP_ID",appSecret:"LARK_DOCS_APP_SECRET",host:"LARK_DOCS_HOST"}),Object.freeze({appId:"LARK_APP_ID",appSecret:"LARK_APP_SECRET",host:"LARK_HOST"})]),Zl=Object.freeze(ui.flatMap(r=>[r.appId,r.appSecret,r.host]));function wr(r){let t=String(r||"").trim().replace(/\/+$/,"");return t?/^https?:\/\//i.test(t)?t:`https://${t}`:Wl}function Vl(r){let t=String(process.env[r.appId]||"").trim(),e=String(process.env[r.appSecret]||"").trim();return!t||!e?null:{appId:t,appSecret:e,host:wr(process.env[r.host])}}async function Xl(){for(let r of ui){let t=Vl(r);if(t)return t}try{let r=await ai(I.LARK_DOCS);return{appId:r?.appId,appSecret:r?.appSecret,host:wr(r?.host)}}catch(r){if(!/unknown provider/i.test(String(r?.message||"")))throw r;let t=await ai(I.LARK);return{appId:t?.appId,appSecret:t?.appSecret,host:wr(t?.host)}}}async function mi(){let{appId:r,appSecret:t,host:e}=await Xl();if(nt&&nt.appId===r&&nt.expiresAt>Date.now())return{token:nt.token,host:e};let i=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:t})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return nt={token:i.tenant_access_token,expiresAt:Date.now()+Yl,appId:r},{token:i.tenant_access_token,host:e}}async function z(r,t,e){let{token:n,host:i}=await mi(),s={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&e!==void 0&&(s.body=JSON.stringify(e));let a=await(await fetch(`${i}${t}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${t} error: ${a.msg||a.code}`);return{data:a.data||{},host:i}}function it(r,t){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${t}`:`https://www.larksuite.com/docx/${t}`}function Ql(r,t){return String(r||"").includes("feishu")?`https://feishu.cn/wiki/${t}`:`https://www.larksuite.com/wiki/${t}`}function ve(r){if(!r||typeof r!="string")return null;let t=r.trim();if(!t)return null;let e=t.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return e?{type:e[1],token:e[2]}:/^[A-Za-z0-9]{10,}$/.test(t)?{type:"docx",token:t}:null}async function Je(r){let t=typeof r=="string"?ve(r):r;if(!t)throw new Error("A valid Lark doc id or URL is required");if(t.type==="docx")return t.token;let{data:e}=await z("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(t.token)}`),n=e?.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 _r(r){let t=String(r??"").replace(/\r\n/g,`
427
+ 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=ed();if(!r)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/googleDocs.js","googleDocsSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"gdocs_create_doc":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let i=(await se(`${Te}/documents`,{method:"POST",body:{title:e}}))?.documentId;if(!i)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=bi(t);if(s&&s.trim()){let{requests:o}=gi(s,1);o.length&&await se(`${Te}/documents/${i}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:i,title:e,url:ct(i)})}case"gdocs_append":{let e=Tr(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=bi(t);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await se(`${Te}/documents/${e}`))?.body,o=Array.isArray(s?.content)?s.content:[],a=o.length&&o[o.length-1].endIndex||2,c=Math.max(1,a-1),l=[],d=c;c>1&&(l.push({insertText:{location:{index:c},text:`
428
+ `}}),d=c+1);let p=gi(n,d);return l.push(...p.requests),await se(`${Te}/documents/${e}:batchUpdate`,{method:"POST",body:{requests:l}}),JSON.stringify({ok:!0,documentId:e,url:ct(e)})}case"gdocs_insert_image":{let e=Tr(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!t?.imagePath||typeof t.imagePath!="string"||!t.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:n,fileName:i,mimeType:s}=pd(t.imagePath),{rawBody:o,contentType:a}=ud({name:i,mimeType:s},n,s),l=(await se(`${td}/files?uploadType=multipart&fields=id`,{method:"POST",rawBody:o,contentType:a}))?.id;if(!l)return JSON.stringify({ok:!1,error:"Drive upload returned no file id"});await se(`${yi}/files/${l}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let d=await se(`${Te}/documents/${e}`),p=Array.isArray(d?.body?.content)?d.body.content:[],u=p.length&&p[p.length-1].endIndex||2,f={location:{index:Math.max(1,u-1)},uri:`https://drive.google.com/uc?export=download&id=${l}`},h=Number(t?.width),_=Number(t?.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 se(`${Te}/documents/${e}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:e,fileId:l,url:ct(e)})}case"gdocs_get":{let e=Tr(t?.documentId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=await se(`${Te}/documents/${e}`),i=dd(n?.body);return JSON.stringify({ok:!0,documentId:e,title:n?.title||"",url:ct(e),text:i,...i.length>=Rr?{truncated:!0}:{}})}case"gdocs_list_created":{let e=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(ad),orderBy:"modifiedTime desc"}),n=await se(`${yi}/files?${e.toString()}`),i=(Array.isArray(n?.files)?n.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||ct(s.id)}));return JSON.stringify({ok:!0,count:i.length,files:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). The drive.file scope grants access ONLY to docs this app created or the user explicitly picked; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker (drive.file cannot see un-picked files). Returns { ok, documentId, title, url, text }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."}},required:["documentId"]}},{name:"gdocs_list_created",description:"List the Google Docs visible to this integration, newest first (max 25). NOTE: under the drive.file scope this lists ONLY docs the app created or the user explicitly picked \u2014 it is NOT a full Drive search. Returns { ok, count, files:[{ documentId, title, modifiedTime, url }] }.",input_schema:{type:"object",properties:{}}}]};import{existsSync as Ni,statSync as md,readFileSync as fd}from"fs";import{fileURLToPath as hd}from"url";import{basename as yd,dirname as gd,resolve as bd}from"path";import{resolveIntegrationToken as wi}from"@zibby/core/backend-client.js";function _d(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=gd(hd(import.meta.url)),t=bd(r,"..","bin","mcp-skill.mjs");return Ni(t)?t:null}var Si=2e4,vi=50,kd=50,wd=20,Sd=10*1024*1024,vd=6e3*1e3,lt=null,Id="https://open.larksuite.com",Oi=Object.freeze([Object.freeze({appId:"LARK_DOCS_APP_ID",appSecret:"LARK_DOCS_APP_SECRET",host:"LARK_DOCS_HOST"}),Object.freeze({appId:"LARK_APP_ID",appSecret:"LARK_APP_SECRET",host:"LARK_HOST"})]),Nd=Object.freeze(Oi.flatMap(r=>[r.appId,r.appSecret,r.host]));function jr(r){let t=String(r||"").trim().replace(/\/+$/,"");return t?/^https?:\/\//i.test(t)?t:`https://${t}`:Id}function Od(r){let t=String(process.env[r.appId]||"").trim(),e=String(process.env[r.appSecret]||"").trim();return!t||!e?null:{appId:t,appSecret:e,host:jr(process.env[r.host])}}async function Td(){for(let r of Oi){let t=Od(r);if(t)return t}try{let r=await wi(I.LARK_DOCS);return{appId:r?.appId,appSecret:r?.appSecret,host:jr(r?.host)}}catch(r){if(!/unknown provider/i.test(String(r?.message||"")))throw r;let t=await wi(I.LARK);return{appId:t?.appId,appSecret:t?.appSecret,host:jr(t?.host)}}}async function Ti(){let{appId:r,appSecret:t,host:e}=await Td();if(lt&&lt.appId===r&&lt.expiresAt>Date.now())return{token:lt.token,host:e};let i=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:t})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return lt={token:i.tenant_access_token,expiresAt:Date.now()+vd,appId:r},{token:i.tenant_access_token,host:e}}async function Y(r,t,e){let{token:n,host:i}=await Ti(),s={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&e!==void 0&&(s.body=JSON.stringify(e));let a=await(await fetch(`${i}${t}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${t} error: ${a.msg||a.code}`);return{data:a.data||{},host:i}}function dt(r,t){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${t}`:`https://www.larksuite.com/docx/${t}`}function Rd(r,t){return String(r||"").includes("feishu")?`https://feishu.cn/wiki/${t}`:`https://www.larksuite.com/wiki/${t}`}function Re(r){if(!r||typeof r!="string")return null;let t=r.trim();if(!t)return null;let e=t.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return e?{type:e[1],token:e[2]}:/^[A-Za-z0-9]{10,}$/.test(t)?{type:"docx",token:t}:null}async function Ke(r){let t=typeof r=="string"?Re(r):r;if(!t)throw new Error("A valid Lark doc id or URL is required");if(t.type==="docx")return t.token;let{data:e}=await Y("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(t.token)}`),n=e?.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 Ar(r){let t=String(r??"").replace(/\r\n/g,`
429
429
  `),e=[];for(let n of t.split(`
430
- `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d,l;if(s){let p=s[1].length;c=`heading${p}`,d=2+p,l=s[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=i);e.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return e}function st(r){let t=typeof r?.markdown=="string"?r.markdown:null,e=typeof r?.text=="string"?r.text:null;return t??e}async function br(r,t){let e;for(let n=0;n<t.length;n+=li){let i=t.slice(n,n+li);e=(await z("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:i})).host}return e}function ed(r){let t=typeof r=="string"?r.trim():"";if(!t)throw new Error("imagePath is required");if(!pi(t)||!Bl(t).isFile())throw new Error(`imagePath not found (or not a file): ${t}`);if(!/\.(png|jpe?g)$/i.test(t))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let e=Jl(t);if(e.length>zl)throw new Error(`image is ${(e.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return e}async function td({fileName:r,parentNode:t,bytes:e}){let{token:n,host:i}=await mi(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",t),s.set("size",String(e.length)),s.set("file",new Blob([e]),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 rd="docx",nd=50;function di(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function id(r){return Array.isArray(r)?r.map(t=>t?.text_run?.text??t?.docs_link?.url??(t?.person?`@${t.person.user_id||""}`:"")).join(""):""}function sd(r){let t=Array.isArray(r?.reply_list?.replies)?r.reply_list.replies:[];return{commentId:r?.comment_id||"",resolved:!!r?.is_solved,replies:t.map(e=>({replyId:e?.reply_id||"",author:e?.user_id||"",text:id(e?.content?.elements),createTime:e?.create_time||""}))}}function kr(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():rd}var fi={id:"lark-docs",callsBackend:!0,serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:[I.LARK_DOCS,I.LARK],description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV",...Zl],promptFragment:'## Lark Docs\nYou can read, create, and append Lark/Feishu documents (docx), and read/post/reply to their comments. This runs on the connected Lark Docs app (the chat app is used when no separate docs app is connected). Each `larkdoc_*` / `larkwiki_*` tool documents its own params and return shape in its tool description \u2014 they are not restated here.\nThese 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=Gl();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"larkdoc_get":{let e=t?.documentId||t?.url||t?.id,n=ve(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Je(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>ci&&(c=c.slice(0,ci),d=!0),JSON.stringify({ok:!0,documentId:i,title:s,url:it(a,i),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let n=typeof t?.wikiSpaceId=="string"&&t.wikiSpaceId.trim()?t.wikiSpaceId.trim():null;if(n){let c=typeof t?.parentNodeToken=="string"&&t.parentNodeToken.trim()?t.parentNodeToken.trim():null,{data:d,host:l}=await z("POST",`/open-apis/wiki/v2/spaces/${encodeURIComponent(n)}/nodes`,{obj_type:"docx",node_type:"origin",title:e,...c?{parent_node_token:c}:{}}),p=d?.node||{},u=p.obj_token;if(!u)return JSON.stringify({ok:!1,error:"Lark wiki node create returned no obj_token"});let m=st(t);if(m&&m.trim()){let f=_r(m);f.length&&await br(u,f)}return JSON.stringify({ok:!0,documentId:u,title:e,wikiSpaceId:n,wikiNodeToken:p.node_token||"",url:p.node_token?Ql(l,p.node_token):it(l,u)})}let{data:i,host:s}=await z("POST","/open-apis/docx/v1/documents",{title:e,...t?.folderToken?{folder_token:String(t.folderToken)}:{}}),o=i?.document?.document_id;if(!o)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let a=st(t);if(a&&a.trim()){let c=_r(a);c.length&&await br(o,c)}return JSON.stringify({ok:!0,documentId:o,title:e,url:it(s,o)})}case"larkdoc_append":{let e=t?.documentId||t?.url||t?.id,n=ve(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=st(t);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Je(n),o=_r(i);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await br(s,o);return JSON.stringify({ok:!0,documentId:s,url:it(a,s)})}case"larkdoc_insert_image":{let e=t?.documentId||t?.url||t?.id,n=ve(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!t?.imagePath||typeof t.imagePath!="string"||!t.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let i=await Je(n),s=t.imagePath.trim(),o=ed(s),a=Dl(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 td({fileName:a,parentNode:d,bytes:o}),p={token:l},u=Number(t?.width),m=Number(t?.height);Number.isFinite(u)&&u>0&&(p.width=Math.round(u)),Number.isFinite(m)&&m>0&&(p.height=Math.round(m));let{host:f}=await z("PATCH",`/open-apis/docx/v1/documents/${i}/blocks/${d}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:i,blockId:d,fileToken:l,url:it(f,i)})}case"larkwiki_list_spaces":{let e=[],n=null;for(let i=0;i<Hl;i++){let s=new URLSearchParams({page_size:String(Fl)});n&&s.set("page_token",n);let{data:o}=await z("GET",`/open-apis/wiki/v2/spaces?${s.toString()}`),a=Array.isArray(o?.items)?o.items:[];for(let c of a)e.push({spaceId:String(c?.space_id||""),name:String(c?.name||"")});if(!o?.has_more||!o?.page_token)break;n=o.page_token}return JSON.stringify({ok:!0,count:e.length,spaces:e})}case"larkdoc_list_comments":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,n=ve(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Je(n),s=kr(t),o=new URLSearchParams({file_type:s,page_size:String(nd)}),{data:a}=await z("GET",`/open-apis/drive/v1/files/${i}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(sd);return JSON.stringify({ok:!0,documentId:i,count:d.length,comments:d})}case"larkdoc_add_comment":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,n=ve(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=st({text:t?.text??t?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Je(n),o=kr(t),{data:a}=await z("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:di(i)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,n=ve(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=t?.commentId||t?.comment_id;if(!i)return JSON.stringify({ok:!1,error:"commentId is required"});let s=st({text:t?.text??t?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Je(n),a=kr(t),{data:c}=await z("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(i)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:di(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(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Pass wikiSpaceId (from larkwiki_list_spaces) to create the doc INSIDE a wiki space instead of as a standalone doc \u2014 optionally nested under parentNodeToken. Returns { ok, documentId, url } (plus wikiNodeToken when created in a wiki) \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. Ignored when wikiSpaceId is set."},wikiSpaceId:{type:"string",description:"Optional wiki space id (from larkwiki_list_spaces) \u2014 create the doc as a node inside this wiki space."},parentNodeToken:{type:"string",description:"Optional wiki node token to nest the new doc under (only with wikiSpaceId). Absent = the space root."}},required:["title"]}},{name:"larkwiki_list_spaces",description:"List the Lark/Feishu wiki spaces visible to the connected app. Returns { ok, count, spaces:[{ spaceId, name }] }. Use to discover the wikiSpaceId for larkdoc_create.",input_schema:{type:"object",properties:{}}},{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 hi={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||[],...M.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return P.serverName;if(process.env.LARK_RECEIVE_ID)return M.serverName;if(process.env.SLACK_BOT_TOKEN)return P.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?P.allowedTools||[]:process.env.LARK_RECEIVE_ID?M.allowedTools||[]:process.env.SLACK_BOT_TOKEN?P.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
430
+ `)){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,l,d;if(s){let p=s[1].length;c=`heading${p}`,l=2+p,d=s[2]}else o?(c="bullet",l=12,d=o[1]):a?(c="ordered",l=13,d=a[1]):(c="text",l=2,d=i);e.push({block_type:l,[c]:{elements:[{text_run:{content:d}}],style:{}}})}return e}function pt(r){let t=typeof r?.markdown=="string"?r.markdown:null,e=typeof r?.text=="string"?r.text:null;return t??e}async function Er(r,t){let e;for(let n=0;n<t.length;n+=vi){let i=t.slice(n,n+vi);e=(await Y("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:i})).host}return e}function Ad(r){let t=typeof r=="string"?r.trim():"";if(!t)throw new Error("imagePath is required");if(!Ni(t)||!md(t).isFile())throw new Error(`imagePath not found (or not a file): ${t}`);if(!/\.(png|jpe?g)$/i.test(t))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let e=fd(t);if(e.length>Sd)throw new Error(`image is ${(e.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return e}async function Ed({fileName:r,parentNode:t,bytes:e}){let{token:n,host:i}=await Ti(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",t),s.set("size",String(e.length)),s.set("file",new Blob([e]),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 xd="docx",jd=50;function Ii(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function Ld(r){return Array.isArray(r)?r.map(t=>t?.text_run?.text??t?.docs_link?.url??(t?.person?`@${t.person.user_id||""}`:"")).join(""):""}function $d(r){let t=Array.isArray(r?.reply_list?.replies)?r.reply_list.replies:[];return{commentId:r?.comment_id||"",resolved:!!r?.is_solved,replies:t.map(e=>({replyId:e?.reply_id||"",author:e?.user_id||"",text:Ld(e?.content?.elements),createTime:e?.create_time||""}))}}function xr(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():xd}var Ri={id:"lark-docs",callsBackend:!0,serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:[I.LARK_DOCS,I.LARK],description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV",...Nd],promptFragment:'## Lark Docs\nYou can read, create, and append Lark/Feishu documents (docx), and read/post/reply to their comments. This runs on the connected Lark Docs app (the chat app is used when no separate docs app is connected). Each `larkdoc_*` / `larkwiki_*` tool documents its own params and return shape in its tool description \u2014 they are not restated here.\nThese 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=_d();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"larkdoc_get":{let e=t?.documentId||t?.url||t?.id,n=Re(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ke(n),s="";try{s=(await Y("GET",`/open-apis/docx/v1/documents/${i}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await Y("GET",`/open-apis/docx/v1/documents/${i}/raw_content?lang=0`),c=String(o?.content||""),l=!1;return c.length>Si&&(c=c.slice(0,Si),l=!0),JSON.stringify({ok:!0,documentId:i,title:s,url:dt(a,i),text:c,...l?{truncated:!0}:{}})}case"larkdoc_create":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let n=typeof t?.wikiSpaceId=="string"&&t.wikiSpaceId.trim()?t.wikiSpaceId.trim():null;if(n){let c=typeof t?.parentNodeToken=="string"&&t.parentNodeToken.trim()?t.parentNodeToken.trim():null,{data:l,host:d}=await Y("POST",`/open-apis/wiki/v2/spaces/${encodeURIComponent(n)}/nodes`,{obj_type:"docx",node_type:"origin",title:e,...c?{parent_node_token:c}:{}}),p=l?.node||{},u=p.obj_token;if(!u)return JSON.stringify({ok:!1,error:"Lark wiki node create returned no obj_token"});let m=pt(t);if(m&&m.trim()){let f=Ar(m);f.length&&await Er(u,f)}return JSON.stringify({ok:!0,documentId:u,title:e,wikiSpaceId:n,wikiNodeToken:p.node_token||"",url:p.node_token?Rd(d,p.node_token):dt(d,u)})}let{data:i,host:s}=await Y("POST","/open-apis/docx/v1/documents",{title:e,...t?.folderToken?{folder_token:String(t.folderToken)}:{}}),o=i?.document?.document_id;if(!o)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let a=pt(t);if(a&&a.trim()){let c=Ar(a);c.length&&await Er(o,c)}return JSON.stringify({ok:!0,documentId:o,title:e,url:dt(s,o)})}case"larkdoc_append":{let e=t?.documentId||t?.url||t?.id,n=Re(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=pt(t);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Ke(n),o=Ar(i);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await Er(s,o);return JSON.stringify({ok:!0,documentId:s,url:dt(a,s)})}case"larkdoc_insert_image":{let e=t?.documentId||t?.url||t?.id,n=Re(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!t?.imagePath||typeof t.imagePath!="string"||!t.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let i=await Ke(n),s=t.imagePath.trim(),o=Ad(s),a=yd(s),l=(await Y("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(!l)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let d=await Ed({fileName:a,parentNode:l,bytes:o}),p={token:d},u=Number(t?.width),m=Number(t?.height);Number.isFinite(u)&&u>0&&(p.width=Math.round(u)),Number.isFinite(m)&&m>0&&(p.height=Math.round(m));let{host:f}=await Y("PATCH",`/open-apis/docx/v1/documents/${i}/blocks/${l}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:i,blockId:l,fileToken:d,url:dt(f,i)})}case"larkwiki_list_spaces":{let e=[],n=null;for(let i=0;i<wd;i++){let s=new URLSearchParams({page_size:String(kd)});n&&s.set("page_token",n);let{data:o}=await Y("GET",`/open-apis/wiki/v2/spaces?${s.toString()}`),a=Array.isArray(o?.items)?o.items:[];for(let c of a)e.push({spaceId:String(c?.space_id||""),name:String(c?.name||"")});if(!o?.has_more||!o?.page_token)break;n=o.page_token}return JSON.stringify({ok:!0,count:e.length,spaces:e})}case"larkdoc_list_comments":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,n=Re(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ke(n),s=xr(t),o=new URLSearchParams({file_type:s,page_size:String(jd)}),{data:a}=await Y("GET",`/open-apis/drive/v1/files/${i}/comments?${o.toString()}`),l=(Array.isArray(a?.items)?a.items:[]).map($d);return JSON.stringify({ok:!0,documentId:i,count:l.length,comments:l})}case"larkdoc_add_comment":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,n=Re(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=pt({text:t?.text??t?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Ke(n),o=xr(t),{data:a}=await Y("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:Ii(i)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,n=Re(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=t?.commentId||t?.comment_id;if(!i)return JSON.stringify({ok:!1,error:"commentId is required"});let s=pt({text:t?.text??t?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Ke(n),a=xr(t),{data:c}=await Y("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(i)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:Ii(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(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Pass wikiSpaceId (from larkwiki_list_spaces) to create the doc INSIDE a wiki space instead of as a standalone doc \u2014 optionally nested under parentNodeToken. Returns { ok, documentId, url } (plus wikiNodeToken when created in a wiki) \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. Ignored when wikiSpaceId is set."},wikiSpaceId:{type:"string",description:"Optional wiki space id (from larkwiki_list_spaces) \u2014 create the doc as a node inside this wiki space."},parentNodeToken:{type:"string",description:"Optional wiki node token to nest the new doc under (only with wikiSpaceId). Absent = the space root."}},required:["title"]}},{name:"larkwiki_list_spaces",description:"List the Lark/Feishu wiki spaces visible to the connected app. Returns { ok, count, spaces:[{ spaceId, name }] }. Use to discover the wikiSpaceId for larkdoc_create.",input_schema:{type:"object",properties:{}}},{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 Ai={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||[],...F.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return P.serverName;if(process.env.LARK_RECEIVE_ID)return F.serverName;if(process.env.SLACK_BOT_TOKEN)return P.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?P.allowedTools||[]:process.env.LARK_RECEIVE_ID?F.allowedTools||[]:process.env.SLACK_BOT_TOKEN?P.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
431
431
  You can post chat messages via:
432
432
  - slack_post_message (channel, text[, blocks]) \u2014 Slack. The \`channel\` is REQUIRED on every call.
433
433
  - lark_send_message (receive_id, text) \u2014 Lark.
434
434
  Where to post:
435
435
  - If SLACK_CHANNEL / LARK_RECEIVE_ID is set, that is the default destination \u2014 use it.
436
436
  - 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).
437
- - 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 M.resolve=="function"?M.resolve(r):process.env.SLACK_BOT_TOKEN&&typeof P.resolve=="function"?P.resolve(r):null},async handleToolCall(r,t,e){return typeof r=="string"&&r.startsWith("slack_")?P.handleToolCall(r,t,e):typeof r=="string"&&r.startsWith("lark_")?M.handleToolCall(r,t,e):JSON.stringify({error:`chat_notify: unknown tool "${r}". Expected slack_* or lark_*.`})},get tools(){return[...P.tools||[],...M.tools||[]]}};import{createRequire as od}from"module";import{execFileSync as ad}from"child_process";import{join as yi}from"path";import{existsSync as cd}from"fs";var ld=od(import.meta.url);function dd(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return ld.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var gi={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:
437
+ - 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 F.resolve=="function"?F.resolve(r):process.env.SLACK_BOT_TOKEN&&typeof P.resolve=="function"?P.resolve(r):null},async handleToolCall(r,t,e){return typeof r=="string"&&r.startsWith("slack_")?P.handleToolCall(r,t,e):typeof r=="string"&&r.startsWith("lark_")?F.handleToolCall(r,t,e):JSON.stringify({error:`chat_notify: unknown tool "${r}". Expected slack_* or lark_*.`})},get tools(){return[...P.tools||[],...F.tools||[]]}};import{createRequire as Pd}from"module";import{execFileSync as Cd}from"child_process";import{join as Ei}from"path";import{existsSync as Ud}from"fs";var Bd=Pd(import.meta.url);function Jd(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return Bd.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var xi={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:
438
438
  - Review any test memory/history above. Prefer selectors proven to work.
439
439
  - If a previous run failed, avoid the same approach.
440
440
  - After setup/login completes, navigate directly to the target page instead of clicking through menus.
@@ -446,7 +446,7 @@ DURING execution \u2014 when a selector fails and you switch to a fallback:
446
446
  AFTER completing the test, you MUST call memory_save_insight at least once:
447
447
  - Save any useful finding: reliable selectors, timing quirks, navigation patterns, workarounds.
448
448
  - Category: selector_tip | timing | navigation | workaround | flaky | general
449
- - Be specific \u2014 future runs will read your insights.`,resolve(){let r=dd();if(!r)return console.warn("[memory] @zibby/ui-memory not found \u2014 memory tools disabled for this run"),null;let t=yi(process.cwd(),".zibby","memory");if(!cd(yi(t,".dolt")))return console.warn("[memory] DB/dolt unavailable \u2014 memory tools disabled for this run"),null;try{let e=ad("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:t,encoding:"utf-8",timeout:5e3}),n=JSON.parse(e.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(e){return console.warn(`[memory] DB/dolt unavailable \u2014 memory tools disabled for this run (${e.message})`),null}return{command:"node",args:[r,"--db-path",t],description:this.description}},tools:[{name:"memory_get_test_history",description:"Query recent test runs with pass/fail results and timing",input_schema:{type:"object",properties:{specPath:{type:"string",description:"Filter by spec path (substring match)"},limit:{type:"number",description:"Max results (default 10)"}}}},{name:"memory_get_selectors",description:"Query known selectors for a page with stability metrics",input_schema:{type:"object",properties:{pageUrl:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_page_model",description:"Query page structure \u2014 elements, roles, selectors",input_schema:{type:"object",properties:{url:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_navigation",description:"Query known page-to-page transitions",input_schema:{type:"object",properties:{fromUrl:{type:"string",description:"Filter by source URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_save_insight",description:"Save a useful observation for future runs (selector tips, timing, workarounds)",input_schema:{type:"object",properties:{category:{type:"string",enum:["selector_tip","timing","navigation","workaround","flaky","general"],description:"Type of insight"},content:{type:"string",description:"The insight text \u2014 be specific and actionable"},specPath:{type:"string",description:"Related spec path"},sessionId:{type:"string",description:"Current session ID"}},required:["category","content"]}}]};import{existsSync as pd,readFileSync as ud}from"fs";import{homedir as md}from"os";import{join as fd}from"path";import{spawn as hd}from"child_process";var Ie={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
449
+ - Be specific \u2014 future runs will read your insights.`,resolve(){let r=Jd();if(!r)return console.warn("[memory] @zibby/ui-memory not found \u2014 memory tools disabled for this run"),null;let t=Ei(process.cwd(),".zibby","memory");if(!Ud(Ei(t,".dolt")))return console.warn("[memory] DB/dolt unavailable \u2014 memory tools disabled for this run"),null;try{let e=Cd("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:t,encoding:"utf-8",timeout:5e3}),n=JSON.parse(e.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(e){return console.warn(`[memory] DB/dolt unavailable \u2014 memory tools disabled for this run (${e.message})`),null}return{command:"node",args:[r,"--db-path",t],description:this.description}},tools:[{name:"memory_get_test_history",description:"Query recent test runs with pass/fail results and timing",input_schema:{type:"object",properties:{specPath:{type:"string",description:"Filter by spec path (substring match)"},limit:{type:"number",description:"Max results (default 10)"}}}},{name:"memory_get_selectors",description:"Query known selectors for a page with stability metrics",input_schema:{type:"object",properties:{pageUrl:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_page_model",description:"Query page structure \u2014 elements, roles, selectors",input_schema:{type:"object",properties:{url:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_navigation",description:"Query known page-to-page transitions",input_schema:{type:"object",properties:{fromUrl:{type:"string",description:"Filter by source URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_save_insight",description:"Save a useful observation for future runs (selector tips, timing, workarounds)",input_schema:{type:"object",properties:{category:{type:"string",enum:["selector_tip","timing","navigation","workaround","flaky","general"],description:"Type of insight"},content:{type:"string",description:"The insight text \u2014 be specific and actionable"},specPath:{type:"string",description:"Related spec path"},sessionId:{type:"string",description:"Current session ID"}},required:["category","content"]}}]};import{existsSync as Dd,readFileSync as qd}from"fs";import{homedir as Md}from"os";import{join as Fd}from"path";import{spawn as Kd}from"child_process";var Ae={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
450
450
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
451
451
  2. Click "Connect Jira" and authorize via Atlassian OAuth
452
452
  3. After OAuth completes, ask me to install Jira again`},github:{description:"GitHub issues, PRs, repository management",integrationProvider:"github",envKeys:[],setupInstructions:`To connect GitHub:
@@ -458,17 +458,17 @@ AFTER completing the test, you MUST call memory_save_insight at least once:
458
458
  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:
459
459
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
460
460
  2. Click "Connect Sentry" and authorize
461
- 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 yd(){let r=["## Available Skills"];for(let[t,e]of Object.entries(Ie)){let n=e.integrationProvider?`integration: ${e.integrationProvider}`:"ready";r.push(`- ${t}: ${e.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: ${Sr()}`),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(`
462
- `)}function gd(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=fd(md(),".zibby","config.json");return pd(r)&&JSON.parse(ud(r,"utf-8")).sessionToken||null}catch{return null}}function _d(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function Sr(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function bd(r){try{let t=process.platform;return hd(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",r]:[r],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}async function kd(){let r=gd();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let t=await fetch(`${_d()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});return t.ok?{checked:!0,statuses:await t.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${t.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function _i(r,t){if(!t||!r)return{connected:null};let e=r[t];return!e||typeof e.connected!="boolean"?{connected:null,details:e||null}:{connected:e.connected,details:e}}var bi={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:Ie,promptFragment:yd,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,t,e){let{activeSkills:n}=e,i=await kd();if(r==="list_available_skills"){let s=Object.entries(Ie).map(([o,a])=>{let c=n.includes(o),d=_i(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}=t;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(n.includes(s)){let l=Ie[s],{getSkill:p}=await import("@zibby/agent-workflow"),m=(p(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?Sr():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!Ie[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(Ie).join(", ")}`});let o=Ie[s];if(o.integrationProvider){let l=_i(i.statuses,o.integrationProvider),p=Sr();if(i.checked&&l.connected===!1){let u=bd(p);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:p,openedBrowser:u,setupInstructions:`Please connect ${o.integrationProvider} first at ${p}. After you finish OAuth, ask me to install ${s} again.`})}}n.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(s)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:d,hint:`${s} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=t;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 wd,readdirSync as Sd,statSync as wi,writeFileSync as vd,mkdirSync as Id}from"fs";import{join as Si,resolve as Nd,relative as Od}from"path";import{execSync as vi}from"child_process";var ki=256*1024,Td=64*1024,Ii={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,t,e){let n=e?.options?.workspace||process.cwd();try{switch(r){case"read_file":return Ad(t,n);case"write_file":return Rd(t,n);case"list_directory":return Ed(t,n);case"run_command":return jd(t,n);case"open_url":return xd(t);case"wait":return await Ld(t,e?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function Pt(r,t){return Nd(t,r)}function Ad(r,t){let e=Pt(r.path,t),n=wi(e);return n.size>ki?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${ki/1024}KB`}):wd(e,"utf-8")}function Rd(r,t){let e=Pt(r.path,t),n=Si(e,"..");return Id(n,{recursive:!0}),vd(e,r.content,"utf-8"),JSON.stringify({ok:!0,path:Od(t,e)})}function Ed(r,t){let e=Pt(r.path||".",t);return Sd(e).map(i=>{try{return wi(Si(e,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
463
- `)}function jd(r,t){let e=r.cwd?Pt(r.cwd,t):t;return vi(r.command,{cwd:e,encoding:"utf-8",timeout:3e4,maxBuffer:Td,stdio:["pipe","pipe","pipe"]})||"(no output)"}function xd(r){let{url:t}=r;if(!t||!t.startsWith("http://")&&!t.startsWith("https://"))return JSON.stringify({error:"Invalid URL \u2014 must start with http:// or https://"});let e=process.platform,n=e==="darwin"?"open":e==="win32"?"start":"xdg-open";try{return vi(`${n} "${t}"`,{stdio:"ignore",timeout:5e3}),JSON.stringify({ok:!0,opened:t})}catch{return JSON.stringify({ok:!1,error:`Could not open browser. Please visit: ${t}`})}}async function Ld(r,t){let e=Math.min(Math.max(r.seconds||5,1),300),n=r.reason||"async operation",i=500,s=Date.now()+e*1e3;for(;Date.now()<s;){if(t?.aborted)return JSON.stringify({ok:!0,waited:Math.round((e*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:e,reason:n})}import{existsSync as $d}from"fs";import{fileURLToPath as Pd}from"url";import{dirname as Cd,resolve as Ud}from"path";import{resolveIntegrationToken as ot}from"@zibby/core/backend-client.js";function Bd(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=Cd(Pd(import.meta.url)),t=Ud(r,"..","bin","mcp-sentry.mjs");return $d(t)?t:null}function at(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Ni(r){let t=r||process.env.SENTRY_ORG;if(!t)throw new Error('Sentry organization not resolved \u2014 reconnect Sentry, or set SENTRY_ORG (self-hosted; the default org slug is "sentry").');return t}async function Oi(r,t={}){let{token:e,organizationSlug:n,baseUrl:i}=await ot("sentry"),s=`${at(i)}/api/0/organizations/${Ni(n)}${r}`,o={method:t.method||"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}};t.body!=null&&(o.body=typeof t.body=="string"?t.body:JSON.stringify(t.body));let a=await fetch(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 Jd(){return Oi("/projects/?per_page=50")}async function qd({query:r="is:unresolved",sort:t="date",project:e,limit:n=25}={}){let i=`/issues/?query=${encodeURIComponent(r)}&sort=${t}&per_page=${n}`;return e&&(i+=`&project=${encodeURIComponent(e)}`),Oi(i)}async function vr(r){let t=String(r??"").trim();if(!t)throw new Error("resolveSentryIssueId: issueRef is required");if(/^\d+$/.test(t))return t;let{token:e,organizationSlug:n,baseUrl:i}=await ot("sentry"),s=await fetch(`${at(i)}/api/0/organizations/${Ni(n)}/shortids/${encodeURIComponent(t)}/`,{headers:{Authorization:`Bearer ${e}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status} resolving shortId "${t}": ${c.slice(0,200)}`)}let o=await s.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${t}" did not resolve to a numeric issue id`);return String(a)}async function Dd(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let t=await vr(r),{token:e,baseUrl:n}=await ot("sentry"),i=await fetch(`${at(n)}/api/0/issues/${t}/`,{headers:{Authorization:`Bearer ${e}`}});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 Md(r,t={}){if(!r)throw new Error("sentryUpdateIssue: issueId is required");let e={};for(let a of["status","statusDetails","assignedTo","isBookmarked","hasSeen"])t[a]!==void 0&&(e[a]=t[a]);if(Object.keys(e).length===0)throw new Error("sentryUpdateIssue: nothing to update (pass status / statusDetails / assignedTo / isBookmarked / hasSeen)");let n=await vr(r),{token:i,baseUrl:s}=await ot("sentry"),o=await fetch(`${at(s)}/api/0/issues/${n}/`,{method:"PUT",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(e)});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 Kd(r,t){if(!r)throw new Error("sentryAddComment: issueId is required");if(!t||!String(t).trim())throw new Error("sentryAddComment: text is required");let e=await vr(r),{token:n,baseUrl:i}=await ot("sentry"),s=await fetch(`${at(i)}/api/0/issues/${e}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(t)})});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 Ct={id:"sentry",callsBackend:!0,serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:I.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry
461
+ 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 Gd(){let r=["## Available Skills"];for(let[t,e]of Object.entries(Ae)){let n=e.integrationProvider?`integration: ${e.integrationProvider}`:"ready";r.push(`- ${t}: ${e.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: ${Lr()}`),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(`
462
+ `)}function Hd(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=Fd(Md(),".zibby","config.json");return Dd(r)&&JSON.parse(qd(r,"utf-8")).sessionToken||null}catch{return null}}function zd(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function Lr(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function Yd(r){try{let t=process.platform;return Kd(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",r]:[r],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}async function Wd(){let r=Hd();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let t=await fetch(`${zd()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});return t.ok?{checked:!0,statuses:await t.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${t.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function ji(r,t){if(!t||!r)return{connected:null};let e=r[t];return!e||typeof e.connected!="boolean"?{connected:null,details:e||null}:{connected:e.connected,details:e}}var Li={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:Ae,promptFragment:Gd,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,t,e){let{activeSkills:n}=e,i=await Wd();if(r==="list_available_skills"){let s=Object.entries(Ae).map(([o,a])=>{let c=n.includes(o),l=ji(i.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:l.connected,setupInstructions:l.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:s})}if(r==="install_skill"){let{skillId:s}=t;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(n.includes(s)){let d=Ae[s],{getSkill:p}=await import("@zibby/agent-workflow"),m=(p(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:d?.description,availableTools:m,integrationUrl:d?.integrationProvider?Lr():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!Ae[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(Ae).join(", ")}`});let o=Ae[s];if(o.integrationProvider){let d=ji(i.statuses,o.integrationProvider),p=Lr();if(i.checked&&d.connected===!1){let u=Yd(p);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:p,openedBrowser:u,setupInstructions:`Please connect ${o.integrationProvider} first at ${p}. After you finish OAuth, ask me to install ${s} again.`})}}n.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),l=(a(s)?.tools||[]).map(d=>d.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:l,hint:`${s} is now active. You now have these tools: ${l.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=t;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 Zd,readdirSync as Vd,statSync as Pi,writeFileSync as Xd,mkdirSync as Qd}from"fs";import{join as Ci,resolve as ep,relative as tp}from"path";import{execSync as Ui}from"child_process";var $i=256*1024,rp=64*1024,Bi={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,t,e){let n=e?.options?.workspace||process.cwd();try{switch(r){case"read_file":return np(t,n);case"write_file":return ip(t,n);case"list_directory":return sp(t,n);case"run_command":return op(t,n);case"open_url":return ap(t);case"wait":return await cp(t,e?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function Kt(r,t){return ep(t,r)}function np(r,t){let e=Kt(r.path,t),n=Pi(e);return n.size>$i?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${$i/1024}KB`}):Zd(e,"utf-8")}function ip(r,t){let e=Kt(r.path,t),n=Ci(e,"..");return Qd(n,{recursive:!0}),Xd(e,r.content,"utf-8"),JSON.stringify({ok:!0,path:tp(t,e)})}function sp(r,t){let e=Kt(r.path||".",t);return Vd(e).map(i=>{try{return Pi(Ci(e,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
463
+ `)}function op(r,t){let e=r.cwd?Kt(r.cwd,t):t;return Ui(r.command,{cwd:e,encoding:"utf-8",timeout:3e4,maxBuffer:rp,stdio:["pipe","pipe","pipe"]})||"(no output)"}function ap(r){let{url:t}=r;if(!t||!t.startsWith("http://")&&!t.startsWith("https://"))return JSON.stringify({error:"Invalid URL \u2014 must start with http:// or https://"});let e=process.platform,n=e==="darwin"?"open":e==="win32"?"start":"xdg-open";try{return Ui(`${n} "${t}"`,{stdio:"ignore",timeout:5e3}),JSON.stringify({ok:!0,opened:t})}catch{return JSON.stringify({ok:!1,error:`Could not open browser. Please visit: ${t}`})}}async function cp(r,t){let e=Math.min(Math.max(r.seconds||5,1),300),n=r.reason||"async operation",i=500,s=Date.now()+e*1e3;for(;Date.now()<s;){if(t?.aborted)return JSON.stringify({ok:!0,waited:Math.round((e*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:e,reason:n})}import{existsSync as lp}from"fs";import{fileURLToPath as dp}from"url";import{dirname as pp,resolve as up}from"path";import{resolveIntegrationToken as ut}from"@zibby/core/backend-client.js";function mp(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=pp(dp(import.meta.url)),t=up(r,"..","bin","mcp-sentry.mjs");return lp(t)?t:null}function mt(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Ji(r){let t=r||process.env.SENTRY_ORG;if(!t)throw new Error('Sentry organization not resolved \u2014 reconnect Sentry, or set SENTRY_ORG (self-hosted; the default org slug is "sentry").');return t}async function Di(r,t={}){let{token:e,organizationSlug:n,baseUrl:i}=await ut("sentry"),s=`${mt(i)}/api/0/organizations/${Ji(n)}${r}`,o={method:t.method||"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}};t.body!=null&&(o.body=typeof t.body=="string"?t.body:JSON.stringify(t.body));let a=await fetch(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 fp(){return Di("/projects/?per_page=50")}async function hp({query:r="is:unresolved",sort:t="date",project:e,limit:n=25}={}){let i=`/issues/?query=${encodeURIComponent(r)}&sort=${t}&per_page=${n}`;return e&&(i+=`&project=${encodeURIComponent(e)}`),Di(i)}async function $r(r){let t=String(r??"").trim();if(!t)throw new Error("resolveSentryIssueId: issueRef is required");if(/^\d+$/.test(t))return t;let{token:e,organizationSlug:n,baseUrl:i}=await ut("sentry"),s=await fetch(`${mt(i)}/api/0/organizations/${Ji(n)}/shortids/${encodeURIComponent(t)}/`,{headers:{Authorization:`Bearer ${e}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status} resolving shortId "${t}": ${c.slice(0,200)}`)}let o=await s.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${t}" did not resolve to a numeric issue id`);return String(a)}async function yp(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let t=await $r(r),{token:e,baseUrl:n}=await ut("sentry"),i=await fetch(`${mt(n)}/api/0/issues/${t}/`,{headers:{Authorization:`Bearer ${e}`}});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 gp(r,t={}){if(!r)throw new Error("sentryUpdateIssue: issueId is required");let e={};for(let a of["status","statusDetails","assignedTo","isBookmarked","hasSeen"])t[a]!==void 0&&(e[a]=t[a]);if(Object.keys(e).length===0)throw new Error("sentryUpdateIssue: nothing to update (pass status / statusDetails / assignedTo / isBookmarked / hasSeen)");let n=await $r(r),{token:i,baseUrl:s}=await ut("sentry"),o=await fetch(`${mt(s)}/api/0/issues/${n}/`,{method:"PUT",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(e)});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 bp(r,t){if(!r)throw new Error("sentryAddComment: issueId is required");if(!t||!String(t).trim())throw new Error("sentryAddComment: text is required");let e=await $r(r),{token:n,baseUrl:i}=await ut("sentry"),s=await fetch(`${mt(i)}/api/0/issues/${e}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(t)})});if(!s.ok){let o=await s.text().catch(()=>"");throw s.status===403?new Error(`Sentry API 403 commenting on issue ${r}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${s.status} commenting on issue ${r}: ${o.slice(0,300)}`)}return s.json()}var Gt={id:"sentry",callsBackend:!0,serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:I.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry
464
464
  You have access to the user's Sentry. Use these tools:
465
465
  - sentry_list_projects: List projects in the organization
466
466
  - sentry_list_issues: List errors/issues (supports Sentry search query, project filter, sort)
467
467
  - sentry_get_issue: Get detailed info about a specific issue (requires issueId)
468
468
  - sentry_update_issue: Change an issue's status (resolved / resolvedInNextRelease / ignored / unresolved / muted), assignment, or bookmark (requires issueId; needs write scope)
469
- - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=Bd();if(!r)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE","ZIBBY_SELF_HOST","SENTRY_URL","SENTRY_ORG","SENTRY_AUTH_TOKEN"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r],env:t,alwaysLoad:!0}},async handleToolCall(r,t={}){try{switch(r){case"sentry_list_projects":{let e=await Jd();return JSON.stringify({projects:e.map(n=>({slug:n.slug,name:n.name,platform:n.platform}))})}case"sentry_list_issues":{let e=await qd({query:t.query,sort:t.sort,project:t.project,limit:t.limit});return JSON.stringify({issues:e.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 e=await Dd(t.issueId);return JSON.stringify({id:e.id,title:e.title,culprit:e.culprit,metadata:e.metadata,count:e.count,userCount:e.userCount,firstSeen:e.firstSeen,lastSeen:e.lastSeen,level:e.level,status:e.status,project:{slug:e.project?.slug,name:e.project?.name}})}case"sentry_update_issue":{let e=await Md(t.issueId,{status:t.status,statusDetails:t.statusDetails,assignedTo:t.assignedTo,isBookmarked:t.isBookmarked,hasSeen:t.hasSeen});return JSON.stringify({ok:!0,id:e.id??t.issueId,status:e.status,assignedTo:e.assignedTo,isBookmarked:e.isBookmarked})}case"sentry_add_comment":{let e=await Kd(t.issueId,t.text);return JSON.stringify({ok:!0,id:e.id,issueId:t.issueId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},toolsForAssistant:[{name:"sentry_list_projects",description:"List Sentry projects",input_schema:{type:"object",properties:{}}},{name:"sentry_list_issues",description:"List Sentry issues (errors)",input_schema:{type:"object",properties:{project:{type:"string",description:"Project slug (optional)"},query:{type:"string",description:"Sentry search query (default: is:unresolved)"},sort:{type:"string",description:"Sort order: date, new, priority, freq, user (default: date)"},limit:{type:"number",description:"Max issues to return (default 25)"}}}},{name:"sentry_get_issue",description:"Get details of a specific Sentry issue",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"}},required:["issueId"]}},{name:"sentry_update_issue",description:"Update a Sentry issue's status, assignment, or bookmark (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},status:{type:"string",description:"resolved | resolvedInNextRelease | unresolved | ignored | muted"},statusDetails:{type:"object",description:'Optional status details, e.g. { "inRelease": "latest" }'},assignedTo:{type:"string",description:'Assignee actor id, e.g. "user:123" or "team:456" (optional)'},isBookmarked:{type:"boolean",description:"Bookmark/unbookmark the issue (optional)"},hasSeen:{type:"boolean",description:"Mark the issue seen/unseen (optional)"}},required:["issueId"]}},{name:"sentry_add_comment",description:"Post a comment/note on a Sentry issue (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},text:{type:"string",description:"Comment body (markdown)"}},required:["issueId","text"]}}]};Ct.tools=Ct.toolsForAssistant;import{spawn as Ci}from"child_process";import{writeFileSync as Gd,mkdirSync as Ti,existsSync as se,readdirSync as qt,readFileSync as Jt,unlinkSync as Fd,createWriteStream as Hd,statSync as zd}from"fs";import{resolve as Ne,join as X}from"path";import{resolveMaxParallelRuns as Ui}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Yd}from"@zibby/core/constants/zibby-scratch.js";var Or="sessions",Tr=".zibby/output",Ut=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",Wd=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",Bi=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",K=new Map,ge=[],Zd=0,Ir=0,Ai=3e3;function Ji(){return`run_${++Zd}_${Date.now().toString(36)}`}function Ri(r){let t=Math.floor(r/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function qi(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function J(r,t,e){if(!Wd)return;let n=`
469
+ - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=mp();if(!r)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE","ZIBBY_SELF_HOST","SENTRY_URL","SENTRY_ORG","SENTRY_AUTH_TOKEN"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r],env:t,alwaysLoad:!0}},async handleToolCall(r,t={}){try{switch(r){case"sentry_list_projects":{let e=await fp();return JSON.stringify({projects:e.map(n=>({slug:n.slug,name:n.name,platform:n.platform}))})}case"sentry_list_issues":{let e=await hp({query:t.query,sort:t.sort,project:t.project,limit:t.limit});return JSON.stringify({issues:e.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 e=await yp(t.issueId);return JSON.stringify({id:e.id,title:e.title,culprit:e.culprit,metadata:e.metadata,count:e.count,userCount:e.userCount,firstSeen:e.firstSeen,lastSeen:e.lastSeen,level:e.level,status:e.status,project:{slug:e.project?.slug,name:e.project?.name}})}case"sentry_update_issue":{let e=await gp(t.issueId,{status:t.status,statusDetails:t.statusDetails,assignedTo:t.assignedTo,isBookmarked:t.isBookmarked,hasSeen:t.hasSeen});return JSON.stringify({ok:!0,id:e.id??t.issueId,status:e.status,assignedTo:e.assignedTo,isBookmarked:e.isBookmarked})}case"sentry_add_comment":{let e=await bp(t.issueId,t.text);return JSON.stringify({ok:!0,id:e.id,issueId:t.issueId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},toolsForAssistant:[{name:"sentry_list_projects",description:"List Sentry projects",input_schema:{type:"object",properties:{}}},{name:"sentry_list_issues",description:"List Sentry issues (errors)",input_schema:{type:"object",properties:{project:{type:"string",description:"Project slug (optional)"},query:{type:"string",description:"Sentry search query (default: is:unresolved)"},sort:{type:"string",description:"Sort order: date, new, priority, freq, user (default: date)"},limit:{type:"number",description:"Max issues to return (default 25)"}}}},{name:"sentry_get_issue",description:"Get details of a specific Sentry issue",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"}},required:["issueId"]}},{name:"sentry_update_issue",description:"Update a Sentry issue's status, assignment, or bookmark (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},status:{type:"string",description:"resolved | resolvedInNextRelease | unresolved | ignored | muted"},statusDetails:{type:"object",description:'Optional status details, e.g. { "inRelease": "latest" }'},assignedTo:{type:"string",description:'Assignee actor id, e.g. "user:123" or "team:456" (optional)'},isBookmarked:{type:"boolean",description:"Bookmark/unbookmark the issue (optional)"},hasSeen:{type:"boolean",description:"Mark the issue seen/unseen (optional)"}},required:["issueId"]}},{name:"sentry_add_comment",description:"Post a comment/note on a Sentry issue (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},text:{type:"string",description:"Comment body (markdown)"}},required:["issueId","text"]}}]};Gt.tools=Gt.toolsForAssistant;import{spawn as Zi}from"child_process";import{writeFileSync as _p,mkdirSync as qi,existsSync as oe,readdirSync as Wt,readFileSync as Yt,unlinkSync as kp,createWriteStream as wp,statSync as Sp}from"fs";import{resolve as Ee,join as X}from"path";import{resolveMaxParallelRuns as Vi}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as vp}from"@zibby/core/constants/zibby-scratch.js";var Ur="sessions",Br=".zibby/output",Ht=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",Ip=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",Xi=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",K=new Map,Se=[],Np=0,Pr=0,Mi=3e3;function Qi(){return`run_${++Np}_${Date.now().toString(36)}`}function Fi(r){let t=Math.floor(r/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function es(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function J(r,t,e){if(!Ip)return;let n=`
470
470
  ${t} [${r}] ${e}
471
- `;try{process.stderr.write(n)}catch{}}function Ar(){ge.length=0;for(let[,r]of K)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",Ar);process.on("SIGINT",()=>{Ar(),process.exit(0)});process.on("SIGTERM",()=>{Ar(),process.exit(0)});var Di={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
471
+ `;try{process.stderr.write(n)}catch{}}function Jr(){Se.length=0;for(let[,r]of K)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",Jr);process.on("SIGINT",()=>{Jr(),process.exit(0)});process.on("SIGTERM",()=>{Jr(),process.exit(0)});var ts={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
472
472
  You can run zibby test workflows directly from chat:
473
473
 
474
474
  **CRITICAL: When user asks to test a ticket:**
@@ -605,35 +605,35 @@ Each run generates:
605
605
  - events.json: All browser events
606
606
  - raw_stream_output.txt: Agent log
607
607
 
608
- Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(r,t,e){let n=e?.options?.workspace||process.cwd();try{switch(r){case"run_generate":return await Vd(t,n);case"run_test":return await np(t,n,e);case"run_status":return ip(t);case"run_cancel":return sp(t);case"run_artifacts":return cp(t,n);case"run_diagnose":return lp(t,n);case"list_specs":return dp(t,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 Nr(){let r=0;for(let[,t]of K)t.status==="running"&&r++;return r}function Ei(){for(;ge.length>0;){let r=Ui(ge[0]?.context?.options?.config);if(Nr()>=r)break;let{args:t,cwd:e,context:n}=ge.shift();Mi(t,e,n)}}async function Vd(r,t){let{ticket:e,description:n,input:i,repo:s,agent:o,output:a}=r,c=["generate"];e&&c.push("--ticket",e),n&&c.push("--description",n),i&&c.push("--input",i),s&&c.push("--repo",s),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,p=l&&d.includes(l)?l:null;p&&c.push("--agent",p);let u=e||"generate";return J(u,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{Bi&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(g=>/\s/.test(g)?JSON.stringify(g):g).join(" ")} cwd=${t}`);let f=Ci("zibby",c,{cwd:t,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",b="";f.stdout.on("data",g=>{let _=g.toString();h+=_;for(let y of _.split(`
609
- `)){let k=qi(y).trim();k.startsWith("\u2705")?J(u,"\u2705",k.slice(2).trim()):k.startsWith("\u2713")&&J(u,"\u2714",k.slice(2).trim())}}),f.stderr.on("data",g=>{b+=g.toString()}),f.on("close",g=>{if(g!==0){J(u,"\u274C",`Generation failed (exit ${g})`),m(JSON.stringify({error:`zibby generate failed with exit code ${g}`,stderr:b.slice(-1e3)}));return}let _=Ne(t,a||"test-specs"),y=[];try{let k=e?e.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";y=qt(_).filter(O=>O.endsWith(".txt")&&(!k||O.startsWith(k))).map(O=>X(_,O))}catch{}J(u,"\u2705",`Generated ${y.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:e||null,specFiles:y.map(k=>k.replace(`${t}/`,"")),total:y.length,message:`Generated ${y.length} specs. Now call run_test for each file.`}))}),f.on("error",g=>{J(u,"\u274C",`Spawn error: ${g.message}`),m(JSON.stringify({error:g.message}))})})}var ji=1e5,xi=/^[A-Z][A-Z0-9]+-\d+$/,Xd=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Qd(r,t){if(!t||!t.length)return r;let e=r;for(let n of t)n.type==="strong"?e=`**${e}**`:n.type==="em"?e=`_${e}_`:n.type==="code"?e=`\`${e}\``:n.type==="strike"?e=`~~${e}~~`:n.type==="link"&&n.attrs?.href&&(e=`[${e}](${n.attrs.href})`);return e}function Bt(r,t=0){if(!Array.isArray(r))return"";let e=[];for(let n of r){if(n.type==="text"){e.push(Qd(n.text||"",n.marks));continue}if(n.type==="hardBreak"){e.push(`
608
+ Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(r,t,e){let n=e?.options?.workspace||process.cwd();try{switch(r){case"run_generate":return await Op(t,n);case"run_test":return await jp(t,n,e);case"run_status":return Lp(t);case"run_cancel":return $p(t);case"run_artifacts":return Up(t,n);case"run_diagnose":return Bp(t,n);case"list_specs":return Jp(t,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 Cr(){let r=0;for(let[,t]of K)t.status==="running"&&r++;return r}function Ki(){for(;Se.length>0;){let r=Vi(Se[0]?.context?.options?.config);if(Cr()>=r)break;let{args:t,cwd:e,context:n}=Se.shift();rs(t,e,n)}}async function Op(r,t){let{ticket:e,description:n,input:i,repo:s,agent:o,output:a}=r,c=["generate"];e&&c.push("--ticket",e),n&&c.push("--description",n),i&&c.push("--input",i),s&&c.push("--repo",s),a&&c.push("--output",a);let l=["assistant","cursor","claude","codex","gemini"],d=o||process.env.AGENT_TYPE,p=d&&l.includes(d)?d:null;p&&c.push("--agent",p);let u=e||"generate";return J(u,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{Xi&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(y=>/\s/.test(y)?JSON.stringify(y):y).join(" ")} cwd=${t}`);let f=Zi("zibby",c,{cwd:t,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",_="";f.stdout.on("data",y=>{let b=y.toString();h+=b;for(let g of b.split(`
609
+ `)){let k=es(g).trim();k.startsWith("\u2705")?J(u,"\u2705",k.slice(2).trim()):k.startsWith("\u2713")&&J(u,"\u2714",k.slice(2).trim())}}),f.stderr.on("data",y=>{_+=y.toString()}),f.on("close",y=>{if(y!==0){J(u,"\u274C",`Generation failed (exit ${y})`),m(JSON.stringify({error:`zibby generate failed with exit code ${y}`,stderr:_.slice(-1e3)}));return}let b=Ee(t,a||"test-specs"),g=[];try{let k=e?e.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";g=Wt(b).filter(O=>O.endsWith(".txt")&&(!k||O.startsWith(k))).map(O=>X(b,O))}catch{}J(u,"\u2705",`Generated ${g.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:e||null,specFiles:g.map(k=>k.replace(`${t}/`,"")),total:g.length,message:`Generated ${g.length} specs. Now call run_test for each file.`}))}),f.on("error",y=>{J(u,"\u274C",`Spawn error: ${y.message}`),m(JSON.stringify({error:y.message}))})})}var Gi=1e5,Hi=/^[A-Z][A-Z0-9]+-\d+$/,Tp=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Rp(r,t){if(!t||!t.length)return r;let e=r;for(let n of t)n.type==="strong"?e=`**${e}**`:n.type==="em"?e=`_${e}_`:n.type==="code"?e=`\`${e}\``:n.type==="strike"?e=`~~${e}~~`:n.type==="link"&&n.attrs?.href&&(e=`[${e}](${n.attrs.href})`);return e}function zt(r,t=0){if(!Array.isArray(r))return"";let e=[];for(let n of r){if(n.type==="text"){e.push(Rp(n.text||"",n.marks));continue}if(n.type==="hardBreak"){e.push(`
610
610
  `);continue}if(n.type==="rule"){e.push(`
611
611
  ---
612
- `);continue}let i=n.content?Bt(n.content,t+1):"";if(n.type==="listItem")e.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${Bt(o.content||[],t+1).trim()}`);e.push(`
612
+ `);continue}let i=n.content?zt(n.content,t+1):"";if(n.type==="listItem")e.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${zt(o.content||[],t+1).trim()}`);e.push(`
613
613
  ${s.join(`
614
614
  `)}
615
- `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${Bt(o.content||[],t+1).trim()}`);e.push(`
615
+ `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${zt(o.content||[],t+1).trim()}`);e.push(`
616
616
  ${s.join(`
617
617
  `)}
618
618
  `)}else if(n.type==="heading"){let s=n.attrs?.level||2;e.push(`
619
619
 
620
620
  ${"#".repeat(s)} ${i.trim()}
621
621
 
622
- `)}else Xd.has(n.type)?e.push(`
622
+ `)}else Tp.has(n.type)?e.push(`
623
623
 
624
624
  ${i}
625
625
  `):e.push(i)}return e.join("").replace(/\n{3,}/g,`
626
626
 
627
- `)}function ep(r){return r==null||r===""?"":typeof r=="string"?r.trim():typeof r=="object"&&Array.isArray(r.content)?Bt(r.content).trim():""}async function tp(r){let{getSkill:t}=await import("@zibby/agent-workflow"),e=t("jira");if(!e||typeof e.handleToolCall!="function")return null;try{let n=await e.handleToolCall("jira_get_issue",{issueKey:r}),i=JSON.parse(n);if(i?.error)return null;let s=await e.handleToolCall("jira_get_comments",{issueKey:r,maxResults:50}),o=JSON.parse(s);if(o?.error)return null;let a=ep(i.description),c=[];a&&c.push(a);let d=Array.isArray(o.comments)?o.comments:[];if(d.length>0){let p=d.map(u=>String(u.body||"").trim()).filter(Boolean).join(`
627
+ `)}function Ap(r){return r==null||r===""?"":typeof r=="string"?r.trim():typeof r=="object"&&Array.isArray(r.content)?zt(r.content).trim():""}async function Ep(r){let{getSkill:t}=await import("@zibby/agent-workflow"),e=t("jira");if(!e||typeof e.handleToolCall!="function")return null;try{let n=await e.handleToolCall("jira_get_issue",{issueKey:r}),i=JSON.parse(n);if(i?.error)return null;let s=await e.handleToolCall("jira_get_comments",{issueKey:r,maxResults:50}),o=JSON.parse(s);if(o?.error)return null;let a=Ap(i.description),c=[];a&&c.push(a);let l=Array.isArray(o.comments)?o.comments:[];if(l.length>0){let p=l.map(u=>String(u.body||"").trim()).filter(Boolean).join(`
628
628
 
629
- `);p&&c.push(p)}let l=c.join(`
629
+ `);p&&c.push(p)}let d=c.join(`
630
630
 
631
- `).trim();return l?(l.length>ji&&(l=`${l.slice(0,ji)}
631
+ `).trim();return d?(d.length>Gi&&(d=`${d.slice(0,Gi)}
632
632
 
633
- ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function rp(r,t){try{let e=JSON.parse(r);return JSON.stringify({...e,...t})}catch{return r}}async function np(r,t,e){let n={...r},i=String(n.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let s=null;if(xi.test(i)&&!i.startsWith("inline:")){let l=await tp(i);l&&(i=l.inlineSpec,n.spec=i,String(n.ticketKey||"").trim()||(n.ticketKey=l.issueKey),s=l.issueKey)}let o=String(n.ticketKey||"").trim();if(o){for(let[l,p]of K.entries())if(p?.ticketKey===o&&!(p?.status!=="running"&&p?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:p.status,reused:!0,message:`A run for ${o} is already ${p.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let l=Ne(t,i);if(!se(l))return xi.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=Ui(e?.options?.config);if(Nr()>=a){let l=Ji(),p=n.ticketKey||l,u={runId:l,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};K.set(l,u),ge.push({args:{...n,_queuedRunId:l},cwd:t,context:e}),J(p,"\u23F3",`Queued (${Nr()}/${a} running, ${ge.length} queued)`);let m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return s&&(m.resolvedFromJiraIssue=s,m.message+=` (spec built from Jira ${s})`),JSON.stringify(m)}let c=Date.now()-Ir;c<Ai&&Ir>0&&await new Promise(l=>setTimeout(l,Ai-c)),Ir=Date.now();let d=Mi(n,t,e);return s?rp(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function Mi(r,t,e){let{spec:n,ticketKey:i,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||Ji(),l=n,p=!1;if(n.startsWith("inline:")){p=!0;let R=Yd(t);Ti(R,{recursive:!0}),l=X(R,`${d}.txt`),Gd(l,n.slice(7).trim(),"utf-8")}let u=Ne(t,".zibby","output","runs");Ti(u,{recursive:!0});let m=X(u,`${d}.log`),f=Hd(m,{flags:"a"}),b=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,g=["test",l];b&&g.push("--agent",b),o&&g.push("--headless"),a&&g.push("--workflow",a),Bi&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${g.map(R=>/\s/.test(R)?JSON.stringify(R):R).join(" ")} cwd=${t}`);let _=Ci("zibby",g,{cwd:t,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),y={runId:d,spec:i?`${i}: ${n}`:n,ticketKey:i||null,specPath:l,logPath:m,isInline:p,pid:_.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=i||d,O="";function Y(R){let A=qi(R).trim();if(!A)return;if(A.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let j=JSON.parse(A.slice(22));j.phase==="node_begin"?y.currentNode=j.node:j.phase==="node_end"&&(j.node&&!y.completedNodes.includes(j.node)&&y.completedNodes.push(j.node),y.currentNode===j.node&&(y.currentNode=null))}catch{}return}let D=A.match(/Session\s+(\S+)/);if(D&&!y.sessionId&&(y.sessionId=D[1],y.sessionPath=Ne(t,Tr,Or,y.sessionId)),A.startsWith("\u250C ")||A.startsWith("\u250C ")){let j=A.slice(2).trim();y.currentNode=j,Ut&&J(k,"\u25B6",`${j}`)}else if(A.startsWith("\u2514 ")||A.startsWith("\u2514 ")){let j=A.slice(2).trim();j.startsWith("done")?(y.currentNode&&!y.completedNodes.includes(y.currentNode)&&y.completedNodes.push(y.currentNode),Ut&&J(k,"\u2714",`${y.currentNode||"node"} done ${j.replace("done","").trim()}`),y.currentNode=null):j.startsWith("failed")&&(Ut&&J(k,"\u2718",`${y.currentNode||"node"} failed ${j.replace("failed","").trim()}`),y.currentNode=null)}else A.includes("Workflow completed")&&(y.currentNode=null,Ut&&J(k,"\u2714",`Workflow completed (${Ri(Date.now()-y.startTime)})`))}function je(R){let A=R.toString();y.output+=A,f.write(A),y.output.length>5e4&&(y.output=y.output.slice(-3e4)),O+=A;let D=O.split(`
634
- `);O=D.pop();for(let j of D)Y(j)}return _.stdout.on("data",je),_.stderr.on("data",R=>{let A=R.toString();y.error+=A,f.write(A),y.error.length>2e4&&(y.error=y.error.slice(-1e4))}),_.on("close",R=>{y.status=R===0?"passed":"failed",y.exitCode=R,y.endTime=Date.now(),O&&Y(O),f.end();let A=Ri(Date.now()-y.startTime);if(R===0?J(k,"\u2705",`Passed (${A})`):J(k,"\u274C",`Failed (${A})`),y.isInline)try{Fd(y.specPath)}catch{}Ei()}),_.on("error",R=>{y.status="error",y.error+=`
635
- Spawn error: ${R.message}`,J(k,"\u274C",`Spawn error: ${R.message}`),f.end(),Ei()}),y._child=_,K.set(d,y),JSON.stringify({runId:d,spec:y.spec,ticketKey:y.ticketKey,status:"running",pid:_.pid,logFile:m})}function Li(r){let t=Math.round(((r.endTime||Date.now())-r.startTime)/1e3),e=r.completedNodes||[],n=r.currentNode||null;if(r.status!=="running")return{elapsed:t,stage:r.status,completedNodes:e,currentNode:null};let i;return n?(i=`Actively executing node "${n}"`,e.length&&(i+=` (completed: ${e.join(", ")})`)):e.length?i=`Between nodes (completed: ${e.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${t}s. This is normal progress \u2014 do not cancel.`,{elapsed:t,stage:"running",currentNode:n,completedNodes:e,progress:i}}function ip(r){let{runId:t}=r;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let s=[...K.entries()].map(([l,p])=>{let u=Li(p),m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:p.status,elapsed:u.elapsed,exitCode:p.exitCode,sessionId:p.sessionId||null};return p.status==="running"?(m.currentNode=u.currentNode,m.completedNodes=u.completedNodes,m.progress=u.progress):m.outputTail=p.output.slice(-500),m}),o=s.filter(l=>l.status==="running").length,a=s.filter(l=>l.status==="passed").length,c=s.filter(l=>l.status==="failed").length,d={total:s.length,running:o,passed:a,failed:c,runs:s};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let e=K.get(t);if(!e)return JSON.stringify({error:`Run not found: ${t}`});let n=Li(e),i={runId:t,spec:e.spec,ticketKey:e.ticketKey,status:e.status,elapsed:n.elapsed,exitCode:e.exitCode,sessionId:e.sessionId||null};return e.status==="running"?(i.currentNode=n.currentNode,i.completedNodes=n.completedNodes,i.progress=n.progress):(i.outputTail=e.output.slice(-1e3),i.errorTail=e.error.slice(-500)),e.status==="running"&&(i._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(i)}function $i(r,t){if(t.status==="queued"){let e=ge.findIndex(n=>n.args._queuedRunId===r);return e>=0&&ge.splice(e,1),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}if(t.status!=="running")return{ok:!1,runId:r,error:`Run is not active (status: ${t.status})`};try{return t._child.kill("SIGTERM"),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}catch(e){return{ok:!1,runId:r,error:`Failed to cancel: ${e.message}`}}}function sp(r){let{runId:t}=r;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let n=[];for(let[i,s]of K.entries())(s.status==="running"||s.status==="queued")&&n.push($i(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 e=K.get(t);return JSON.stringify(e?$i(t,e):{error:`Run not found: ${t}`})}function op(r,t){let e=K.get(r);if(e?.sessionPath&&se(e.sessionPath))return e.sessionPath;if(e?.sessionId){let n=Ne(t,Tr,Or,e.sessionId);if(se(n))return n}return null}function Ki(r,t=""){let e=[];if(!se(r))return e;for(let n of qt(r,{withFileTypes:!0})){let i=t?`${t}/${n.name}`:n.name;if(n.isDirectory())e.push(...Ki(X(r,n.name),i));else{let s=zd(X(r,n.name));e.push({path:i,size:s.size})}}return e}function Pi(r){if(!se(r))return null;try{return JSON.parse(Jt(r,"utf-8"))}catch{return null}}function Gi(r,t=2e3){if(!r||!se(r))return"";try{return Jt(r,"utf-8").slice(-Math.max(200,Number(t)||2e3))}catch{return""}}function ap({run:r,logTail:t,errorTail:e}){let i=`${t||""}
636
- ${e||""}`.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 cp(r,t){let{runId:e,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=Ne(t,Tr,Or);if(!se(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=s.toLowerCase();for(let p of qt(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=X(c,p.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let b=X(u,f);if(se(b))try{let g=Jt(b,"utf-8");if(g.toLowerCase().includes(l)){let _=g.toLowerCase().indexOf(l),y=Math.max(0,_-100),k=Math.min(g.length,_+s.length+100);d.push({sessionId:p.name,artifact:h,snippet:g.slice(y,k)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:s,matches:d,total:d.length})}if(!e)return JSON.stringify({error:"runId is required for this type"});if(n==="log"){let c=K.get(e),d=Gi(c?.logPath,o);if(d)return JSON.stringify({runId:e,source:"run-log",totalLength:d.length,tail:d})}let a=op(e,t);if(!a)return JSON.stringify({error:`No session found for run ${e}. The run may still be starting.`});switch(n){case"list":{let c=Ki(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=Pi(X(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=Pi(X(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=X(a,i,"raw_stream_output.txt");if(!se(c))return JSON.stringify({error:`No log found in ${i}`});let d=Jt(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 lp(r,t){let e=String(r?.runId||"all"),n=Number(r?.tail||2e3),i=e==="all"?[...K.keys()]:[e];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let s=i.map(c=>{let d=K.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=Gi(d.logPath,n),p=String(d.error||"").slice(-Math.max(200,n));return{...ap({run:d,logTail:l,errorTail:p}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:p}}),o=s.filter(c=>c.status==="failed"||c.status==="error"),a=s.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:s.length,failed:o.length,active:a.length,diagnoses:s})}function dp(r,t){let e=r?.directory||"test-specs",n=Ne(t,e);if(!se(n))return JSON.stringify({specs:[],directory:e,message:`Directory not found: ${e}`});try{let s=function(o,a){for(let c of qt(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(X(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=>`${e}/${o}`),total:i.length,directory:e})}catch(i){return JSON.stringify({error:i.message})}}function Fi(r){let t=(r||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return t?{provider:"github",owner:t[1],repo:t[2]}:(t=(r||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),t?{provider:"gitlab",owner:t[1],repo:t[2]}:null)}var Hi={...fe,id:"git-write",envKeys:[...fe.envKeys||[],...$e.envKeys||[],...Pe.envKeys||[]].filter((r,t,e)=>e.indexOf(r)===t),promptFragment:`${fe.promptFragment}
633
+ ...[truncated]`),{inlineSpec:`inline:${d}`,issueKey:r}):null}catch{return null}}function xp(r,t){try{let e=JSON.parse(r);return JSON.stringify({...e,...t})}catch{return r}}async function jp(r,t,e){let n={...r},i=String(n.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let s=null;if(Hi.test(i)&&!i.startsWith("inline:")){let d=await Ep(i);d&&(i=d.inlineSpec,n.spec=i,String(n.ticketKey||"").trim()||(n.ticketKey=d.issueKey),s=d.issueKey)}let o=String(n.ticketKey||"").trim();if(o){for(let[d,p]of K.entries())if(p?.ticketKey===o&&!(p?.status!=="running"&&p?.status!=="queued"))return JSON.stringify({runId:d,ticketKey:o,status:p.status,reused:!0,message:`A run for ${o} is already ${p.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let d=Ee(t,i);if(!oe(d))return Hi.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=Vi(e?.options?.config);if(Cr()>=a){let d=Qi(),p=n.ticketKey||d,u={runId:d,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};K.set(d,u),Se.push({args:{...n,_queuedRunId:d},cwd:t,context:e}),J(p,"\u23F3",`Queued (${Cr()}/${a} running, ${Se.length} queued)`);let m={runId:d,spec:u.spec,ticketKey:u.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return s&&(m.resolvedFromJiraIssue=s,m.message+=` (spec built from Jira ${s})`),JSON.stringify(m)}let c=Date.now()-Pr;c<Mi&&Pr>0&&await new Promise(d=>setTimeout(d,Mi-c)),Pr=Date.now();let l=rs(n,t,e);return s?xp(l,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):l}function rs(r,t,e){let{spec:n,ticketKey:i,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,l=c||Qi(),d=n,p=!1;if(n.startsWith("inline:")){p=!0;let T=vp(t);qi(T,{recursive:!0}),d=X(T,`${l}.txt`),_p(d,n.slice(7).trim(),"utf-8")}let u=Ee(t,".zibby","output","runs");qi(u,{recursive:!0});let m=X(u,`${l}.log`),f=wp(m,{flags:"a"}),_=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,y=["test",d];_&&y.push("--agent",_),o&&y.push("--headless"),a&&y.push("--workflow",a),Xi&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${y.map(T=>/\s/.test(T)?JSON.stringify(T):T).join(" ")} cwd=${t}`);let b=Zi("zibby",y,{cwd:t,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),g={runId:l,spec:i?`${i}: ${n}`:n,ticketKey:i||null,specPath:d,logPath:m,isInline:p,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=i||l,O="";function q(T){let A=es(T).trim();if(!A)return;if(A.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let x=JSON.parse(A.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 M=A.match(/Session\s+(\S+)/);if(M&&!g.sessionId&&(g.sessionId=M[1],g.sessionPath=Ee(t,Br,Ur,g.sessionId)),A.startsWith("\u250C ")||A.startsWith("\u250C ")){let x=A.slice(2).trim();g.currentNode=x,Ht&&J(k,"\u25B6",`${x}`)}else if(A.startsWith("\u2514 ")||A.startsWith("\u2514 ")){let x=A.slice(2).trim();x.startsWith("done")?(g.currentNode&&!g.completedNodes.includes(g.currentNode)&&g.completedNodes.push(g.currentNode),Ht&&J(k,"\u2714",`${g.currentNode||"node"} done ${x.replace("done","").trim()}`),g.currentNode=null):x.startsWith("failed")&&(Ht&&J(k,"\u2718",`${g.currentNode||"node"} failed ${x.replace("failed","").trim()}`),g.currentNode=null)}else A.includes("Workflow completed")&&(g.currentNode=null,Ht&&J(k,"\u2714",`Workflow completed (${Fi(Date.now()-g.startTime)})`))}function ye(T){let A=T.toString();g.output+=A,f.write(A),g.output.length>5e4&&(g.output=g.output.slice(-3e4)),O+=A;let M=O.split(`
634
+ `);O=M.pop();for(let x of M)q(x)}return b.stdout.on("data",ye),b.stderr.on("data",T=>{let A=T.toString();g.error+=A,f.write(A),g.error.length>2e4&&(g.error=g.error.slice(-1e4))}),b.on("close",T=>{g.status=T===0?"passed":"failed",g.exitCode=T,g.endTime=Date.now(),O&&q(O),f.end();let A=Fi(Date.now()-g.startTime);if(T===0?J(k,"\u2705",`Passed (${A})`):J(k,"\u274C",`Failed (${A})`),g.isInline)try{kp(g.specPath)}catch{}Ki()}),b.on("error",T=>{g.status="error",g.error+=`
635
+ Spawn error: ${T.message}`,J(k,"\u274C",`Spawn error: ${T.message}`),f.end(),Ki()}),g._child=b,K.set(l,g),JSON.stringify({runId:l,spec:g.spec,ticketKey:g.ticketKey,status:"running",pid:b.pid,logFile:m})}function zi(r){let t=Math.round(((r.endTime||Date.now())-r.startTime)/1e3),e=r.completedNodes||[],n=r.currentNode||null;if(r.status!=="running")return{elapsed:t,stage:r.status,completedNodes:e,currentNode:null};let i;return n?(i=`Actively executing node "${n}"`,e.length&&(i+=` (completed: ${e.join(", ")})`)):e.length?i=`Between nodes (completed: ${e.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${t}s. This is normal progress \u2014 do not cancel.`,{elapsed:t,stage:"running",currentNode:n,completedNodes:e,progress:i}}function Lp(r){let{runId:t}=r;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let s=[...K.entries()].map(([d,p])=>{let u=zi(p),m={runId:d,spec:p.spec,ticketKey:p.ticketKey,status:p.status,elapsed:u.elapsed,exitCode:p.exitCode,sessionId:p.sessionId||null};return p.status==="running"?(m.currentNode=u.currentNode,m.completedNodes=u.completedNodes,m.progress=u.progress):m.outputTail=p.output.slice(-500),m}),o=s.filter(d=>d.status==="running").length,a=s.filter(d=>d.status==="passed").length,c=s.filter(d=>d.status==="failed").length,l={total:s.length,running:o,passed:a,failed:c,runs:s};return o>0&&(l._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(l)}let e=K.get(t);if(!e)return JSON.stringify({error:`Run not found: ${t}`});let n=zi(e),i={runId:t,spec:e.spec,ticketKey:e.ticketKey,status:e.status,elapsed:n.elapsed,exitCode:e.exitCode,sessionId:e.sessionId||null};return e.status==="running"?(i.currentNode=n.currentNode,i.completedNodes=n.completedNodes,i.progress=n.progress):(i.outputTail=e.output.slice(-1e3),i.errorTail=e.error.slice(-500)),e.status==="running"&&(i._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(i)}function Yi(r,t){if(t.status==="queued"){let e=Se.findIndex(n=>n.args._queuedRunId===r);return e>=0&&Se.splice(e,1),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}if(t.status!=="running")return{ok:!1,runId:r,error:`Run is not active (status: ${t.status})`};try{return t._child.kill("SIGTERM"),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}catch(e){return{ok:!1,runId:r,error:`Failed to cancel: ${e.message}`}}}function $p(r){let{runId:t}=r;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let n=[];for(let[i,s]of K.entries())(s.status==="running"||s.status==="queued")&&n.push(Yi(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 e=K.get(t);return JSON.stringify(e?Yi(t,e):{error:`Run not found: ${t}`})}function Pp(r,t){let e=K.get(r);if(e?.sessionPath&&oe(e.sessionPath))return e.sessionPath;if(e?.sessionId){let n=Ee(t,Br,Ur,e.sessionId);if(oe(n))return n}return null}function ns(r,t=""){let e=[];if(!oe(r))return e;for(let n of Wt(r,{withFileTypes:!0})){let i=t?`${t}/${n.name}`:n.name;if(n.isDirectory())e.push(...ns(X(r,n.name),i));else{let s=Sp(X(r,n.name));e.push({path:i,size:s.size})}}return e}function Wi(r){if(!oe(r))return null;try{return JSON.parse(Yt(r,"utf-8"))}catch{return null}}function is(r,t=2e3){if(!r||!oe(r))return"";try{return Yt(r,"utf-8").slice(-Math.max(200,Number(t)||2e3))}catch{return""}}function Cp({run:r,logTail:t,errorTail:e}){let i=`${t||""}
636
+ ${e||""}`.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 Up(r,t){let{runId:e,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=Ee(t,Br,Ur);if(!oe(c))return JSON.stringify({matches:[],message:"No sessions found"});let l=[],d=s.toLowerCase();for(let p of Wt(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=X(c,p.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let _=X(u,f);if(oe(_))try{let y=Yt(_,"utf-8");if(y.toLowerCase().includes(d)){let b=y.toLowerCase().indexOf(d),g=Math.max(0,b-100),k=Math.min(y.length,b+s.length+100);l.push({sessionId:p.name,artifact:h,snippet:y.slice(g,k)})}}catch{}}if(l.length>=20)break}return JSON.stringify({query:s,matches:l,total:l.length})}if(!e)return JSON.stringify({error:"runId is required for this type"});if(n==="log"){let c=K.get(e),l=is(c?.logPath,o);if(l)return JSON.stringify({runId:e,source:"run-log",totalLength:l.length,tail:l})}let a=Pp(e,t);if(!a)return JSON.stringify({error:`No session found for run ${e}. The run may still be starting.`});switch(n){case"list":{let c=ns(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=Wi(X(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=Wi(X(a,i,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${i}`});let l=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalEvents:l.length,events:l.slice(-50)})}case"log":{let c=X(a,i,"raw_stream_output.txt");if(!oe(c))return JSON.stringify({error:`No log found in ${i}`});let l=Yt(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalLength:l.length,tail:l.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${n}. Use: list, result, events, log, search`})}}function Bp(r,t){let e=String(r?.runId||"all"),n=Number(r?.tail||2e3),i=e==="all"?[...K.keys()]:[e];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let s=i.map(c=>{let l=K.get(c);if(!l)return{runId:c,error:`Run not found: ${c}`};let d=is(l.logPath,n),p=String(l.error||"").slice(-Math.max(200,n));return{...Cp({run:l,logTail:d,errorTail:p}),ticketKey:l.ticketKey||null,spec:l.spec,logTail:d,errorTail:p}}),o=s.filter(c=>c.status==="failed"||c.status==="error"),a=s.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:s.length,failed:o.length,active:a.length,diagnoses:s})}function Jp(r,t){let e=r?.directory||"test-specs",n=Ee(t,e);if(!oe(n))return JSON.stringify({specs:[],directory:e,message:`Directory not found: ${e}`});try{let s=function(o,a){for(let c of Wt(o,{withFileTypes:!0})){let l=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(X(o,c.name),l):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&i.push(l)}},i=[];return s(n,""),JSON.stringify({specs:i.map(o=>`${e}/${o}`),total:i.length,directory:e})}catch(i){return JSON.stringify({error:i.message})}}function ss(r){let t=(r||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return t?{provider:"github",owner:t[1],repo:t[2]}:(t=(r||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),t?{provider:"gitlab",owner:t[1],repo:t[2]}:null)}var os={..._e,id:"git-write",envKeys:[..._e.envKeys||[],...Je.envKeys||[],...De.envKeys||[]].filter((r,t,e)=>e.indexOf(r)===t),promptFragment:`${_e.promptFragment}
637
637
 
638
638
  ## Opening a pull request / merge request (git_open_pr)
639
639
  After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
@@ -645,7 +645,7 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
645
645
  To MERGE an open PR/MR, use the provider-agnostic tool:
646
646
  - git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
647
647
  { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
648
- 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,t,e){if(r!=="git_open_pr"&&r!=="git_merge_pr")return fe.handleToolCall(r,t,e);try{let n=t||{},i=n.repoUrl||n.repo_url||n.url;if(!i)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(r==="git_merge_pr"){let l=n.number??n.iid??n.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let p=Fi(i);return p?p.provider==="github"?$e.handleToolCall("github_merge_pr",{owner:p.owner,repo:p.repo,number:l,mergeMethod:n.mergeMethod},e):Pe.handleToolCall("gitlab_accept_mr",{project:`${p.owner}/${p.repo}`,iid:l},e):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=Fi(i);return d?d.provider==="github"?$e.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:s,base:o,title:a,body:c},e):Pe.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:s,target_branch:o,title:a,description:c},e):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:[...fe.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 Vi}from"child_process";import{existsSync as $r,mkdirSync as Xi}from"fs";import{join as le,basename as pp}from"path";import{randomBytes as up}from"crypto";import{pathToFileURL as lt}from"url";import{createRequire as Qi}from"module";var jr=".zibby/memory",es="dolt",ts={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},xr="mem0",Rr=new Map,Dt=new Map,Mt=!1,mp=Qi(import.meta.url),Ht=()=>up(8).toString("hex"),Oe=()=>new Date().toISOString(),fp=[`CREATE TABLE IF NOT EXISTS chat_memory (
648
+ 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,t,e){if(r!=="git_open_pr"&&r!=="git_merge_pr")return _e.handleToolCall(r,t,e);try{let n=t||{},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 d=n.number??n.iid??n.prNumber;if(d==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let p=ss(i);return p?p.provider==="github"?Je.handleToolCall("github_merge_pr",{owner:p.owner,repo:p.repo,number:d,mergeMethod:n.mergeMethod},e):De.handleToolCall("gitlab_accept_mr",{project:`${p.owner}/${p.repo}`,iid:d},e):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 l=ss(i);return l?l.provider==="github"?Je.handleToolCall("github_create_pr",{owner:l.owner,repo:l.repo,head:s,base:o,title:a,body:c},e):De.handleToolCall("gitlab_create_mr",{project:`${l.owner}/${l.repo}`,source_branch:s,target_branch:o,title:a,description:c},e):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:[..._e.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 ps}from"child_process";import{existsSync as Gr,mkdirSync as us}from"fs";import{join as ue,basename as Dp}from"path";import{randomBytes as qp}from"crypto";import{pathToFileURL as ht}from"url";import{createRequire as ms}from"module";var Mr=".zibby/memory",fs="dolt",hs={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},Fr="mem0",Dr=new Map,Zt=new Map,Vt=!1,Mp=ms(import.meta.url),tr=()=>qp(8).toString("hex"),xe=()=>new Date().toISOString(),Fp=[`CREATE TABLE IF NOT EXISTS chat_memory (
649
649
  id VARCHAR(64) PRIMARY KEY,
650
650
  memory_key VARCHAR(160),
651
651
  category VARCHAR(32) NOT NULL,
@@ -676,10 +676,10 @@ To MERGE an open PR/MR, use the provider-agnostic tool:
676
676
  tasks_failed INT DEFAULT 0,
677
677
  key_facts TEXT,
678
678
  created_at VARCHAR(32) NOT NULL
679
- )`],zi=new Set;function G(r,t){return Vi(es,t,{...ts,cwd:r})}function _e(r,t){try{let e=G(r,["sql","-q",t,"-r","json"]);return JSON.parse(e.trim()).rows||[]}catch{return[]}}function F(r,t){G(r,["sql","-q",t])}function Kt(r){if(zi.has(r))return!0;if(!$r(le(r,".dolt"))){if(!hp())return!1;Xi(r,{recursive:!0}),G(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let t=`${fp.join(`;
680
- `)};`;F(r,t);try{F(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{F(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return zi.add(r),!0}function hp(){try{return Vi(es,["version"],{...ts,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function Lr(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function qe(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function Pr(r,t){let e=["short","mid","long"].includes(r)?r:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(t||"").toLowerCase())&&e==="short"?"mid":e}function rs(r){let t=new Map;for(let e of r||[]){let n=Lr(e.content),i=e.memory_key?`key:${e.memory_key}`:n?`norm:${n}`:"";if(!i)continue;let s=t.get(i);if(!s){t.set(i,e);continue}let o=qe(s.tier),a=qe(e.tier);if(a>o){t.set(i,e);continue}a===o&&Number(e.relevance||0)>Number(s.relevance||0)&&t.set(i,e)}return[...t.values()]}function Ft(r,t){let e=String(r??"");return e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}\u2026`}function ct(r,t){let e={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:t||String(r?.backend||xr),error:r?.error||null};return e.backend==="mem0"?{...e,recentSessions:[],taskStats:[]}:e}function Yi(r){let t=[];if(r.recentSessions?.length>0){t.push("Recent sessions:");for(let e of r.recentSessions.slice(0,3))e?.summary?.trim()&&t.push(`- ${Ft(e.summary,150)}${e.tickets?` [${e.tickets}]`:""}`)}if(r.topMemories?.length>0){t.push("Known facts:");for(let e of r.topMemories.slice(0,10)){let n=e.tier==="long"?"\u2605":"\xB7";t.push(`${n} [${e.category}] ${Ft(e.content,120)}`)}}return t.length===0?"":`## Memory Context
679
+ )`],as=new Set;function G(r,t){return ps(fs,t,{...hs,cwd:r})}function ve(r,t){try{let e=G(r,["sql","-q",t,"-r","json"]);return JSON.parse(e.trim()).rows||[]}catch{return[]}}function H(r,t){G(r,["sql","-q",t])}function Xt(r){if(as.has(r))return!0;if(!Gr(ue(r,".dolt"))){if(!Kp())return!1;us(r,{recursive:!0}),G(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let t=`${Fp.join(`;
680
+ `)};`;H(r,t);try{H(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{H(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return as.add(r),!0}function Kp(){try{return ps(fs,["version"],{...hs,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function Kr(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function Ge(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function Hr(r,t){let e=["short","mid","long"].includes(r)?r:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(t||"").toLowerCase())&&e==="short"?"mid":e}function ys(r){let t=new Map;for(let e of r||[]){let n=Kr(e.content),i=e.memory_key?`key:${e.memory_key}`:n?`norm:${n}`:"";if(!i)continue;let s=t.get(i);if(!s){t.set(i,e);continue}let o=Ge(s.tier),a=Ge(e.tier);if(a>o){t.set(i,e);continue}a===o&&Number(e.relevance||0)>Number(s.relevance||0)&&t.set(i,e)}return[...t.values()]}function er(r,t){let e=String(r??"");return e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}\u2026`}function ft(r,t){let e={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:t||String(r?.backend||Fr),error:r?.error||null};return e.backend==="mem0"?{...e,recentSessions:[],taskStats:[]}:e}function cs(r){let t=[];if(r.recentSessions?.length>0){t.push("Recent sessions:");for(let e of r.recentSessions.slice(0,3))e?.summary?.trim()&&t.push(`- ${er(e.summary,150)}${e.tickets?` [${e.tickets}]`:""}`)}if(r.topMemories?.length>0){t.push("Known facts:");for(let e of r.topMemories.slice(0,10)){let n=e.tier==="long"?"\u2605":"\xB7";t.push(`${n} [${e.category}] ${er(e.content,120)}`)}}return t.length===0?"":`## Memory Context
681
681
  ${t.join(`
682
- `)}`}function Gt(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(t=>({summary:Ft(String(t?.summary||""),160),tickets:t?.tickets||null,created_at:t?.created_at||null})),topMemories:r.topMemories.slice(0,8).map(t=>({category:t?.category||null,tier:t?.tier||null,content:Ft(String(t?.content||""),140),source:t?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function yp(r,t){let e=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(e==="mem0"||e==="dolt")return e;let n=String(t?.options?.memoryBackend||t?.options?.config?.memory?.backend||"").trim().toLowerCase();if(n==="mem0"||n==="dolt")return n;if(Dt.has(r))return Dt.get(r);try{let i=le(r,".zibby.config.mjs");if($r(i)){let s=await import(lt(i).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return Dt.set(r,o),o}}catch{}return Dt.set(r,xr),xr}function ns(r){let t=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return t||`workspace:${pp(r||process.cwd())}`}var gp="mem0";function is(r){let t=le(r,jr,gp);return{dir:t,vectorDbPath:le(t,"vectors.db"),historyDbPath:le(t,"history.db")}}function _p(r){let t=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!t)return null;let e=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),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}=is(r||process.cwd());return{llm:{provider:"openai",config:{model:n,baseURL:t,...e?{apiKey:e}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:s,baseURL:t,...e?{apiKey:e}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function ss(r){let t=r||process.cwd();if(Rr.has(t))return Rr.get(t);let e;try{let a=Qi(lt(le(t,"package.json")).href).resolve("mem0ai/oss");e=await import(lt(a).href)}catch{try{let o=mp.resolve("mem0ai/oss");e=await import(lt(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${t}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let n=e?.Memory;if(!n)throw new Error("mem0ai/oss does not export Memory");let i=_p(t);if(i)try{Xi(is(t).dir,{recursive:!0})}catch{}let s=i?new n(i):new n;return Rr.set(t,s),s}function Wi(r,t="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||Ht(),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:Pr(n?.metadata?.tier||t,n?.metadata?.category||"fact"),relevance:Number(n?.score??n?.metadata?.relevance??.8),created_at:n?.created_at||n?.metadata?.created_at||Oe()})).filter(n=>String(n.content||"").trim().length>0)}var De={id:"dolt",store:(r,t)=>as(r,t),recall:(r,t)=>Ip(r,t),brief:(r,t)=>Np(r,t),endSession:(r,t)=>ls(r,t),logTask:(r,t)=>ds(r,t),taskHistory:(r,t)=>ps(r,t)},bp={id:"mem0",store:(r,t,e)=>vp(r,t,e),recall:(r,t,e)=>cs(r,t,e),brief:(r,t,e)=>Op(r,t,e),endSession:(r,t)=>ls(r,t),logTask:(r,t)=>ds(r,t),taskHistory:(r,t)=>ps(r,t)},kp={dolt:De,mem0:bp};async function Zi(r,t){let e=await yp(r,t);return kp[e]||De}var os={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
682
+ `)}`}function Qt(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(t=>({summary:er(String(t?.summary||""),160),tickets:t?.tickets||null,created_at:t?.created_at||null})),topMemories:r.topMemories.slice(0,8).map(t=>({category:t?.category||null,tier:t?.tier||null,content:er(String(t?.content||""),140),source:t?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function Gp(r,t){let e=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(e==="mem0"||e==="dolt")return e;let n=String(t?.options?.memoryBackend||t?.options?.config?.memory?.backend||"").trim().toLowerCase();if(n==="mem0"||n==="dolt")return n;if(Zt.has(r))return Zt.get(r);try{let i=ue(r,".zibby.config.mjs");if(Gr(i)){let s=await import(ht(i).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return Zt.set(r,o),o}}catch{}return Zt.set(r,Fr),Fr}function gs(r){let t=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return t||`workspace:${Dp(r||process.cwd())}`}var Hp="mem0";function bs(r){let t=ue(r,Mr,Hp);return{dir:t,vectorDbPath:ue(t,"vectors.db"),historyDbPath:ue(t,"history.db")}}function zp(r){let t=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!t)return null;let e=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),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}=bs(r||process.cwd());return{llm:{provider:"openai",config:{model:n,baseURL:t,...e?{apiKey:e}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:s,baseURL:t,...e?{apiKey:e}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function _s(r){let t=r||process.cwd();if(Dr.has(t))return Dr.get(t);let e;try{let a=ms(ht(ue(t,"package.json")).href).resolve("mem0ai/oss");e=await import(ht(a).href)}catch{try{let o=Mp.resolve("mem0ai/oss");e=await import(ht(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${t}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let n=e?.Memory;if(!n)throw new Error("mem0ai/oss does not export Memory");let i=zp(t);if(i)try{us(bs(t).dir,{recursive:!0})}catch{}let s=i?new n(i):new n;return Dr.set(t,s),s}function ls(r,t="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||tr(),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:Hr(n?.metadata?.tier||t,n?.metadata?.category||"fact"),relevance:Number(n?.score??n?.metadata?.relevance??.8),created_at:n?.created_at||n?.metadata?.created_at||xe()})).filter(n=>String(n.content||"").trim().length>0)}var He={id:"dolt",store:(r,t)=>ws(r,t),recall:(r,t)=>Qp(r,t),brief:(r,t)=>eu(r,t),endSession:(r,t)=>vs(r,t),logTask:(r,t)=>Is(r,t),taskHistory:(r,t)=>Ns(r,t)},Yp={id:"mem0",store:(r,t,e)=>Xp(r,t,e),recall:(r,t,e)=>Ss(r,t,e),brief:(r,t,e)=>tu(r,t,e),endSession:(r,t)=>vs(r,t),logTask:(r,t)=>Is(r,t),taskHistory:(r,t)=>Ns(r,t)},Wp={dolt:He,mem0:Yp};async function ds(r,t){let e=await Gp(r,t);return Wp[e]||He}var ks={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
683
683
  You have persistent memory across sessions. Use it to avoid losing context:
684
684
  - **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
685
685
  - **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
@@ -695,40 +695,40 @@ You have persistent memory across sessions. Use it to avoid losing context:
695
695
  - When the user's request is complete: call memory_end_session
696
696
 
697
697
  ### Categories for memory_store
698
- fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,t={}){let e=r?.options?.workspace||process.cwd(),n=le(e,jr),i=await Zi(e,r),s=i.id;if(s==="dolt"&&!Kt(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:ct({backend:s,error:o},s),promptContext:"",debugPreview:Gt(ct({backend:s,error:o},s)),error:o}}try{let o=await i.brief(t,n,e),a=JSON.parse(o||"{}"),c=ct({...a,backend:s},s);return{backend:s,brief:c,promptContext:Yi(c),debugPreview:Gt(c),error:c.error||null}}catch(o){if(s==="mem0"&&i!==De&&Kt(n)){if(!Mt){Mt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
699
- `)}catch{}}try{let d=await De.brief(t,n,e),l=JSON.parse(d||"{}"),p=ct({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:Yi(p),debugPreview:Gt(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=ct({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:Gt(c),error:a}}},async handleToolCall(r,t,e){let n=e?.options?.workspace||process.cwd(),i=le(n,jr),s=await Zi(n,e),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!Kt(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(t,i,n);case"memory_recall":return d.recall(t,i,n);case"memory_brief":return d.brief(t,i,n);case"memory_end_session":return d.endSession(t,i,n);case"task_log":return d.logTask(t,i,n);case"task_history":return d.taskHistory(t,i,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(d){if(o==="mem0"&&s!==De){if(Kt(i)){if(!Mt){Mt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
700
- `)}catch{}}try{return await c(De)}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 as(r,t){let{content:e,category:n,source:i,ticketKey:s,tier:o,memoryKey:a}=r;if(!e||!n)return JSON.stringify({error:"content and category are required"});let c=Lr(e);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=Pr(o,n),l=d==="long"?1:d==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let g=_e(t,`SELECT id, tier, relevance
698
+ fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,t={}){let e=r?.options?.workspace||process.cwd(),n=ue(e,Mr),i=await ds(e,r),s=i.id;if(s==="dolt"&&!Xt(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:ft({backend:s,error:o},s),promptContext:"",debugPreview:Qt(ft({backend:s,error:o},s)),error:o}}try{let o=await i.brief(t,n,e),a=JSON.parse(o||"{}"),c=ft({...a,backend:s},s);return{backend:s,brief:c,promptContext:cs(c),debugPreview:Qt(c),error:c.error||null}}catch(o){if(s==="mem0"&&i!==He&&Xt(n)){if(!Vt){Vt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
699
+ `)}catch{}}try{let l=await He.brief(t,n,e),d=JSON.parse(l||"{}"),p=ft({...d,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:cs(p),debugPreview:Qt(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=ft({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:Qt(c),error:a}}},async handleToolCall(r,t,e){let n=e?.options?.workspace||process.cwd(),i=ue(n,Mr),s=await ds(n,e),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!Xt(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=l=>{switch(r){case"memory_store":return l.store(t,i,n);case"memory_recall":return l.recall(t,i,n);case"memory_brief":return l.brief(t,i,n);case"memory_end_session":return l.endSession(t,i,n);case"task_log":return l.logTask(t,i,n);case"task_history":return l.taskHistory(t,i,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(l){if(o==="mem0"&&s!==He){if(Xt(i)){if(!Vt){Vt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${l.message}); degrading to dolt for this run
700
+ `)}catch{}}try{return await c(He)}catch(d){return JSON.stringify({error:d.message,backend:"dolt",degradedFrom:"mem0"})}}return JSON.stringify({error:`mem0 unavailable (${l.message}); dolt fallback also unavailable`,backend:"mem0"})}return JSON.stringify({error:l.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 ws(r,t){let{content:e,category:n,source:i,ticketKey:s,tier:o,memoryKey:a}=r;if(!e||!n)return JSON.stringify({error:"content and category are required"});let c=Kr(e);if(!c)return JSON.stringify({error:"content is empty after normalization"});let l=Hr(o,n),d=l==="long"?1:l==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let y=ve(t,`SELECT id, tier, relevance
701
701
  FROM chat_memory
702
702
  WHERE memory_key = ${S(p)}
703
703
  ORDER BY created_at DESC
704
- LIMIT 1`)[0];if(g){let _=String(g.tier||"mid"),y=Number(g.relevance||0),k=qe(d)>qe(_)?d:_,O=Math.max(l,y);F(t,`UPDATE chat_memory
704
+ LIMIT 1`)[0];if(y){let b=String(y.tier||"mid"),g=Number(y.relevance||0),k=Ge(l)>Ge(b)?l:b,O=Math.max(d,g);H(t,`UPDATE chat_memory
705
705
  SET content = ${S(e)},
706
706
  category = ${S(n)},
707
707
  source = ${S(i)},
708
708
  ticket_key = ${S(s)},
709
709
  tier = ${S(k)},
710
710
  relevance = ${O},
711
- created_at = ${S(Oe())}
712
- WHERE id = ${S(g.id)}`);try{G(t,["add","."]),G(t,["commit","-m",`memory upsert: ${n} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:g.id,category:n,tier:k,memoryKey:p,upserted:!0})}}let m=_e(t,`SELECT id, content, tier, relevance
711
+ created_at = ${S(xe())}
712
+ WHERE id = ${S(y.id)}`);try{G(t,["add","."]),G(t,["commit","-m",`memory upsert: ${n} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:y.id,category:n,tier:k,memoryKey:p,upserted:!0})}}let m=ve(t,`SELECT id, content, tier, relevance
713
713
  FROM chat_memory
714
714
  WHERE category = ${S(n)}
715
715
  ORDER BY created_at DESC
716
- LIMIT 200`).find(b=>Lr(b.content)===c);if(m){let b=String(m.tier||"mid"),g=Number(m.relevance||0),_=qe(d)>qe(b),y=l>g;if(_||y){F(t,`UPDATE chat_memory
717
- SET tier = ${S(_?d:b)},
718
- relevance = ${Math.max(l,g)}
719
- WHERE id = ${S(m.id)}`);try{G(t,["add","."]),G(t,["commit","-m",`memory promote: ${n} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:n,tier:_?d:b,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:n,tier:b,deduped:!0,promoted:!1})}let f=Ht(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;F(t,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
720
- VALUES (${S(f)}, ${S(p||null)}, ${S(n)}, ${S(e)}, ${S(i)}, ${S(s)}, ${S(h)}, ${S(d)}, ${l}, ${S(Oe())})`);try{G(t,["add","."]),G(t,["commit","-m",`memory: ${n} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:n,tier:d,memoryKey:p||null,stored:e.slice(0,100)})}function wp(r){let t=String(r||"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var Er=new Map;async function Sp(r,t){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return wp(process.env.ZIBBY_MEM0_INFER);let e=t||process.cwd();if(Er.has(e))return Er.get(e);let n=!1;try{let i=le(e,".zibby.config.mjs");$r(i)&&(n=(await import(lt(i).href))?.default?.memory?.infer===!0)}catch{}return Er.set(e,n),n}async function vp(r,t,e){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 ss(e),p=ns(e),u=Pr(a,i),m=await Sp(d,e);return await l.add([{role:"user",content:String(n)}],{userId:p,infer:m,metadata:{memoryKey:c||null,category:i,tier:u,source:s||"zibby-chat",ticketKey:o||null,created_at:Oe()}}),JSON.stringify({ok:!0,backend:"mem0",userId:p,category:i,tier:u,infer:m,memoryKey:c||null,stored:String(n).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function Ip(r,t){let{query:e,category:n,ticketKey:i,tier:s,limit:o=20}=r,a=[];e&&a.push(`content LIKE ${S(`%${e}%`)}`),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
716
+ LIMIT 200`).find(_=>Kr(_.content)===c);if(m){let _=String(m.tier||"mid"),y=Number(m.relevance||0),b=Ge(l)>Ge(_),g=d>y;if(b||g){H(t,`UPDATE chat_memory
717
+ SET tier = ${S(b?l:_)},
718
+ relevance = ${Math.max(d,y)}
719
+ WHERE id = ${S(m.id)}`);try{G(t,["add","."]),G(t,["commit","-m",`memory promote: ${n} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:n,tier:b?l:_,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:n,tier:_,deduped:!0,promoted:!1})}let f=tr(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;H(t,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
720
+ VALUES (${S(f)}, ${S(p||null)}, ${S(n)}, ${S(e)}, ${S(i)}, ${S(s)}, ${S(h)}, ${S(l)}, ${d}, ${S(xe())})`);try{G(t,["add","."]),G(t,["commit","-m",`memory: ${n} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:n,tier:l,memoryKey:p||null,stored:e.slice(0,100)})}function Zp(r){let t=String(r||"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var qr=new Map;async function Vp(r,t){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return Zp(process.env.ZIBBY_MEM0_INFER);let e=t||process.cwd();if(qr.has(e))return qr.get(e);let n=!1;try{let i=ue(e,".zibby.config.mjs");Gr(i)&&(n=(await import(ht(i).href))?.default?.memory?.infer===!0)}catch{}return qr.set(e,n),n}async function Xp(r,t,e){let{content:n,category:i,source:s,ticketKey:o,tier:a,memoryKey:c,infer:l}=r;if(!n||!i)return JSON.stringify({error:"content and category are required"});try{let d=await _s(e),p=gs(e),u=Hr(a,i),m=await Vp(l,e);return await d.add([{role:"user",content:String(n)}],{userId:p,infer:m,metadata:{memoryKey:c||null,category:i,tier:u,source:s||"zibby-chat",ticketKey:o||null,created_at:xe()}}),JSON.stringify({ok:!0,backend:"mem0",userId:p,category:i,tier:u,infer:m,memoryKey:c||null,stored:String(n).slice(0,100)})}catch(d){throw new Error(`mem0 store failed: ${d.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:d})}}function Qp(r,t){let{query:e,category:n,ticketKey:i,tier:s,limit:o=20}=r,a=[];e&&a.push(`content LIKE ${S(`%${e}%`)}`),n&&a.push(`category = ${S(n)}`),i&&a.push(`ticket_key = ${S(i)}`),s&&a.push(`tier = ${S(s)}`);let l=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
721
721
  FROM chat_memory ${a.length>0?`WHERE ${a.join(" AND ")}`:""}
722
722
  ORDER BY relevance DESC, created_at DESC
723
- LIMIT ${o}`,l=_e(t,d);return JSON.stringify({total:l.length,memories:l})}async function cs(r,t,e){let{query:n,category:i,ticketKey:s,tier:o,limit:a=20}=r;try{let c=await ss(e),d=ns(e),l=[];if(n&&String(n).trim()){let p=await c.search(String(n),{filters:{user_id:d},topK:a});l=Wi(p)}else{let p=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=Wi(p)}return i&&(l=l.filter(p=>p.category===i)),s&&(l=l.filter(p=>p.ticket_key===s)),o&&(l=l.filter(p=>p.tier===o)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function Np(r,t){let{ticketKey:e}=r;Ap(t);let i=_e(t,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
724
- FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),s=e?`AND ticket_key = ${S(e)}`:"",o=_e(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
725
- WHERE tier = 'long' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=_e(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
726
- WHERE tier = 'mid' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 8`),d=_e(t,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
727
- GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=rs([...o,...a]);return JSON.stringify({recentSessions:i,topMemories:l,taskStats:d,ticketFilter:e||null})}async function Op(r,t,e){let{ticketKey:n}=r,i=await cs({limit:80},t,e),s=JSON.parse(i||"{}"),o=Array.isArray(s.memories)?s.memories:[];n&&(o=o.filter(u=>u.ticket_key===n));let a=u=>{let m=Date.parse(String(u?.created_at||""))||0;return Number(u?.relevance||0)*1e12+m},c=(u,m)=>a(m)-a(u),d=o.filter(u=>u.tier==="long").sort(c).slice(0,10),l=o.filter(u=>u.tier==="mid").sort(c).slice(0,8),p=rs([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:p,taskStats:[],ticketFilter:n||null,backend:"mem0"})}function ls(r,t){let{summary:e,tickets:n,tasksRun:i=0,tasksPassed:s=0,tasksFailed:o=0,keyFacts:a}=r;if(!e)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${Ht()}`;if(F(t,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
728
- VALUES (${S(c)}, ${S(e)}, ${S(n)}, ${i}, ${s}, ${o}, ${S(a)}, ${S(Oe())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))as({content:d,category:"fact",source:"session_summary",tier:"mid"},t);Tp(t);try{G(t,["add","."]),G(t,["commit","-m",`session end: ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:e.slice(0,200)})}function ds(r,t){let{title:e,type:n,status:i,ticketKey:s,specPath:o,resultSummary:a}=r;if(!e||!n||!i)return JSON.stringify({error:"title, type, and status are required"});let c=Ht(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;F(t,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
729
- VALUES (${S(c)}, ${S(s)}, ${S(n)}, ${S(e)}, ${S(i)}, ${S(o)}, ${S(d)}, ${S(a)}, ${S(Oe())}, ${S(Oe())})`);try{G(t,["add","."]),G(t,["commit","-m",`task: ${i} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:e,type:n,status:i})}function ps(r,t){let{ticketKey:e,type:n,status:i,limit:s=20}=r,o=[];e&&o.push(`ticket_key = ${S(e)}`),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
723
+ LIMIT ${o}`,d=ve(t,l);return JSON.stringify({total:d.length,memories:d})}async function Ss(r,t,e){let{query:n,category:i,ticketKey:s,tier:o,limit:a=20}=r;try{let c=await _s(e),l=gs(e),d=[];if(n&&String(n).trim()){let p=await c.search(String(n),{filters:{user_id:l},topK:a});d=ls(p)}else{let p=await c.getAll({filters:{user_id:l},topK:Math.max(a,50)});d=ls(p)}return i&&(d=d.filter(p=>p.category===i)),s&&(d=d.filter(p=>p.ticket_key===s)),o&&(d=d.filter(p=>p.tier===o)),d=d.slice(0,a),JSON.stringify({total:d.length,memories:d,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function eu(r,t){let{ticketKey:e}=r;nu(t);let i=ve(t,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
724
+ FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),s=e?`AND ticket_key = ${S(e)}`:"",o=ve(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
725
+ WHERE tier = 'long' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=ve(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
726
+ WHERE tier = 'mid' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 8`),l=ve(t,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
727
+ GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),d=ys([...o,...a]);return JSON.stringify({recentSessions:i,topMemories:d,taskStats:l,ticketFilter:e||null})}async function tu(r,t,e){let{ticketKey:n}=r,i=await Ss({limit:80},t,e),s=JSON.parse(i||"{}"),o=Array.isArray(s.memories)?s.memories:[];n&&(o=o.filter(u=>u.ticket_key===n));let a=u=>{let m=Date.parse(String(u?.created_at||""))||0;return Number(u?.relevance||0)*1e12+m},c=(u,m)=>a(m)-a(u),l=o.filter(u=>u.tier==="long").sort(c).slice(0,10),d=o.filter(u=>u.tier==="mid").sort(c).slice(0,8),p=ys([...l,...d]);return JSON.stringify({recentSessions:[],topMemories:p,taskStats:[],ticketFilter:n||null,backend:"mem0"})}function vs(r,t){let{summary:e,tickets:n,tasksRun:i=0,tasksPassed:s=0,tasksFailed:o=0,keyFacts:a}=r;if(!e)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${tr()}`;if(H(t,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
728
+ VALUES (${S(c)}, ${S(e)}, ${S(n)}, ${i}, ${s}, ${o}, ${S(a)}, ${S(xe())})`),a)for(let l of a.split(";").map(d=>d.trim()).filter(Boolean))ws({content:l,category:"fact",source:"session_summary",tier:"mid"},t);ru(t);try{G(t,["add","."]),G(t,["commit","-m",`session end: ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:e.slice(0,200)})}function Is(r,t){let{title:e,type:n,status:i,ticketKey:s,specPath:o,resultSummary:a}=r;if(!e||!n||!i)return JSON.stringify({error:"title, type, and status are required"});let c=tr(),l=process.env.ZIBBY_CHAT_SESSION_ID||null;H(t,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
729
+ VALUES (${S(c)}, ${S(s)}, ${S(n)}, ${S(e)}, ${S(i)}, ${S(o)}, ${S(l)}, ${S(a)}, ${S(xe())}, ${S(xe())})`);try{G(t,["add","."]),G(t,["commit","-m",`task: ${i} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:e,type:n,status:i})}function Ns(r,t){let{ticketKey:e,type:n,status:i,limit:s=20}=r,o=[];e&&o.push(`ticket_key = ${S(e)}`),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
730
730
  FROM chat_tasks ${o.length>0?`WHERE ${o.join(" AND ")}`:""}
731
- ORDER BY created_at DESC LIMIT ${s}`,d=_e(t,c);return JSON.stringify({total:d.length,tasks:d})}function Tp(r){try{F(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),F(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),F(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),F(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function Ap(r){try{let t=new Date(Date.now()-864e5).toISOString();F(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(t)}`)}catch{}}import{existsSync as us,readFileSync as Rp}from"node:fs";import{homedir as Ep}from"node:os";import{join as jp,dirname as xp,resolve as Lp}from"node:path";import{fileURLToPath as $p}from"node:url";function Pp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=xp($p(import.meta.url)),t=Lp(r,"..","bin","mcp-skill.mjs");return us(t)?t:null}function Cp(){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=jp(Ep(),".zibby","config.json");return us(r)&&JSON.parse(Rp(r,"utf-8")).sessionToken||null}catch{return null}}function Up(){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 Bp(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Cr(r){return`${Bp()}:${r}`}async function Ur(r,t){let e=Cp();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${Up()}/credits/review-memory`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...t})});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 ms={id:"kv-memory",callsBackend:!0,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)
731
+ ORDER BY created_at DESC LIMIT ${s}`,l=ve(t,c);return JSON.stringify({total:l.length,tasks:l})}function ru(r){try{H(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),H(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),H(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),H(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function nu(r){try{let t=new Date(Date.now()-864e5).toISOString();H(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(t)}`)}catch{}}import{existsSync as Os,readFileSync as iu}from"node:fs";import{homedir as su}from"node:os";import{join as ou,dirname as au,resolve as cu}from"node:path";import{fileURLToPath as lu}from"node:url";function du(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=au(lu(import.meta.url)),t=cu(r,"..","bin","mcp-skill.mjs");return Os(t)?t:null}function pu(){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=ou(su(),".zibby","config.json");return Os(r)&&JSON.parse(iu(r,"utf-8")).sessionToken||null}catch{return null}}function uu(){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 mu(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function zr(r){return`${mu()}:${r}`}async function Yr(r,t){let e=pu();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${uu()}/credits/review-memory`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...t})});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 Ts={id:"kv-memory",callsBackend:!0,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)
732
732
  You have a PRIVATE per-agent key-value memory that survives across your
733
733
  stateless runs. It is automatically namespaced to YOU (this agent type) \u2014 other
734
734
  agents cannot see or collide with your entries, and you don't need to prefix
@@ -743,7 +743,7 @@ Tools:
743
743
  Use to record durable facts \u2014 e.g. dedup markers, prior decisions, summaries.
744
744
 
745
745
  Your namespace is added for you automatically; pass plain keys like
746
- "seen#owner/repo#42" or "lastRun".`,resolve(){let r=Pp();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/kvMemory.js","kvMemorySkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"kv_recall":{let e=typeof t?.key=="string"?t.key.trim():"";if(!e)return JSON.stringify({error:"key is required"});let n=await Ur("recall",{scope:Cr(e)});return JSON.stringify(n)}case"kv_recall_prefix":{let e=typeof t?.keyPrefix=="string"?t.keyPrefix.trim():"";if(!e)return JSON.stringify({error:"keyPrefix is required"});let n=await Ur("recall-prefix",{scopePrefix:Cr(e)});return JSON.stringify(n)}case"kv_store":{let e=typeof t?.key=="string"?t.key.trim():"";if(!e)return JSON.stringify({error:"key is required"});if(typeof t?.content!="string"||t.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let n={scope:Cr(e),content:t.content};t.metadata!=null&&(n.metadata=t.metadata);let i=await Ur("store",n);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"kv_recall",description:'Recall the value you stored under a plain key (exact match). Your per-agent namespace is added automatically \u2014 pass a plain key like "seen#owner/repo#42".',input_schema:{type:"object",properties:{key:{type:"string",description:'Plain storage key (no namespace prefix needed) \u2014 e.g. "seen#owner/repo#42" or "lastRun".'}},required:["key"]}},{name:"kv_recall_prefix",description:'List your entries whose plain key STARTS WITH a prefix (e.g. "seen#"). Your per-agent namespace is added automatically. Capped at 25.',input_schema:{type:"object",properties:{keyPrefix:{type:"string",description:'Plain key prefix to match (no namespace prefix needed) \u2014 e.g. "seen#".'}},required:["keyPrefix"]}},{name:"kv_store",description:"Store (overwrite) a value under a plain key so a later run of yours can recall it. Your per-agent namespace is added automatically.",input_schema:{type:"object",properties:{key:{type:"string",description:"Plain storage key (no namespace prefix needed). Same key you recall by."},content:{type:"string",description:"The value to persist. Free-form markdown/text."},metadata:{type:"object",description:"Optional structured metadata."}},required:["key","content"]}}]};import{existsSync as hs,readFileSync as Jp}from"node:fs";import{homedir as qp}from"node:os";import{join as Dp,dirname as Mp,resolve as Kp}from"node:path";import{fileURLToPath as Gp}from"node:url";function Fp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Mp(Gp(import.meta.url)),t=Kp(r,"..","bin","mcp-skill.mjs");return hs(t)?t:null}function ys(){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=Dp(qp(),".zibby","config.json");return hs(r)&&JSON.parse(Jp(r,"utf-8")).sessionToken||null}catch{return null}}function gs(){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 fs(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Hp(){let r={};for(let[t,e]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(t);if(!n)continue;let i=typeof e=="string"?e.trim():"";i&&(r[n[1]]=i)}return r}var _s={};function Te(r){let t={...Hp(),..._s},e=Object.keys(t),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(t,n)?{storeId:t[n],name:n}:{error:`unknown store '${n}'; available: ${e.join(", ")}`}:e.length===1?{storeId:t[e[0]],name:e[0]}:e.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${e.join(", ")})`}}async function zp(r){let t=ys();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let e=await fetch(`${gs()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`ensure_store failed (${e.status}): ${n.slice(0,300)}`)}return e.json()}async function de(r,t,e){let n=ys();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${gs()}/datasets/stores/${encodeURIComponent(r)}/${t}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${t} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var Yp=Math.floor(3.5*1024*1024);async function Wp(r,t,e,n){let i=await de(r,"put-url",{path:t,contentType:n});if(!i?.url)throw new Error("put-url did not return an upload URL");let s=await fetch(i.url,{method:i.method||"PUT",headers:i.headers||{"Content-Type":n},body:e});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`direct upload failed (${s.status}): ${o.slice(0,200)}`)}return{ok:!0,path:i.path||t,size:e.length,contentType:i.contentType||n,via:"presign"}}async function Zp(r,t){let e=await de(r,"get-url",{path:t});if(!e?.url)throw new Error("get-url did not return a download URL");let n=await fetch(e.url,{method:e.method||"GET"});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`direct download failed (${n.status}): ${s.slice(0,200)}`)}let i=await n.arrayBuffer();return{buf:Buffer.from(i),contentType:n.headers.get("content-type")||"application/octet-stream"}}var bs={id:"dataset-store",callsBackend:!0,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)
746
+ "seen#owner/repo#42" or "lastRun".`,resolve(){let r=du();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/kvMemory.js","kvMemorySkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"kv_recall":{let e=typeof t?.key=="string"?t.key.trim():"";if(!e)return JSON.stringify({error:"key is required"});let n=await Yr("recall",{scope:zr(e)});return JSON.stringify(n)}case"kv_recall_prefix":{let e=typeof t?.keyPrefix=="string"?t.keyPrefix.trim():"";if(!e)return JSON.stringify({error:"keyPrefix is required"});let n=await Yr("recall-prefix",{scopePrefix:zr(e)});return JSON.stringify(n)}case"kv_store":{let e=typeof t?.key=="string"?t.key.trim():"";if(!e)return JSON.stringify({error:"key is required"});if(typeof t?.content!="string"||t.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let n={scope:zr(e),content:t.content};t.metadata!=null&&(n.metadata=t.metadata);let i=await Yr("store",n);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"kv_recall",description:'Recall the value you stored under a plain key (exact match). Your per-agent namespace is added automatically \u2014 pass a plain key like "seen#owner/repo#42".',input_schema:{type:"object",properties:{key:{type:"string",description:'Plain storage key (no namespace prefix needed) \u2014 e.g. "seen#owner/repo#42" or "lastRun".'}},required:["key"]}},{name:"kv_recall_prefix",description:'List your entries whose plain key STARTS WITH a prefix (e.g. "seen#"). Your per-agent namespace is added automatically. Capped at 25.',input_schema:{type:"object",properties:{keyPrefix:{type:"string",description:'Plain key prefix to match (no namespace prefix needed) \u2014 e.g. "seen#".'}},required:["keyPrefix"]}},{name:"kv_store",description:"Store (overwrite) a value under a plain key so a later run of yours can recall it. Your per-agent namespace is added automatically.",input_schema:{type:"object",properties:{key:{type:"string",description:"Plain storage key (no namespace prefix needed). Same key you recall by."},content:{type:"string",description:"The value to persist. Free-form markdown/text."},metadata:{type:"object",description:"Optional structured metadata."}},required:["key","content"]}}]};import{existsSync as As,readFileSync as fu}from"node:fs";import{homedir as hu}from"node:os";import{join as yu,dirname as gu,resolve as bu}from"node:path";import{fileURLToPath as _u}from"node:url";function ku(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=gu(_u(import.meta.url)),t=bu(r,"..","bin","mcp-skill.mjs");return As(t)?t:null}function Es(){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=yu(hu(),".zibby","config.json");return As(r)&&JSON.parse(fu(r,"utf-8")).sessionToken||null}catch{return null}}function xs(){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 Rs(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function wu(){let r={};for(let[t,e]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(t);if(!n)continue;let i=typeof e=="string"?e.trim():"";i&&(r[n[1]]=i)}return r}var js={};function je(r){let t={...wu(),...js},e=Object.keys(t),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(t,n)?{storeId:t[n],name:n}:{error:`unknown store '${n}'; available: ${e.join(", ")}`}:e.length===1?{storeId:t[e[0]],name:e[0]}:e.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${e.join(", ")})`}}async function Su(r){let t=Es();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let e=await fetch(`${xs()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`ensure_store failed (${e.status}): ${n.slice(0,300)}`)}return e.json()}async function me(r,t,e){let n=Es();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${xs()}/datasets/stores/${encodeURIComponent(r)}/${t}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${t} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var vu=Math.floor(3.5*1024*1024);async function Iu(r,t,e,n){let i=await me(r,"put-url",{path:t,contentType:n});if(!i?.url)throw new Error("put-url did not return an upload URL");let s=await fetch(i.url,{method:i.method||"PUT",headers:i.headers||{"Content-Type":n},body:e});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`direct upload failed (${s.status}): ${o.slice(0,200)}`)}return{ok:!0,path:i.path||t,size:e.length,contentType:i.contentType||n,via:"presign"}}async function Nu(r,t){let e=await me(r,"get-url",{path:t});if(!e?.url)throw new Error("get-url did not return a download URL");let n=await fetch(e.url,{method:e.method||"GET"});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`direct download failed (${n.status}): ${s.slice(0,200)}`)}let i=await n.arrayBuffer();return{buf:Buffer.from(i),contentType:n.headers.get("content-type")||"application/octet-stream"}}var Ls={id:"dataset-store",callsBackend:!0,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)
747
747
  You have one or more durable stores for STRUCTURED records that survive across
748
748
  your stateless runs. Unlike key-value memory (for picking up where you left
749
749
  off), this is for accumulating DATA you want to QUERY and AGGREGATE later \u2014 e.g.
@@ -790,7 +790,25 @@ Tools:
790
790
  - file_list: (file stores) List stored files (optionally by path prefix).
791
791
  - file_delete: (file stores) Delete ONE file by path.
792
792
  Pick the tool that matches the store's TYPE; using a dataset tool on a sqlite
793
- store (or a file tool on either, etc.) is rejected.`,resolve(){let r=Fp();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/datasetStore.js","datasetStoreSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(r,t){try{switch(r){case"dataset_append":{if(t?.record==null||typeof t.record!="object"||Array.isArray(t.record))return JSON.stringify({error:"record is required (a JSON object)"});let e=Te(t?.store);if(e.error)return JSON.stringify({error:e.error});let n=typeof t?.agent=="string"&&t.agent.trim()?t.agent.trim():fs(),i={record:t.record,agent:n};typeof t?.description=="string"&&t.description.trim()&&(i.description=t.description.trim());let s=await de(e.storeId,"append",i);return JSON.stringify({...s,store:e.name,storeId:e.storeId})}case"dataset_query":{let e=Te(t?.store);if(e.error)return JSON.stringify({error:e.error});let n={};for(let s of["select","where","groupBy","orderBy","limit","since","until","agent"])t?.[s]!=null&&(n[s]=t[s]);let i=await de(e.storeId,"query",n);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}case"ensure_store":{let e=typeof t?.name=="string"?t.name.trim():"";if(!e)return JSON.stringify({error:"name is required"});let n=typeof t?.type=="string"&&t.type.trim()?t.type.trim().toLowerCase():"sqlite",i=typeof t?.description=="string"?t.description.trim():"",s=await zp({name:e,type:n,description:i,namespace:fs()});return s?.storeId&&(_s[e]=s.storeId),JSON.stringify({...s,store:e})}case"file_put":{let e=Te(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.path!="string"||!t.path.trim())return JSON.stringify({error:'path is required (a relative file path like "reports/2026-07.json")'});let n=typeof t?.content=="string",i=typeof t?.contentBase64=="string"&&t.contentBase64.length>0;if(!n&&!i)return JSON.stringify({error:"content (text) or contentBase64 (base64 bytes) is required"});let s=t.path.trim(),o=typeof t?.contentType=="string"&&t.contentType.trim()?t.contentType.trim():"",a=n?Buffer.from(t.content,"utf8"):Buffer.from(String(t.contentBase64).replace(/\s+/g,""),"base64");if(a.length>Yp){let l=o||(n?"text/plain; charset=utf-8":"application/octet-stream"),p=await Wp(e.storeId,s,a,l);return JSON.stringify({...p,store:e.name,storeId:e.storeId})}let c={path:s};n?c.content=t.content:c.contentBase64=t.contentBase64,o&&(c.contentType=o);let d=await de(e.storeId,"put",c);return JSON.stringify({...d,store:e.name,storeId:e.storeId})}case"file_get":{let e=Te(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.path!="string"||!t.path.trim())return JSON.stringify({error:"path is required"});let n=t.path.trim(),i;try{i=await de(e.storeId,"get",{path:n})}catch(c){if(!/failed \(413\)/.test(c?.message||""))throw c;let d=await Zp(e.storeId,n);i={path:n,size:d.buf.length,contentType:d.contentType,lastModified:null,contentBase64:d.buf.toString("base64")}}let s={ok:!0,store:e.name,storeId:e.storeId,path:i.path,size:i.size,contentType:i.contentType,lastModified:i.lastModified},o=Buffer.from(i.contentBase64||"","base64"),a=o.toString("utf8");return Buffer.compare(Buffer.from(a,"utf8"),o)===0&&!a.includes("\0")?(s.content=a,s.encoding="utf8"):(s.contentBase64=i.contentBase64,s.encoding="base64"),JSON.stringify(s)}case"file_list":{let e=Te(t?.store);if(e.error)return JSON.stringify({error:e.error});let n={};typeof t?.prefix=="string"&&t.prefix.trim()&&(n.prefix=t.prefix.trim()),t?.limit!=null&&(n.limit=t.limit),typeof t?.cursor=="string"&&t.cursor&&(n.cursor=t.cursor);let i=await de(e.storeId,"list",n);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}case"file_delete":{let e=Te(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.path!="string"||!t.path.trim())return JSON.stringify({error:"path is required"});let n=await de(e.storeId,"delete",{path:t.path.trim()});return JSON.stringify({...n,store:e.name,storeId:e.storeId})}case"sqlite_exec":case"sqlite_query":{let e=Te(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.sql!="string"||!t.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let n={sql:t.sql};r==="sqlite_query"&&(n.readOnly=!0),Array.isArray(t?.params)&&(n.params=t.params);let i=await de(e.storeId,"sql",n);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset","file"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics. "file" = arbitrary file/blob storage by relative path (file_put/file_get/file_list/file_delete).'},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"]}},{name:"file_put",description:"For FILE-type stores: write (or overwrite) ONE file at a relative path \u2014 raw JSON dumps, CSVs, images, snapshots, any blob you want to keep across your stateless runs. Text goes in `content`; binary goes base64-encoded in `contentBase64` (pass exactly one). SIZE: there is no practical limit \u2014 anything over ~3.5 MiB is streamed straight to object storage via a presigned URL automatically, so do NOT gzip, base64-wrap, chunk or split a file just to make it fit. Non-ASCII paths (e.g. \u4E2A\u4EBA\u62A5\u544A.html) are fine \u2014 do not transliterate. Overwriting the same path UPDATES the file. Returns { ok, path, size }.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},path:{type:"string",description:'Relative file path, e.g. "dumps/run-42.json" or "img/chart.png". Letters, digits, ".", "_", "-" and "/" only; no "..", no leading "/".'},content:{type:"string",description:"Text content (UTF-8). Use for JSON/CSV/text files."},contentBase64:{type:"string",description:"Base64-encoded binary content (images etc.). Alternative to `content`."},contentType:{type:"string",description:'Optional MIME type (e.g. "application/json", "image/png"). Defaults sensibly.'}},required:["path"]}},{name:"file_get",description:'For FILE-type stores: read ONE stored file back by its relative path. Text files come back as `content` (encoding "utf8"); binary files come back as `contentBase64` (encoding "base64"). Returns { path, size, contentType, lastModified, content|contentBase64, encoding }.',input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},path:{type:"string",description:"The relative file path to fetch (as listed by file_list / used in file_put)."}},required:["path"]}},{name:"file_list",description:'For FILE-type stores: list the stored files \u2014 each entry has { path, size, lastModified }. Optionally filter by a path `prefix` (e.g. "dumps/"). Paginated via `cursor` when there are more results.',input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},prefix:{type:"string",description:'Optional path prefix filter, e.g. "dumps/" or "reports/2026".'},limit:{type:"number",description:"Max entries to return (default/max 1000)."},cursor:{type:"string",description:"Pagination cursor from a previous file_list response (nextCursor)."}},required:[]}},{name:"file_delete",description:"For FILE-type stores: delete ONE stored file by its relative path. Returns { ok, path, deleted }. Errors if the path does not exist.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},path:{type:"string",description:"The relative file path to delete."}},required:["path"]}}]};import{SKILL_META as Vp}from"@zibby/skill-ids";import{existsSync as vs,readFileSync as Xp}from"node:fs";import{homedir as Qp}from"node:os";import{join as eu,dirname as tu,resolve as ru}from"node:path";import{fileURLToPath as nu}from"node:url";function iu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=tu(nu(import.meta.url)),t=ru(r,"..","bin","mcp-skill.mjs");return vs(t)?t:null}function Yt(){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=eu(Qp(),".zibby","config.json");return vs(r)&&JSON.parse(Xp(r,"utf-8")).sessionToken||null}catch{return null}}function Wt(){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 su(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Is(r){return`${su()}:artifact:${r}`}var Me="headings, paragraphs, **bold**, *italic*, `inline code`, fenced code blocks, bullet + numbered lists, blockquotes, horizontal rules, links, and GitHub-style pipe tables (including |---:| alignment)",zt="raw HTML (tags are escaped and print as literal text), images, nested lists, footnotes and strikethrough",dt=2,Ke=0;function Br(r,t){return JSON.stringify({published:!1,stop:!0,attemptsUsed:dt,defects:t||[],error:r,instruction:`STOP. You have used both publish attempts and the page is still rejected. Do NOT call artifact_publish or artifact_update again in this turn. Tell the user plainly that you could not produce a clean page, say in one line what was wrong, and give them the content directly in the chat instead. A broken link is worse than an honest "I couldn't".`})}function ou(r,t,e){return JSON.stringify({published:!1,stop:!1,attemptsRemaining:dt-Ke,defects:e||[],error:t,instruction:"The page was NOT published and no URL exists. Fix EXACTLY the defects listed above and call once more \u2014 you get ONE more attempt, then this tool will stop you."+(r==="html"?` You are on the \`html\` path, where you author the entire document and every mistake ships. Unless this page genuinely needs a custom visual layout, the fastest and most reliable fix is to re-send the SAME content as \`markdown\` \u2014 Zibby then generates the document skeleton, CSS and tables for you and these defects become impossible. Markdown supports ${Me}.`:` Markdown supports ${Me}; it does NOT support ${zt}.`)})}async function au(r){let t=Yt();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let e=await fetch(`${Wt()}/credits/artifacts`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let n=await e.text().catch(()=>""),i=null;try{i=JSON.parse(n)}catch{}let s=new Error(e.status===422&&i?.error?i.error:`artifact write failed (${e.status}): ${n.slice(0,300)}`);throw s.status=e.status,Array.isArray(i?.defects)&&(s.defects=i.defects),s}return e.json()}async function ks(r,t){try{let e=await au(r);return Ke=0,e}catch(e){if(e?.status!==422)throw e;return Ke+=1,{__rejected:!0,payload:Ke>=dt?Br(e.message,e.defects):ou(t,e.message,e.defects)}}}async function cu(r){let t=Yt();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let e=await fetch(`${Wt()}/credits/artifacts/${encodeURIComponent(r)}`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`artifact get failed (${e.status}): ${n.slice(0,300)}`)}return e.json()}async function ws(r,t){let e=Yt();if(!e)return;let n=await fetch(`${Wt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:"store",scope:Is(r),content:JSON.stringify(t)})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`artifact index write failed (${n.status}): ${i.slice(0,200)}`)}}async function lu(r){let t=Yt();if(!t)return null;let e=await fetch(`${Wt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:"recall",scope:Is(r)})});if(!e.ok)return null;let n=await e.json().catch(()=>null);if(!n?.found||!n?.memory?.content)return null;try{return JSON.parse(n.memory.content)}catch{return null}}function Ss(r){let t=typeof r?.html=="string"&&r.html.length>0,e=typeof r?.markdown=="string"&&r.markdown.length>0;return t&&e?{error:"Pass EITHER markdown OR html, not both \u2014 they are different rendering paths. Use markdown unless the page needs a custom visual layout."}:e?{format:"markdown",content:r.markdown}:t?{format:"html",content:r.html}:null}var Ns={id:"artifact",callsBackend:!0,meta:Vp.artifact,serverName:"artifact",allowedTools:["mcp__artifact__*"],description:"Artifacts \u2014 publish a self-contained, shareable HTML/Markdown page to Zibby and get back a URL; the index of what you published is your memory.",promptFragment:`## Artifacts (publish a shareable page, remember what you made)
793
+ store (or a file tool on either, etc.) is rejected.`,resolve(){let r=ku();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/datasetStore.js","datasetStoreSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(r,t){try{switch(r){case"dataset_append":{if(t?.record==null||typeof t.record!="object"||Array.isArray(t.record))return JSON.stringify({error:"record is required (a JSON object)"});let e=je(t?.store);if(e.error)return JSON.stringify({error:e.error});let n=typeof t?.agent=="string"&&t.agent.trim()?t.agent.trim():Rs(),i={record:t.record,agent:n};typeof t?.description=="string"&&t.description.trim()&&(i.description=t.description.trim());let s=await me(e.storeId,"append",i);return JSON.stringify({...s,store:e.name,storeId:e.storeId})}case"dataset_query":{let e=je(t?.store);if(e.error)return JSON.stringify({error:e.error});let n={};for(let s of["select","where","groupBy","orderBy","limit","since","until","agent"])t?.[s]!=null&&(n[s]=t[s]);let i=await me(e.storeId,"query",n);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}case"ensure_store":{let e=typeof t?.name=="string"?t.name.trim():"";if(!e)return JSON.stringify({error:"name is required"});let n=typeof t?.type=="string"&&t.type.trim()?t.type.trim().toLowerCase():"sqlite",i=typeof t?.description=="string"?t.description.trim():"",s=await Su({name:e,type:n,description:i,namespace:Rs()});return s?.storeId&&(js[e]=s.storeId),JSON.stringify({...s,store:e})}case"file_put":{let e=je(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.path!="string"||!t.path.trim())return JSON.stringify({error:'path is required (a relative file path like "reports/2026-07.json")'});let n=typeof t?.content=="string",i=typeof t?.contentBase64=="string"&&t.contentBase64.length>0;if(!n&&!i)return JSON.stringify({error:"content (text) or contentBase64 (base64 bytes) is required"});let s=t.path.trim(),o=typeof t?.contentType=="string"&&t.contentType.trim()?t.contentType.trim():"",a=n?Buffer.from(t.content,"utf8"):Buffer.from(String(t.contentBase64).replace(/\s+/g,""),"base64");if(a.length>vu){let d=o||(n?"text/plain; charset=utf-8":"application/octet-stream"),p=await Iu(e.storeId,s,a,d);return JSON.stringify({...p,store:e.name,storeId:e.storeId})}let c={path:s};n?c.content=t.content:c.contentBase64=t.contentBase64,o&&(c.contentType=o);let l=await me(e.storeId,"put",c);return JSON.stringify({...l,store:e.name,storeId:e.storeId})}case"file_get":{let e=je(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.path!="string"||!t.path.trim())return JSON.stringify({error:"path is required"});let n=t.path.trim(),i;try{i=await me(e.storeId,"get",{path:n})}catch(c){if(!/failed \(413\)/.test(c?.message||""))throw c;let l=await Nu(e.storeId,n);i={path:n,size:l.buf.length,contentType:l.contentType,lastModified:null,contentBase64:l.buf.toString("base64")}}let s={ok:!0,store:e.name,storeId:e.storeId,path:i.path,size:i.size,contentType:i.contentType,lastModified:i.lastModified},o=Buffer.from(i.contentBase64||"","base64"),a=o.toString("utf8");return Buffer.compare(Buffer.from(a,"utf8"),o)===0&&!a.includes("\0")?(s.content=a,s.encoding="utf8"):(s.contentBase64=i.contentBase64,s.encoding="base64"),JSON.stringify(s)}case"file_list":{let e=je(t?.store);if(e.error)return JSON.stringify({error:e.error});let n={};typeof t?.prefix=="string"&&t.prefix.trim()&&(n.prefix=t.prefix.trim()),t?.limit!=null&&(n.limit=t.limit),typeof t?.cursor=="string"&&t.cursor&&(n.cursor=t.cursor);let i=await me(e.storeId,"list",n);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}case"file_delete":{let e=je(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.path!="string"||!t.path.trim())return JSON.stringify({error:"path is required"});let n=await me(e.storeId,"delete",{path:t.path.trim()});return JSON.stringify({...n,store:e.name,storeId:e.storeId})}case"sqlite_exec":case"sqlite_query":{let e=je(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.sql!="string"||!t.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let n={sql:t.sql};r==="sqlite_query"&&(n.readOnly=!0),Array.isArray(t?.params)&&(n.params=t.params);let i=await me(e.storeId,"sql",n);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset","file"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics. "file" = arbitrary file/blob storage by relative path (file_put/file_get/file_list/file_delete).'},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"]}},{name:"file_put",description:"For FILE-type stores: write (or overwrite) ONE file at a relative path \u2014 raw JSON dumps, CSVs, images, snapshots, any blob you want to keep across your stateless runs. Text goes in `content`; binary goes base64-encoded in `contentBase64` (pass exactly one). SIZE: there is no practical limit \u2014 anything over ~3.5 MiB is streamed straight to object storage via a presigned URL automatically, so do NOT gzip, base64-wrap, chunk or split a file just to make it fit. Non-ASCII paths (e.g. \u4E2A\u4EBA\u62A5\u544A.html) are fine \u2014 do not transliterate. Overwriting the same path UPDATES the file. Returns { ok, path, size }.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},path:{type:"string",description:'Relative file path, e.g. "dumps/run-42.json" or "img/chart.png". Letters, digits, ".", "_", "-" and "/" only; no "..", no leading "/".'},content:{type:"string",description:"Text content (UTF-8). Use for JSON/CSV/text files."},contentBase64:{type:"string",description:"Base64-encoded binary content (images etc.). Alternative to `content`."},contentType:{type:"string",description:'Optional MIME type (e.g. "application/json", "image/png"). Defaults sensibly.'}},required:["path"]}},{name:"file_get",description:'For FILE-type stores: read ONE stored file back by its relative path. Text files come back as `content` (encoding "utf8"); binary files come back as `contentBase64` (encoding "base64"). Returns { path, size, contentType, lastModified, content|contentBase64, encoding }.',input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},path:{type:"string",description:"The relative file path to fetch (as listed by file_list / used in file_put)."}},required:["path"]}},{name:"file_list",description:'For FILE-type stores: list the stored files \u2014 each entry has { path, size, lastModified }. Optionally filter by a path `prefix` (e.g. "dumps/"). Paginated via `cursor` when there are more results.',input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},prefix:{type:"string",description:'Optional path prefix filter, e.g. "dumps/" or "reports/2026".'},limit:{type:"number",description:"Max entries to return (default/max 1000)."},cursor:{type:"string",description:"Pagination cursor from a previous file_list response (nextCursor)."}},required:[]}},{name:"file_delete",description:"For FILE-type stores: delete ONE stored file by its relative path. Returns { ok, path, deleted }. Errors if the path does not exist.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},path:{type:"string",description:"The relative file path to delete."}},required:["path"]}}]};import{SKILL_META as dm}from"@zibby/skill-ids";import{existsSync as Zs,readFileSync as pm}from"node:fs";import{homedir as um}from"node:os";import{join as mm,dirname as fm,resolve as hm}from"node:path";import{fileURLToPath as ym}from"node:url";import{existsSync as Ou}from"node:fs";import{dirname as Tu,resolve as Ru}from"node:path";import{fileURLToPath as Au}from"node:url";var Q={ZERO_WIDTH:"zero-width-bar",ROW_COUNT:"data-row-count",ROW_MISSING:"data-row-missing",BAR_COUNT:"data-bar-count",BAR_PROPORTION:"bar-proportion",VALUE_MISMATCH:"data-value-mismatch",PLACEHOLDER_TEXT:"placeholder-text",OVERFLOW:"overflow-clipped"},Eu=5,xu=20,ju=.04,Lu=3,$u=.5;function ae(r,t){if(t==null||t<0)return null;let e=1;for(let n=0;n<t&&n<r.length;n+=1)r.charCodeAt(n)===10&&(e+=1);return e}function ce(r,t,e){let n=t[e.code]||0;n>=Eu||r.length>=xu||(t[e.code]=n+1,r.push(e))}var Pu={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026"};function Cs(r){return String(r).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi,(t,e)=>{if(e[0]==="#"){let i=e[1]==="x"||e[1]==="X"?parseInt(e.slice(2),16):parseInt(e.slice(1),10);return Number.isFinite(i)?String.fromCodePoint(i):t}let n=Pu[String(e).toLowerCase()];return n??t})}function ze(r){return Cs(String(r??"")).replace(/\s+/g," ").trim().toLowerCase()}function $s(r){return Math.round(r*10)/10}var Cu=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Zr=new Set(["script","style","textarea"]),Uu=new Set(["span","a","em","strong","b","i","u","s","small","code","label","abbr","cite","q","sub","sup","mark","time","var","kbd","samp","font","tt"]),Bu=/^<\s*(\/?)\s*([a-zA-Z][a-zA-Z0-9:_.-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/;function Ju(r){let t={},e=/([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'=<>`]+))|([a-zA-Z_:][-a-zA-Z0-9_:.]*)/g,n;for(;(n=e.exec(r))!==null;)n[1]?t[n[1].toLowerCase()]=n[3]!=null?n[3]:n[4]!=null?n[4]:n[5]==null?"":n[5]:n[6]&&(t[n[6].toLowerCase()]="");return t}function Du(r){let t={tag:"#root",attrs:{},children:[],parent:null,start:0},e=t,n=[t],i=0,s=(o,a)=>{if(a<=o)return;let c=r.slice(o,a);c.trim()&&e.children.push({tag:"#text",attrs:{},children:[],parent:e,start:o,value:c})};for(;i<r.length;){let o=r.indexOf("<",i);if(o<0){s(i,r.length);break}if(s(i,o),r.startsWith("<!--",o)){let p=r.indexOf("-->",o);i=p<0?r.length:p+3;continue}if(r.startsWith("<!",o)||r.startsWith("<?",o)){let p=r.indexOf(">",o);i=p<0?r.length:p+1;continue}let a=Bu.exec(r.slice(o));if(!a){i=o+1;continue}let c=a[0],l=a[2].toLowerCase();if(a[1]){for(let p=n.length-1;p>0;p-=1)if(n[p].tag===l){n.length=p,e=n[p-1];break}i=o+c.length;continue}let d={tag:l,attrs:Ju(a[3]||""),children:[],parent:e,start:o};if(e.children.push(d),i=o+c.length,!(a[4]||Cu.has(l))){if(Zr.has(l)){let p=r.slice(i),u=new RegExp(`</\\s*${l}\\s*>`,"i").exec(p);d.raw=u?p.slice(0,u.index):p,i+=u?u.index+u[0].length:p.length;continue}n.push(d),e=d}}return t}function Le(r,t){for(let e of r.children)e.tag!=="#text"&&(t(e),Le(e,t))}function nr(r){let t=[],e=n=>{for(let i of n.children)i.tag==="#text"?t.push(i.value||""):(t.push(" "),e(i),t.push(" "))};return e(r),ze(t.join(""))}function qu(r){let t=[],e=n=>{for(let i of n.children)i.tag==="#text"?t.push({value:i.value||"",start:i.start,parent:n}):i.tag!=="pre"&&i.tag!=="code"&&e(i)};return e(r),t}function yt(r){let t={};for(let e of String(r||"").split(";")){let n=e.indexOf(":");n<0||(t[e.slice(0,n).trim().toLowerCase()]=e.slice(n+1).trim().replace(/\s*!important$/i,""))}return t}function Mu(r){let t=[];return Le(r,e=>{if(e.tag!=="style"||!e.raw)return;let n=e.raw.replace(/@[a-z-]+[^{]*\{/gi," "),i=/([^{}]+)\{([^{}]*)\}/g,s;for(;(s=i.exec(n))!==null;){let o=yt(s[2]);for(let a of s[1].split(",")){let c=a.trim();if(!c||/[\s>+~:[\]*]/.test(c))continue;let l=[],d=null,p=null,u=!0,m=/([.#]?)([A-Za-z_][-\w]*)/g,f;for(;(f=m.exec(c))!==null;)if(f[1]===".")l.push(f[2].toLowerCase());else if(f[1]==="#")d=f[2];else if(f.index===0)p=f[2].toLowerCase();else{u=!1;break}u&&(p||d||l.length)&&t.push({classes:l,id:d,tag:p,decls:o})}}}),t}function Us(r){return String(r.attrs.class||"").split(/\s+/).filter(Boolean).map(t=>t.toLowerCase())}function Fu(r,t,e){if(r.tag&&r.tag!==t.tag||r.id&&r.id!==t.attrs.id)return!1;for(let n of r.classes)if(e.indexOf(n)<0)return!1;return!0}function fe(r,t,e){let n=yt(r.attrs.style)[t];if(n!=null&&n!=="")return n.toLowerCase();let i=Us(r),s=null;for(let o of e){if(!Fu(o,r,i))continue;let a=o.decls[t];a!=null&&a!==""&&(s=a.toLowerCase())}return s}function Ps(r,t){let e=fe(r,"display",t);return e||(Uu.has(r.tag)?"inline":"block")}function Wr(r){if(!r)return null;let t=/^(-?\d+(?:\.\d+)?)px$/.exec(String(r).trim());return t?Number(t[1]):null}function Bs(r){if(!r)return null;let t=/^(-?\d+(?:\.\d+)?)%$/.exec(String(r).trim());return t?Number(t[1]):null}function rr(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function Ku(r){if(!r.length||!rr(r[0]))return r.map(n=>n==null?"":String(n));let t=null,e=0;for(let n of Object.keys(r[0])){let i=r.map(o=>rr(o)&&o[n]!=null?String(o[n]):"");if(i.some(o=>o.length<2))continue;let s=new Set(i.map(ze)).size;if(s>e&&(e=s,t=i),s===r.length)break}return t||r.map((n,i)=>String(rr(n)?Object.values(n)[0]==null?i:Object.values(n)[0]:n))}function Gu(r){let t=[],e=[],n=new Set,i=(o,a)=>{if(!(a.length<2)){if(a.every(rr)){t.push({path:o,records:a,identities:Ku(a)});let c=Object.keys(a[0]),l=c.filter(p=>a.every(u=>typeof u[p]=="number"&&Number.isFinite(u[p]))),d=c.filter(p=>a.every(u=>typeof u[p]=="string"));l.length===1&&d.length>=1&&e.push({path:o,labels:a.map(p=>String(p[d[0]])),values:a.map(p=>Number(p[l[0]]))});return}a.every(c=>typeof c=="number"&&Number.isFinite(c))&&e.push({path:o,labels:a.map((c,l)=>`#${l}`),values:a.slice()})}},s=(o,a,c)=>{if(!(c>6||o==null||typeof o!="object"||n.has(o))){if(n.add(o),Array.isArray(o)){i(a,o);for(let l=0;l<o.length&&l<200;l+=1)s(o[l],`${a}[${l}]`,c+1);return}for(let l of Object.keys(o))s(o[l],a?`${a}.${l}`:l,c+1)}};return s(r,"",0),{collections:t,series:e}}function Hu(r){let t=String(r||"").match(/[MmLlHhVvZz]|-?\d*\.?\d+(?:e-?\d+)?/gi);if(!t)return null;let e=0,n=0,i="",s=1/0,o=-1/0,a=1/0,c=-1/0,l=()=>{!Number.isFinite(e)||!Number.isFinite(n)||(e<s&&(s=e),e>o&&(o=e),n<a&&(a=n),n>c&&(c=n))},d=0,p=0;for(;d<t.length&&p++<2e4;){let u=t[d];if(/[A-Za-z]/.test(u)&&(i=u,d+=1,i==="Z"||i==="z"))continue;if(d>=t.length)break;let m=()=>{let f=Number(t[d]);return d+=1,f};switch(i){case"M":e=m(),n=m(),l(),i="L";break;case"m":e+=m(),n+=m(),l(),i="l";break;case"L":e=m(),n=m(),l();break;case"l":e+=m(),n+=m(),l();break;case"H":e=m(),l();break;case"h":e+=m(),l();break;case"V":n=m(),l();break;case"v":n+=m(),l();break;default:d+=1;break}}return!Number.isFinite(s)||!Number.isFinite(a)?null:{w:o-s,h:c-a}}var zu=/(^|[-_])(bar|gauge|meter|fill|progress|track)([-_]|$)/i;function Yu(r){let t=r.parent;for(let e=0;t&&e<3;e+=1,t=t.parent){let n=nr(t);if(n)return n}return""}function Js(r,t){if(Us(r).some(i=>zu.test(i)))return!0;let e=yt(r.attrs.style);return!!(e.background||e["background-color"]||fe(r,"background",t)||fe(r,"background-color",t))&&nr(r)===""}function Wu(r){let t=new Map;for(let n of r)for(let i=n.node.parent;i;i=i.parent)t.set(i,(t.get(i)||0)+1);let e=new Map;for(let n of r){let i=null;for(let s=n.node.parent;s;s=s.parent)if((t.get(s)||0)>=2){i=s;break}i&&(e.has(i)||e.set(i,[]),e.get(i).push(n))}return[...e.values()].filter(n=>n.length>=2)}function Zu(r,t){let e=new Map,n=[];Le(r,s=>{if(s.tag==="path"||s.tag==="rect"){let d=s.attrs.ecmeta_series_index;if(d==null)return;let p=null;if(s.tag==="rect"){let f=Number(s.attrs.width),h=Number(s.attrs.height);Number.isFinite(f)&&Number.isFinite(h)&&(p={w:f,h})}else p=Hu(s.attrs.d||"");if(!p)return;let u=s.attrs.ecmeta_data_index,m=String(d);e.has(m)||e.set(m,[]),e.get(m).push({bar:{node:s,extent:NaN,unit:"user",dataIndex:u==null||u===""?null:Number(u),context:"",start:s.start},box:p});return}if(Zr.has(s.tag)||s.tag==="svg")return;let o=yt(s.attrs.style),a=o.width==null?o["inline-size"]:o.width;if(a==null||a==="")return;let c=Bs(a),l=Wr(a);c==null&&l==null||Js(s,t)&&n.push({node:s,extent:c??l,unit:c==null?"px":"%",dataIndex:null,context:Yu(s),start:s.start})});let i=[];for(let s of e.values()){if(s.length<2)continue;let o=l=>Math.max(...l)-Math.min(...l),a=o(s.map(l=>l.box.h))>=o(s.map(l=>l.box.w));for(let l of s)l.bar.extent=a?l.box.h:l.box.w;let c=s.map(l=>l.bar).sort((l,d)=>l.dataIndex!=null&&d.dataIndex!=null?l.dataIndex-d.dataIndex:l.start-d.start);i.push(c)}for(let s of Wu(n)){let o=s.filter(l=>l.unit==="%"),a=s.filter(l=>l.unit==="px"),c=o.length>=a.length?o:a;c.length>=2&&i.push(c)}return i}function Vu(r){let t=[];return Le(r,e=>{if(e.tag!=="table")return;let n=[];Le(e,i=>{if(i.tag!=="tr")return;let s=i.children.filter(o=>o.tag==="td"||o.tag==="th");s.length&&s.every(o=>o.tag==="th")||n.push(i)}),t.push({node:e,rows:n,rowTexts:n.map(nr),start:e.start})}),t}function Xu(r,t,e,n,i,s,o){let a=nr(t);for(let c of n){let l=c.records.length;if(l<3)continue;let d=[],p=0;for(let y of c.identities){let b=ze(y);!b||b.length<2||(p+=1,a.includes(b)||d.push(String(y)))}if(p<3)continue;let u=p-d.length,m=p?u/p:1,f=null,h=0;for(let y of e){if(!y.rows.length)continue;let b=0,g=new Set;for(let k of y.rowTexts){let O=!1;c.identities.forEach((q,ye)=>{let T=ze(q);T.length>=2&&k.indexOf(T)>=0&&(O=!0,g.add(ye))}),O&&(b+=1)}b<Math.max(2,Math.ceil(y.rows.length*.5))||g.size<Math.ceil(b*.8)||b>h&&(h=b,f=y)}let _=f!=null;o.push({path:c.path||"(root)",records:l,identitiesSearched:p,presentInPage:u,renderedFraction:Number(m.toFixed(3)),boundTableRows:_?f.rows.length:null}),!(m<$u)&&(d.length&&ce(i,s,{code:Q.ROW_MISSING,line:_?ae(r,f.start):1,message:`The data at \`${c.path||"(root)"}\` has ${l} records but ${d.length} of them appear NOWHERE on the page: ${d.slice(0,6).map(y=>JSON.stringify(String(y).slice(0,40))).join(", ")}${d.length>6?`, +${d.length-6} more`:""}.`,hint:"Render every record you were given, or say in the page that it is a partial view and how many were left out. A silently truncated table reads as the complete answer."}),d.length===0&&_&&f.rows.length!==l&&ce(i,s,{code:Q.ROW_COUNT,line:ae(r,f.start),message:`The table renders ${f.rows.length} body row(s) but the data at \`${c.path||"(root)"}\` has ${l} records \u2014 ${Math.abs(l-f.rows.length)} ${l>f.rows.length?"missing":"extra"}.`,hint:'Emit exactly one <tr> per record. If you meant to show only some of them, state the cut ("top 10 of 23") in the page itself.'}))}}function Qu(r,t){let e=new Array(r.length).fill(-1);if(r.every(s=>s.dataIndex!=null)){let s=0;if(r.forEach((o,a)=>{let c=o.dataIndex;c>=0&&c<t.values.length&&(e[a]=c,s+=1)}),s===r.length)return e}e.fill(-1);let n=new Set,i=0;if(r.forEach((s,o)=>{for(let a=0;a<t.labels.length;a+=1){if(n.has(a))continue;let c=ze(t.labels[a]);if(c.length>=2&&s.context.indexOf(c)>=0){e[o]=a,n.add(a),i+=1;break}}}),i===r.length)return e;if(r.length!==t.values.length)return null;for(let s=0;s<r.length;s+=1)e[s]=s;return e}function em(r,t){let e=null,n=0;for(let s of t){let o=s.labels.filter(a=>{let c=ze(a);return c.length>=2&&r.some(l=>l.context.indexOf(c)>=0)}).length;o>n&&(n=o,e=s)}if(n>=2)return e;let i=t.filter(s=>s.values.length===r.length);return i.length===1?i[0]:null}function tm(r,t,e,n,i,s){s.barGroups=t.map(o=>o.length),s.boundBars=0;for(let o of t){let a=em(o,e);if(!a)continue;if(a.values.length!==o.length){ce(n,i,{code:Q.BAR_COUNT,line:ae(r,o[0].start),message:`The chart draws ${o.length} bar(s) but the series at \`${a.path||"(root)"}\` has ${a.values.length} value(s).`,hint:"Draw one bar per value. A dropped bar silently removes a whole category from the reader's view of the data."});continue}let c=Qu(o,a);if(!c||c.some(u=>u<0))continue;s.boundBars+=o.length;let l=[];for(let u=0;u<o.length;u+=1)o[u].extent>0&&a.values[c[u]]>0&&l.push(u);if(l.length>=Lu){let u=l.map(y=>o[y].extent/a.values[c[y]]).sort((y,b)=>y-b),m=Math.floor(u.length/2),f=u.length%2?u[m]:(u[m-1]+u[m])/2,h=Math.max(...a.values.map(y=>Math.abs(y))),_=f*h;if(f>0&&_>0)for(let y of l){let b=a.values[c[y]],g=f*b,k=Math.abs(o[y].extent-g)/_;if(k<=ju)continue;let O=o[y].unit==="%"?"%":"";ce(n,i,{code:Q.BAR_PROPORTION,line:ae(r,o[y].start),message:`The bar for ${JSON.stringify(a.labels[c[y]])} (value ${b}) is drawn at ${$s(o[y].extent)}${O}, but every other bar in this chart puts it at ${$s(g)}${O} \u2014 off by ${Math.round(k*100)}% of the full-scale bar. The chart misrepresents the data.`,hint:"Every bar in one chart must use the SAME value\u2192length scale. Compute each length from its datum with one formula (value / max * 100), never by writing the numbers out by hand."})}}let d=a.values.reduce((u,m)=>u+m,0),p=Math.max(...a.values.map(u=>Math.abs(u)));for(let u=0;u<o.length;u+=1){let m=a.values[c[u]],f=o[u].context;if(!f)continue;let h=(f.match(/-?\d[\d,]*(?:\.\d+)?/g)||[]).map(_=>Number(_.replace(/,/g,""))).filter(_=>Number.isFinite(_));h.length&&(h.some(_=>Math.abs(_-m)<1e-9)||d>0&&h.some(_=>Math.abs(_-m/d*100)<.6)||p>0&&h.some(_=>Math.abs(_-m/p*100)<.6)||ce(n,i,{code:Q.VALUE_MISMATCH,line:ae(r,o[u].start),message:`The row for ${JSON.stringify(a.labels[c[u]])} prints ${h.slice(0,3).join(", ")} but its datum is ${m}.`,hint:"Print the figure your tools returned, unchanged, and use that same figure everywhere it appears on the page."}))}}}var rm=/^(flex|inline-flex|grid|inline-grid)$/;function nm(r,t,e,n,i,s){let o=0;Le(t,a=>{if(Zr.has(a.tag))return;let c=yt(a.attrs.style).width;if(!c)return;let l=Bs(c);if(l==null||l<=0||!Js(a,e))return;o+=1;let d=Ps(a,e);if(d==="none"){ce(n,i,{code:Q.ZERO_WIDTH,line:ae(r,a.start),message:`<${a.tag}> is given style="width:${c}" but its effective display is \`none\` \u2014 it is not rendered at all.`,hint:"Remove the display:none rule that matches this element, or remove the element. A width on a display:none box is dead code."});return}if(d!=="inline")return;let p=a.parent;if(p&&p.tag!=="#root"&&rm.test(Ps(p,e)))return;let u=fe(a,"position",e);if(u==="absolute"||u==="fixed")return;let m=fe(a,"float",e);m==="left"||m==="right"||ce(n,i,{code:Q.ZERO_WIDTH,line:ae(r,a.start),message:`<${a.tag}${a.attrs.class?` class="${a.attrs.class}"`:""}> is given style="width:${c}" but its effective display is \`inline\` \u2014 CSS IGNORES width on a non-replaced inline box, so this bar renders with no length at all. The source looks right; the page will not.`,hint:"Give the bar display:block or display:inline-block (or make its container display:flex). A <span> is inline by DEFAULT \u2014 that alone is enough to swallow the width."})}),s.percentWidthBars=o}function im(r,t,e,n,i){Le(t,s=>{let o=Wr(fe(s,"width",e));if(!(o==null||o<=0))for(let a=s.parent;a&&a.tag!=="#root";a=a.parent){let c=Wr(fe(a,"width",e));if(c==null||c<=0)continue;if(o<=c)return;let l=fe(a,"overflow",e)||fe(a,"overflow-x",e);if(l!=="hidden"&&l!=="clip")return;ce(n,i,{code:Q.OVERFLOW,line:ae(r,s.start),message:`<${s.tag}> is ${o}px wide inside a ${c}px ancestor with overflow:${l} \u2014 ${Math.round(o-c)}px of it is clipped and can never be seen.`,hint:"Size the child from its container (a percentage, or max-width:100%), or widen the container. Content the reader cannot see is content you did not publish."});return}})}var sm=[{re:/\[object (?:Object|Array|Promise|Map|Set|Null|Undefined)\]/g,what:"an object stringified instead of a field being picked off it"},{re:/\$\{[^}\n]{0,80}\}/g,what:"an un-substituted JavaScript template placeholder"},{re:/\{\{[^}\n]{0,80}\}\}/g,what:"an un-substituted moustache placeholder"},{re:/(?:^|[^\w.])(NaN)(?![\w])/g,what:"NaN \u2014 an arithmetic result that was never a number"},{re:/(?:^|[^\w.])(-?Infinity)(?![\w])/g,what:"Infinity \u2014 a division by zero reached the page"}],om=/^(undefined|null)$/i,am=new Set(["td","th","li","span","div","strong","em","b"]);function cm(r,t,e,n,i){let s=0;for(let o of qu(t)){let a=o.value;s+=a.length;for(let l of sm){l.re.lastIndex=0;let d;for(;(d=l.re.exec(a))!==null;){let p=d[1]==null?d[0]:d[1];ce(e,n,{code:Q.PLACEHOLDER_TEXT,line:ae(r,o.start+d.index+d[0].indexOf(p)),message:`The page prints ${JSON.stringify(p.slice(0,60))} as VISIBLE TEXT \u2014 ${l.what}. A reader sees this literally.`,hint:"Format the value before it reaches the page: pick the field you meant off the object, and guard the arithmetic so a missing input renders as an em dash rather than NaN."}),d.index===l.re.lastIndex&&(l.re.lastIndex+=1)}}let c=Cs(a).trim();om.test(c)&&am.has(o.parent.tag)&&ce(e,n,{code:Q.PLACEHOLDER_TEXT,line:ae(r,o.start),message:`A <${o.parent.tag}> contains only the literal text "${c}" \u2014 the value it was meant to hold was ${c}.`,hint:'Render an em dash (\u2014) or "n/a" for a missing value; never let the JavaScript literal reach the reader.'})}i.textCharsScanned=s}function ir({html:r,data:t}){let e=typeof r=="string"?r:"",n=[],i={};if(!e.trim())return{ok:!1,defects:[{code:"empty-content",line:1,message:"No html was passed to the check.",hint:"Pass the exact page source you are about to publish."}],checked:{tables:0,bodyRows:0,bars:0,barGroups:[],boundBars:0,seriesInData:0,collections:[]}};let s=Du(e),o=Mu(s),a=Vu(s),c=Zu(s,o),l=Gu(t),d={tables:a.length,bodyRows:a.reduce((p,u)=>p+u.rows.length,0),bars:c.reduce((p,u)=>p+u.length,0),barGroups:[],boundBars:0,seriesInData:l.series.length,collections:[]};return Xu(e,s,a,l.collections,n,i,d.collections),tm(e,c,l.series,n,i,d),nm(e,s,o,n,i,d),im(e,s,o,n,i),cm(e,s,n,i,d),n.sort((p,u)=>(p.line||0)-(u.line||0)),{ok:n.length===0,defects:n,checked:d}}function lm(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Tu(Au(import.meta.url)),t=Ru(r,"..","bin","mcp-skill.mjs");return Ou(t)?t:null}var Ds={id:"report-check",serverName:"report_check",allowedTools:["mcp__report_check__*"],envKeys:[],description:"Report check \u2014 verify a rendered report page against the DATA it was built from (row counts, bar proportionality, collapsed bars, placeholder residue) before publishing it.",promptFragment:`## Report Check (run this BEFORE you publish a data page)
794
+ When you are about to publish a page that RENDERS DATA \u2014 a table of records, a
795
+ bar chart, a set of meters \u2014 call \`report_check\` first with the exact \`html\`
796
+ you are about to publish and the \`data\` you built it from (the raw tool
797
+ results, as JSON). It compares the two and tells you where the page disagrees
798
+ with the data: a table short of rows, a bar drawn at the wrong length, a printed
799
+ number that is not its datum, a bar whose width the CSS silently throws away, an
800
+ \`[object Object]\` or an un-substituted \`\${\u2026}\` left in a cell.
801
+
802
+ This is NOT the publish validator \u2014 that one runs server-side and checks the
803
+ MARKUP. This one checks the FACTS. Pass the data unchanged; do not write your own
804
+ expectations and do not describe the page. The check derives what must be true
805
+ from the data by itself.
806
+
807
+ Then READ the \`checked\` block in the result: it says how many tables, rows and
808
+ bars were actually found. If it reports 0 bars for a page full of bars, the check
809
+ never saw your chart and a clean verdict means nothing.`,resolve(){let r=lm();return r?{type:"stdio",command:"node",args:[r,"../dist/reportCheck.js","reportCheckSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,t){if(r!=="report_check")return JSON.stringify({error:`Unknown tool: ${r}`});try{let e=typeof t?.html=="string"?t.html:"";if(!e.trim())return JSON.stringify({error:"html is required \u2014 pass the exact page source you are about to publish."});let n=t?.data;if(typeof n=="string")try{n=JSON.parse(n)}catch{return JSON.stringify({error:"data was a string but not valid JSON \u2014 pass the data as a JSON object."})}return n==null?JSON.stringify({error:"data is required \u2014 pass the tool results the page was built from, unchanged."}):JSON.stringify(ir({html:e,data:n}))}catch(e){return JSON.stringify({error:`report_check failed: ${e.message}`})}},tools:[{name:"report_check",description:'Pre-flight a data page BEFORE publishing it: compares the rendered HTML against the DATA it was built from and reports every place they disagree. Catches what the publish validator structurally cannot \u2014 a table that renders fewer rows than the data has records, a bar drawn at a length that is not proportional to its value, a number printed beside a bar that is not that bar\'s datum, a bar whose width is silently nullified by the CSS cascade, and placeholder residue ([object Object], NaN, an un-substituted ${\u2026}) left in visible text. Pass the data UNCHANGED, exactly as your tools returned it (wrap a bare array as {"rows": [...]}) \u2014 the check discovers the collections and series inside it and derives what must be true on its own. Do NOT write your own expectations. Returns { ok, defects:[{code,line,message,hint}], checked }. Always read `checked`: it reports how many tables, rows and bars were found, so a clean `ok:true` with `bars: 0` on a chart page tells you the check never saw your chart.',input_schema:{type:"object",properties:{html:{type:"string",description:"The exact HTML you are about to publish (the same string you would pass to artifact_publish)."},data:{type:"object",description:'The data the page was built from, as JSON \u2014 the raw tool results. Any shape: arrays of records and label/value series are found automatically. Wrap a bare top-level array as {"rows": [...]}.'}},required:["html","data"]}}]};function gm(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=fm(ym(import.meta.url)),t=hm(r,"..","bin","mcp-skill.mjs");return Zs(t)?t:null}function bt(){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=mm(um(),".zibby","config.json");return Zs(r)&&JSON.parse(pm(r,"utf-8")).sessionToken||null}catch{return null}}function _t(){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 bm(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Vs(r){return`${bm()}:artifact:${r}`}var Ye="headings, paragraphs, **bold**, *italic*, `inline code`, fenced code blocks, bullet + numbered lists, blockquotes, horizontal rules, links, and GitHub-style pipe tables (including |---:| alignment)",or="raw HTML (tags are escaped and print as literal text), images, nested lists, footnotes and strikethrough",gt=2,We=0;function Xr(r,t){return JSON.stringify({published:!1,stop:!0,attemptsUsed:gt,defects:t||[],error:r,instruction:`STOP. You have used both publish attempts and the page is still rejected. Do NOT call artifact_publish or artifact_update again in this turn. Tell the user plainly that you could not produce a clean page, say in one line what was wrong, and give them the content directly in the chat instead. A broken link is worse than an honest "I couldn't".`})}function _m(r,t,e){return JSON.stringify({published:!1,stop:!1,attemptsRemaining:gt-We,defects:e||[],error:t,instruction:"The page was NOT published and no URL exists. Fix EXACTLY the defects listed above and call once more \u2014 you get ONE more attempt, then this tool will stop you."+(r==="html"?` You are on the \`html\` path, where you author the entire document and every mistake ships. Unless this page genuinely needs a custom visual layout, the fastest and most reliable fix is to re-send the SAME content as \`markdown\` \u2014 Zibby then generates the document skeleton, CSS and tables for you and these defects become impossible. Markdown supports ${Ye}.`:` Markdown supports ${Ye}; it does NOT support ${or}.`)})}var qs="The page WAS published and the url is valid. This only means the data\u2194render pre-flight could not reach a verdict \u2014 nothing is known to be wrong. Open the page yourself if the figures matter.";function km(r){let t=new Set,e=(r||[]).map((i,s)=>{let o=i.line?` line ${i.line}:`:"",a="";return i.hint&&!t.has(i.code)&&(t.add(i.code),a=` \u2014 ${i.hint}`),`${s+1}. [${i.code}]${o} ${i.message}${a}`}),n=e.length;return`Artifact NOT published and NOTHING was sent \u2014 the page was checked against the \`data\` you passed and disagrees with it in ${n} place${n===1?"":"s"}:
810
+ ${e.join(`
811
+ `)}`}function wm(r,t){let e;try{e=ir({html:r,data:t})}catch(s){return{unverified:{status:"unverified",reason:`the data\u2194render pre-flight threw and was skipped: ${String(s?.message||s).slice(0,200)}`,note:qs}}}if(!e?.ok)return{rejected:{message:km(e?.defects),defects:e?.defects||[]}};let n=e.checked||{};return(Number(n.tables)||0)+(Number(n.bars)||0)===0?{unverified:{status:"unverified",reason:"the pre-flight found no tables and no bars in this page, so it had nothing to compare against your data \u2014 a clean result here proves nothing",checked:n,note:qs}}:null}function Ms(r,t,e){return We+=1,{__rejected:!0,payload:We>=gt?Xr(t,e):_m(r,t,e)}}async function Sm(r){let t=bt();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let e=await fetch(`${_t()}/credits/artifacts`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let n=await e.text().catch(()=>""),i=null;try{i=JSON.parse(n)}catch{}let s=new Error(e.status===422&&i?.error?i.error:`artifact write failed (${e.status}): ${n.slice(0,300)}`);throw s.status=e.status,Array.isArray(i?.defects)&&(s.defects=i.defects),s}return e.json()}async function Fs(r,t,e){let n=e?wm(e.html,e.data):null;if(n?.rejected)return Ms(t,n.rejected.message,n.rejected.defects);try{let i=await Sm(r);return We=0,n?.unverified&&(i.__preflightNote=n.unverified),i}catch(i){if(i?.status!==422)throw i;return Ms(t,i.message,i.defects)}}async function Xs(r){let t=bt();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let e=await fetch(`${_t()}/credits/artifacts/${encodeURIComponent(r)}`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`artifact get failed (${e.status}): ${n.slice(0,300)}`)}return e.json()}async function Ks(r,t,e={}){let n=bt();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let i=await fetch(`${_t()}/credits/artifacts/${encodeURIComponent(r)}/${t}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){let s=await i.text().catch(()=>""),o=null;try{o=JSON.parse(s)}catch{}throw new Error(o?.error||`artifact ${t} failed (${i.status}): ${s.slice(0,300)}`)}return i.json()}var Vr=60;function Gs(r,t){let e=Math.max(0,t-Math.floor(Vr/2)),i=r.slice(e,e+Vr).replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");return(e>0?"\u2026":"")+i+(e+Vr<r.length?"\u2026":"")}function vm(r,t){if(r===t)return null;let e=Math.min(r.length,t.length),n=0;for(;n<e&&r[n]===t[n];)n+=1;return{kind:n===e?t.length<r.length?"truncated":"longer":"diverged",sentChars:r.length,storedChars:t.length,delta:t.length-r.length,firstDiffAt:n,sentExcerpt:Gs(r,n),storedExcerpt:Gs(t,n)}}var sr="Read-back compares the STORED SOURCE with what was sent (transport/storage integrity only). It does NOT check that the page renders correctly.";async function Hs(r,t){let e;try{e=await Xs(r)}catch(s){return{status:"unverified",scope:sr,reason:`read-back request failed: ${String(s?.message||s).slice(0,200)}`,note:"The page WAS published and the url is valid \u2014 this only means the extra integrity check could not run. No action needed."}}let n=e?.content;if(typeof n!="string")return{status:"unverified",scope:sr,reason:"read-back returned no content field",note:"The page WAS published and the url is valid \u2014 this only means the extra integrity check could not run. No action needed."};if(n===""&&t!=="")return{status:"unverified",scope:sr,reason:"read-back returned empty content, which the backend also returns when its object-store read errors \u2014 indistinguishable, so this is inconclusive rather than a mismatch",note:"The page WAS published and the url is valid. If the page looks blank when opened, re-send the same content with artifact_update."};let i=vm(t,n);return i?{status:"mismatch",scope:sr,...i,note:`The stored page source is NOT what was sent (${i.kind}: sent ${i.sentChars} chars, stored ${i.storedChars}, first difference at character ${i.firstDiffAt}). The url exists and the page is live, so do NOT re-publish a new one. You may call artifact_update ONCE with the identical content to rewrite the blob; if it differs again, stop and tell the user the published page may be incomplete rather than retrying.`}:null}async function zs(r,t){let e=bt();if(!e)return;let n=await fetch(`${_t()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:"store",scope:Vs(r),content:JSON.stringify(t)})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`artifact index write failed (${n.status}): ${i.slice(0,200)}`)}}async function Im(r){let t=bt();if(!t)return null;let e=await fetch(`${_t()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:"recall",scope:Vs(r)})});if(!e.ok)return null;let n=await e.json().catch(()=>null);if(!n?.found||!n?.memory?.content)return null;try{return JSON.parse(n.memory.content)}catch{return null}}function Ys(r){let t=typeof r?.html=="string"&&r.html.length>0,e=typeof r?.markdown=="string"&&r.markdown.length>0;return t&&e?{error:"Pass EITHER markdown OR html, not both \u2014 they are different rendering paths. Use markdown unless the page needs a custom visual layout."}:e?{format:"markdown",content:r.markdown}:t?{format:"html",content:r.html}:null}function Ws(r,t){let e=r?.data;if(e==null)return null;if(!t||t.format!=="html")return{error:"`data` is only meaningful together with `html`. The pre-flight reads a rendered HTML document (tables, bars, CSS), so on the markdown path it would check nothing while reporting a clean page \u2014 that is worse than not checking. Re-send WITHOUT `data`. Do NOT switch to `html` just to get the check: on the markdown path Zibby generates the document, so the collapsed-bar and broken-geometry defects it looks for cannot happen there in the first place."};let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{return{error:'`data` was a string but not valid JSON \u2014 pass the tool results as a JSON object (wrap a bare array as {"rows": [...]}).'}}return{preflight:{html:t.content,data:n}}}var Qs={id:"artifact",callsBackend:!0,meta:dm.artifact,serverName:"artifact",allowedTools:["mcp__artifact__*"],description:"Artifacts \u2014 publish a self-contained, shareable HTML/Markdown page to Zibby and get back a URL; the index of what you published is your memory.",promptFragment:`## Artifacts (publish a shareable page, remember what you made)
794
812
  You can PUBLISH a standalone page \u2014 a status report, a plan, a comparison table,
795
813
  a dashboard-y summary, a diagram, a "here's what I found" write-up \u2014 and get back
796
814
  a shareable URL.
@@ -798,7 +816,7 @@ a shareable URL.
798
816
  ### WRITE IT AS MARKDOWN. That is the default, and it is not a stylistic hint.
799
817
  Pass \`markdown\` and Zibby generates the whole document for you \u2014 doctype, head,
800
818
  CSS, typography, dark mode, table styling. You supply only the CONTENT. Markdown
801
- supports ${Me}. It does NOT support ${zt}.
819
+ supports ${Ye}. It does NOT support ${or}.
802
820
 
803
821
  Pass \`html\` ONLY when the page genuinely needs a visual layout Markdown cannot
804
822
  express \u2014 a bar chart, a gauge, a custom grid, an SVG diagram. On the html path
@@ -817,11 +835,22 @@ up saying 42 in one place and 45 in another. If you need a total, compute it wit
817
835
  a tool (or restate the figures exactly as your tools returned them) and cite the
818
836
  same figure everywhere it appears.
819
837
 
838
+ ### If an html page RENDERS DATA, pass \`data\` too.
839
+ A table of records, a bar chart, a row of meters \u2014 pass the raw tool results the
840
+ page was built from as \`data\`, unchanged and unsummarised. The page is then
841
+ compared against them before anything is sent, which catches the failures nobody
842
+ sees until a human opens the link: a table short of rows, a bar drawn at a length
843
+ that is not its value, a leftover \`\${\u2026}\` or \`[object Object]\`. Do not write
844
+ your own expectations \u2014 the check derives them from the data. Prose pages don't
845
+ need it, and it is an error on the \`markdown\` path.
846
+
820
847
  ### The page is validated BEFORE a URL exists.
821
848
  If the content is broken you get back the exact defects and their line numbers,
822
- and no page is created. You get ONE retry. After that the tool STOPS you \u2014 at
823
- which point say plainly that you could not produce a clean page and put the
824
- content in the chat instead. Do not keep trying.
849
+ and no page is created. You get ONE retry \u2014 and the \`data\` check and the server
850
+ check SHARE those two attempts, so a locally refused page costs an attempt just
851
+ like a rejected one. After that the tool STOPS you \u2014 at which point say plainly
852
+ that you could not produce a clean page and put the content in the chat instead.
853
+ Do not keep trying.
825
854
 
826
855
  THE CONTENT COMES FROM THIS CONVERSATION \u2014 NEVER FROM YOUR IMAGINATION.
827
856
  When someone says "make me a page / an artifact / a report", they mean THE THING
@@ -841,25 +870,59 @@ situation in which "\u793A\u4F8B / sample / demo" belongs in a title you publish
841
870
 
842
871
  Tools:
843
872
  - artifact_publish: Publish a NEW page. Pass a \`title\` and EITHER \`markdown\`
844
- (the default \u2014 prefer this) OR \`html\` (never both). Optional \`kind\` (e.g.
845
- "report", "plan", "dashboard"), \`favicon\` (an emoji), and \`summary\` (one line
846
- for your own index). Returns { id, url }. Share the url; keep the id if you'll
847
- update it later.
873
+ (the default \u2014 prefer this) OR \`html\` (never both). Pass \`data\` when the html
874
+ page renders a dataset (see above). Optional \`kind\` (e.g. "report", "plan",
875
+ "dashboard"), \`favicon\` (an emoji), and \`summary\` (one line for your own
876
+ index). Returns { id, url }. Share the url; keep the id if you'll update it
877
+ later.
848
878
  - artifact_update: Revise an EXISTING page by \`id\` (same url, new version). Pass
849
879
  the fields to change (\`title\`, \`markdown\`|\`html\`).
850
880
  - artifact_get: Fetch one artifact by \`id\` \u2192 { metadata, content } so you can
851
881
  reuse / edit / re-publish it.
882
+ - artifact_share: Make a page readable WITHOUT a Zibby login \u2192 { url, password }.
883
+ - artifact_unshare: Revoke that, immediately and for everyone.
884
+
885
+ ### If the people you are answering have no Zibby account, SHARE the page.
886
+ A published url only opens for logged-in members of this project. When you are
887
+ talking to a Lark or Slack channel, most of the people there are not Zibby users \u2014
888
+ so the link you just posted is, for them, a login screen they cannot get past.
889
+
890
+ So: when you publish a page for a chat channel, call \`artifact_share\` and post
891
+ the url AND the password together, in the same reply, formatted so both are easy
892
+ to copy. Copy the password character for character \u2014 it is case-sensitive, it is
893
+ shown exactly once, and nothing can look it up afterwards (you can only issue a
894
+ new one, which kills the old). Do not paraphrase it, do not "tidy" it, and do not
895
+ split it across lines.
896
+
897
+ This password is a page-viewing password and nothing else \u2014 it is not an account
898
+ password, it grants no access to Zibby, this project, or any other artifact, and
899
+ it is revocable with \`artifact_unshare\`. Treat it as the ordinary contents of the
900
+ message you are writing. That is the ONLY kind of secret you may ever put in a
901
+ message: never paste a token, key, or credential into chat, a prompt, or a page.
902
+
903
+ Sharing is per page and opt-in \u2014 publishing alone never exposes anything. If the
904
+ page is sensitive and the channel is wide, say so and let them decide rather than
905
+ sharing it silently.
852
906
 
853
907
  To recall WHAT YOU HAVE ALREADY PUBLISHED, use your kv-memory tool
854
908
  kv_recall_prefix with keyPrefix "artifact:" \u2014 each entry is the index record
855
909
  { id, title, url, kind, createdAt, summary } for a page you made. (Publishing
856
- records this automatically; you don't store it yourself.)`,resolve(){let r=iu();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/artifact.js","artifactSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"artifact_publish":{if(Ke>=dt)return Br("Publish budget already spent this turn.",[]);let e=typeof t?.title=="string"?t.title.trim():"";if(!e)return JSON.stringify({error:"title is required"});let n=Ss(t);if(!n)return JSON.stringify({error:"provide exactly one of markdown (preferred) or html (non-empty string)"});if(n.error)return JSON.stringify({error:n.error});let i={title:e,[n.format]:n.content};typeof t?.kind=="string"&&t.kind.trim()&&(i.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(i.favicon=t.favicon.trim());let s=await ks(i,n.format);if(s?.__rejected)return s.payload;let o=s?.id,a=s?.url;if(!o||!a)return JSON.stringify({error:"artifact write returned no id/url",response:s});let c={id:o,title:e,url:a,kind:i.kind||null,createdAt:s.createdAt||new Date().toISOString(),summary:typeof t?.summary=="string"&&t.summary.trim()?t.summary.trim():e};try{await ws(o,c)}catch(d){return JSON.stringify({id:o,url:a,indexWarning:d.message})}return JSON.stringify({id:o,url:a})}case"artifact_update":{if(Ke>=dt)return Br("Publish budget already spent this turn.",[]);let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=Ss(t);if(n?.error)return JSON.stringify({error:n.error});let i=typeof t?.title=="string"?t.title.trim():"";if(!n&&!i)return JSON.stringify({error:"nothing to update \u2014 pass a new title and/or markdown|html"});let s={id:e};i&&(s.title=i),n&&(s[n.format]=n.content),typeof t?.kind=="string"&&t.kind.trim()&&(s.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(s.favicon=t.favicon.trim());let o=await ks(s,n?.format);if(o?.__rejected)return o.payload;let a=o?.url;if(!a)return JSON.stringify({error:"artifact update returned no url",response:o});let c=await lu(e)||{},d={...c,id:e,url:a,title:i||c.title||"Untitled",kind:s.kind||c.kind||null,createdAt:c.createdAt||o.createdAt||new Date().toISOString(),updatedAt:o.updatedAt||new Date().toISOString()};typeof t?.summary=="string"&&t.summary.trim()?d.summary=t.summary.trim():d.summary||(d.summary=d.title);try{await ws(e,d)}catch(l){return JSON.stringify({id:e,url:a,indexWarning:l.message})}return JSON.stringify({id:e,url:a})}case"artifact_get":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=await cu(e);return JSON.stringify(n)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"artifact_publish",description:`Publish a NEW self-contained, shareable page (report/plan/table/dashboard/diagram/write-up) and get back a shareable URL. USE \`markdown\` \u2014 it is the default path and Zibby generates the entire document for you (doctype, head, CSS, dark mode, table styling); you supply only the content, so the page cannot come out malformed. Markdown supports ${Me}; it does NOT support ${zt}. Use \`html\` ONLY when the page needs a visual layout Markdown cannot express (a bar chart, a gauge, a custom grid, an SVG diagram) \u2014 on that path you author the whole document and every mistake ships verbatim. Never pass both. Every figure on the page must come from a tool result or this conversation \u2014 do not do arithmetic in prose and print the result, and use the same number everywhere it appears. The content MUST come from the current conversation or data you fetched this turn; if you are not sure what the page should be about, ASK instead of calling this tool, and never publish a demo/sample/placeholder or an account-overview page as a stand-in. On the html path keep all CSS/JS/images INLINE (inline <style>/<script>, data: URIs) and send real tags (never &lt;escaped&gt; markup) \u2014 the page is sandboxed on view with no network at all, so every external URL is dead. The content is VALIDATED before any URL exists: if it is broken you get the exact defects and line numbers back, you get ONE retry, and then the tool stops you. Returns { id, url }.`,input_schema:{type:"object",properties:{title:{type:"string",description:"The page title (also the browser tab title)."},markdown:{type:"string",description:`PREFERRED. The page content as Markdown \u2014 Zibby renders it into a styled, self-contained document, so you never author a skeleton. Supports ${Me}. Does NOT support ${zt}. Provide this OR html, never both.`},html:{type:"string",description:"The EXCEPTION path \u2014 only for a layout Markdown cannot express (bar chart, gauge, custom grid, SVG diagram). A self-contained HTML document or fragment, served VERBATIM: you own the doctype, head, CSS and every tag. All assets must be inline (<style>/<script>, data: URIs). Provide this OR markdown, never both."},kind:{type:"string",description:'Optional label for what this is, e.g. "report", "plan", "dashboard", "diagram". Stored in your index.'},favicon:{type:"string",description:'Optional emoji used as the browser-tab icon, e.g. "\u{1F4CA}".'},summary:{type:"string",description:"Optional one-line summary for your own index (defaults to the title). Helps you recall later what this page was."}},required:["title"]}},{name:"artifact_update",description:"Revise an EXISTING artifact by id \u2014 the shareable URL stays the same, the content is replaced (new version). Pass the fields to change (title and/or markdown|html). Prefer `markdown` for the same reason artifact_publish does: Zibby generates the document, so it cannot come out malformed. An update is validated exactly like a publish \u2014 if the new content is broken it is REFUSED and the page keeps its last good version. Returns { id, url }.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to update (from a prior artifact_publish, or your kv-memory "artifact:" index).'},title:{type:"string",description:"New title (optional)."},markdown:{type:"string",description:`PREFERRED. New Markdown content (optional) \u2014 Zibby renders the document skeleton. Supports ${Me}. Provide this OR html.`},html:{type:"string",description:"New HTML content (optional), served verbatim \u2014 only for layouts Markdown cannot express. Provide this OR markdown."},kind:{type:"string",description:"Optional updated kind label."},favicon:{type:"string",description:"Optional updated emoji favicon."},summary:{type:"string",description:"Optional updated one-line index summary."}},required:["id"]}},{name:"artifact_get",description:'Fetch ONE artifact you published, by id \u2192 { metadata, content }. Use to reuse / edit / re-publish a page. To LIST what you have published, use your kv-memory tool kv_recall_prefix with keyPrefix "artifact:".',input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id."}},required:["id"]}}]};import{createRequire as du}from"node:module";import{existsSync as Rs,mkdirSync as pu,writeFileSync as Os}from"node:fs";import{dirname as Es,join as Ge,resolve as js}from"node:path";import{fileURLToPath as xs}from"node:url";var Ls=du(import.meta.url),Jr=null;function uu(){return Jr||(Jr=Ls("echarts")),Jr}var qr=null;function mu(){return qr||(qr=Ls("@resvg/resvg-js")),qr}var fu=800,hu=600,yu=4096,gu=16,Ts=60,$s="Noto Sans";function _u(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Es(xs(import.meta.url)),t=js(r,"..","bin","mcp-skill.mjs");return Rs(t)?t:null}function bu(){let r=Es(xs(import.meta.url)),t=js(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(e=>Ge(t,e)).filter(e=>Rs(e))}function ku(){let r=process.env.ZIBBY_NODE_SESSION_PATH,t=process.env.ZIBBY_SESSION_PATH,e=r||(t?Ge(t,"chart-render"):Ge(process.cwd(),".zibby","output","charts"));return pu(e,{recursive:!0}),e}function Ae(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function As(r,t){let e=Number(r);return Number.isFinite(e)?Math.max(gu,Math.min(yu,Math.round(e))):t}function Dr(r){return typeof r!="string"||r.length<=Ts?r:`${r.slice(0,Ts-1)}\u2026`}function Zt(r){if(Array.isArray(r))for(let t=0;t<r.length;t++){let e=r[t];typeof e=="string"?r[t]=Dr(e):Ae(e)&&typeof e.name=="string"&&(e.name=Dr(e.name))}}function wu(r){for(let n of["xAxis","yAxis"]){let i=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let s of i)Ae(s)&&Zt(s.data)}let t=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of t)Ae(n)&&Zt(n.indicator);Ae(r.legend)&&Zt(r.legend.data);let e=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of e)Ae(n)&&(typeof n.name=="string"&&(n.name=Dr(n.name)),Zt(n.data))}function Su(r){let t=JSON.parse(JSON.stringify(r));return t.animation=!1,t.backgroundColor==null&&(t.backgroundColor="#fff"),Ae(t.textStyle)||(t.textStyle={}),t.textStyle.fontFamily==null&&(t.textStyle.fontFamily=$s),wu(t),t}function vu(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Iu(r,t,e){let i=uu().init(null,null,{renderer:"svg",ssr:!0,width:t,height:e});try{return i.setOption(r),i.renderToSVGString()}finally{i.dispose()}}function Nu(r){let{Resvg:t}=mu();return new t(r,{font:{fontFiles:bu(),loadSystemFonts:!0,defaultFontFamily:$s}}).render().asPng()}var Ps={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)
910
+ records this automatically; you don't store it yourself.)`,resolve(){let r=gm();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/artifact.js","artifactSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"artifact_publish":{if(We>=gt)return Xr("Publish budget already spent this turn.",[]);let e=typeof t?.title=="string"?t.title.trim():"";if(!e)return JSON.stringify({error:"title is required"});let n=Ys(t);if(!n)return JSON.stringify({error:"provide exactly one of markdown (preferred) or html (non-empty string)"});if(n.error)return JSON.stringify({error:n.error});let i=Ws(t,n);if(i?.error)return JSON.stringify({error:i.error});let s={title:e,[n.format]:n.content};typeof t?.kind=="string"&&t.kind.trim()&&(s.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(s.favicon=t.favicon.trim());let o=await Fs(s,n.format,i?.preflight);if(o?.__rejected)return o.payload;let a=o?.id,c=o?.url;if(!a||!c)return JSON.stringify({error:"artifact write returned no id/url",response:o});let l={id:a,url:c};o.__preflightNote&&(l.preflight=o.__preflightNote);let d=await Hs(a,n.content);d&&(l.readBack=d);let p={id:a,title:e,url:c,kind:s.kind||null,createdAt:o.createdAt||new Date().toISOString(),summary:typeof t?.summary=="string"&&t.summary.trim()?t.summary.trim():e};try{await zs(a,p)}catch(u){l.indexWarning=u.message}return JSON.stringify(l)}case"artifact_update":{if(We>=gt)return Xr("Publish budget already spent this turn.",[]);let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=Ys(t);if(n?.error)return JSON.stringify({error:n.error});let i=typeof t?.title=="string"?t.title.trim():"";if(!n&&!i)return JSON.stringify({error:"nothing to update \u2014 pass a new title and/or markdown|html"});let s=Ws(t,n);if(s?.error)return JSON.stringify({error:s.error});let o={id:e};i&&(o.title=i),n&&(o[n.format]=n.content),typeof t?.kind=="string"&&t.kind.trim()&&(o.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(o.favicon=t.favicon.trim());let a=await Fs(o,n?.format,s?.preflight);if(a?.__rejected)return a.payload;let c=a?.url;if(!c)return JSON.stringify({error:"artifact update returned no url",response:a});let l={id:e,url:c};if(a.__preflightNote&&(l.preflight=a.__preflightNote),n){let u=await Hs(e,n.content);u&&(l.readBack=u)}let d=await Im(e)||{},p={...d,id:e,url:c,title:i||d.title||"Untitled",kind:o.kind||d.kind||null,createdAt:d.createdAt||a.createdAt||new Date().toISOString(),updatedAt:a.updatedAt||new Date().toISOString()};typeof t?.summary=="string"&&t.summary.trim()?p.summary=t.summary.trim():p.summary||(p.summary=p.title);try{await zs(e,p)}catch(u){l.indexWarning=u.message}return JSON.stringify(l)}case"artifact_get":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=await Xs(e);return JSON.stringify(n)}case"artifact_share":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=await Ks(e,"protect");return JSON.stringify({id:n.id,url:n.url,password:n.password,shared:!0,instruction:"Send BOTH the url and the password to the person who asked. Copy the password EXACTLY \u2014 it is case-sensitive and cannot be recovered later (call artifact_share again to issue a new one)."})}case"artifact_unshare":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=await Ks(e,"unprotect");return JSON.stringify({id:n.id,shared:!1,wasShared:n.wasShared})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"artifact_publish",description:`Publish a NEW self-contained, shareable page (report/plan/table/dashboard/diagram/write-up) and get back a shareable URL. USE \`markdown\` \u2014 it is the default path and Zibby generates the entire document for you (doctype, head, CSS, dark mode, table styling); you supply only the content, so the page cannot come out malformed. Markdown supports ${Ye}; it does NOT support ${or}. Use \`html\` ONLY when the page needs a visual layout Markdown cannot express (a bar chart, a gauge, a custom grid, an SVG diagram) \u2014 on that path you author the whole document and every mistake ships verbatim. Never pass both. Every figure on the page must come from a tool result or this conversation \u2014 do not do arithmetic in prose and print the result, and use the same number everywhere it appears. The content MUST come from the current conversation or data you fetched this turn; if you are not sure what the page should be about, ASK instead of calling this tool, and never publish a demo/sample/placeholder or an account-overview page as a stand-in. On the html path keep all CSS/JS/images INLINE (inline <style>/<script>, data: URIs) and send real tags (never &lt;escaped&gt; markup) \u2014 the page is sandboxed on view with no network at all, so every external URL is dead. PASS \`data\` WHENEVER THE HTML PAGE RENDERS A DATASET \u2014 a table of records, a bar chart, a row of meters. Give it the raw tool results the page was built from, unchanged; the page is then checked AGAINST that data before anything is sent, catching a table short of rows, a bar drawn at the wrong length, and leftover \${\u2026} or [object Object]. It costs you nothing when the page is right. Skip it for prose pages, and never pass it with \`markdown\` (that is an error, not a no-op). The content is VALIDATED before any URL exists: if it is broken \u2014 by that data check or by the server \u2014 you get the exact defects and line numbers back, you get ONE retry, and then the tool stops you. Both kinds of rejection share the SAME two attempts. Returns { id, url }.`,input_schema:{type:"object",properties:{title:{type:"string",description:"The page title (also the browser tab title)."},markdown:{type:"string",description:`PREFERRED. The page content as Markdown \u2014 Zibby renders it into a styled, self-contained document, so you never author a skeleton. Supports ${Ye}. Does NOT support ${or}. Provide this OR html, never both.`},html:{type:"string",description:"The EXCEPTION path \u2014 only for a layout Markdown cannot express (bar chart, gauge, custom grid, SVG diagram). A self-contained HTML document or fragment, served VERBATIM: you own the doctype, head, CSS and every tag. All assets must be inline (<style>/<script>, data: URIs). Provide this OR markdown, never both."},data:{type:"object",description:'Optional, and worth passing WHENEVER the html page renders a dataset (a table of records, a bar chart, meters): the raw tool results the page was built from, as JSON, UNCHANGED \u2014 do not summarise it and do not write your own expectations, the check derives what must be true by itself (wrap a bare array as {"rows": [...]}). The page is then verified against it BEFORE publishing: row counts, bar lengths vs their values, bars whose width the CSS throws away, and placeholder residue. If they disagree nothing is sent and you get the defects back, using one of your two attempts. Only valid with `html` \u2014 passing it with `markdown` is an error.'},kind:{type:"string",description:'Optional label for what this is, e.g. "report", "plan", "dashboard", "diagram". Stored in your index.'},favicon:{type:"string",description:'Optional emoji used as the browser-tab icon, e.g. "\u{1F4CA}".'},summary:{type:"string",description:"Optional one-line summary for your own index (defaults to the title). Helps you recall later what this page was."}},required:["title"]}},{name:"artifact_update",description:"Revise an EXISTING artifact by id \u2014 the shareable URL stays the same, the content is replaced (new version). Pass the fields to change (title and/or markdown|html). Prefer `markdown` for the same reason artifact_publish does: Zibby generates the document, so it cannot come out malformed. An update is validated exactly like a publish \u2014 including the optional `data` check when you send new `html` that renders a dataset \u2014 and if the new content is broken it is REFUSED, the page keeps its last good version, and the rejection shares the same two attempts as publish. Returns { id, url }.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to update (from a prior artifact_publish, or your kv-memory "artifact:" index).'},title:{type:"string",description:"New title (optional)."},markdown:{type:"string",description:`PREFERRED. New Markdown content (optional) \u2014 Zibby renders the document skeleton. Supports ${Ye}. Provide this OR html.`},html:{type:"string",description:"New HTML content (optional), served verbatim \u2014 only for layouts Markdown cannot express. Provide this OR markdown."},data:{type:"object",description:"Optional \u2014 same as on artifact_publish: when the new `html` renders a dataset, pass the raw tool results it was built from and the page is checked against them before anything is sent. Only valid alongside new `html`."},kind:{type:"string",description:"Optional updated kind label."},favicon:{type:"string",description:"Optional updated emoji favicon."},summary:{type:"string",description:"Optional updated one-line index summary."}},required:["id"]}},{name:"artifact_get",description:'Fetch ONE artifact you published, by id \u2192 { metadata, content }. Use to reuse / edit / re-publish a page. To LIST what you have published, use your kv-memory tool kv_recall_prefix with keyPrefix "artifact:".',input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id."}},required:["id"]}},{name:"artifact_share",description:"Make an artifact viewable WITHOUT a Zibby login, by password. Returns { url, password } \u2014 a link anyone can open plus the password that opens it. USE THIS when the people who need to read the page do not have Zibby accounts \u2014 the usual case is a Lark or Slack channel where you were asked for something and the channel members are not Zibby users. The normal artifact url only opens for logged-in members of this project, so for those recipients it is a dead link; this is what makes it readable. You MUST then send BOTH the url and the password in your reply, and copy the password EXACTLY (it is case-sensitive). It is shown ONCE and cannot be looked up afterwards \u2014 if it is lost, call this again to issue a new one, which also stops the old one working. Works on any artifact you published, old or new. Calling it again on an already-shared artifact replaces the password. Use artifact_unshare to revoke.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to share (from artifact_publish, or your kv-memory "artifact:" index).'}},required:["id"]}},{name:"artifact_unshare",description:"Revoke an artifact's password link \u2014 it goes back to being viewable only by logged-in members of this project. Immediate and total: anyone who already entered the password loses access too, not just new visitors. Safe to call on an artifact that was never shared.",input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id to stop sharing."}},required:["id"]}}]};import{createRequire as Nm}from"node:module";import{randomBytes as Om}from"node:crypto";import{existsSync as io,mkdirSync as Tm,writeFileSync as eo}from"node:fs";import{dirname as so,join as Ze,resolve as oo}from"node:path";import{fileURLToPath as ao}from"node:url";var co=Nm(import.meta.url),Qr=null;function Rm(){return Qr||(Qr=co("echarts")),Qr}var en=null;function Am(){return en||(en=co("@resvg/resvg-js")),en}var Em=800,xm=600,jm=4096,Lm=16,to=60,lo="Noto Sans",ro=256*1024;function $m(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=so(ao(import.meta.url)),t=oo(r,"..","bin","mcp-skill.mjs");return io(t)?t:null}function Pm(){let r=so(ao(import.meta.url)),t=oo(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(e=>Ze(t,e)).filter(e=>io(e))}function Cm(){let r=process.env.ZIBBY_NODE_SESSION_PATH,t=process.env.ZIBBY_SESSION_PATH,e=r||(t?Ze(t,"chart-render"):Ze(process.cwd(),".zibby","output","charts"));return Tm(e,{recursive:!0}),e}function $e(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function no(r,t){let e=Number(r);return Number.isFinite(e)?Math.max(Lm,Math.min(jm,Math.round(e))):t}function tn(r){return typeof r!="string"||r.length<=to?r:`${r.slice(0,to-1)}\u2026`}function ar(r){if(Array.isArray(r))for(let t=0;t<r.length;t++){let e=r[t];typeof e=="string"?r[t]=tn(e):$e(e)&&typeof e.name=="string"&&(e.name=tn(e.name))}}function Um(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)&&ar(s.data)}let t=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of t)$e(n)&&ar(n.indicator);$e(r.legend)&&ar(r.legend.data);let e=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of e)$e(n)&&(typeof n.name=="string"&&(n.name=tn(n.name)),ar(n.data))}function Bm(r){let t=JSON.parse(JSON.stringify(r));return t.animation=!1,t.backgroundColor==null&&(t.backgroundColor="#fff"),$e(t.textStyle)||(t.textStyle={}),t.textStyle.fontFamily==null&&(t.textStyle.fontFamily=lo),Um(t),t}function Jm(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Dm(r,t,e){let i=Rm().init(null,null,{renderer:"svg",ssr:!0,width:t,height:e});try{return i.setOption(r),i.renderToSVGString()}finally{i.dispose()}}function qm(r){return r.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"")}function Mm(r,t){return r.replace(/id="zr\d+-/g,`id="${t}-`).replace(/url\(#zr\d+-/g,`url(#${t}-`).replace(/class="zr\d+-/g,`class="${t}-`)}function Fm(r){let t=[];for(let e of r.matchAll(/(?:xlink:)?href\s*=\s*"([^"]*)"/gi)){let n=e[1].trim();n&&!n.startsWith("#")&&!/^data:/i.test(n)&&t.push(n)}for(let e of r.matchAll(/url\(\s*['"]?([^'")]*)['"]?\s*\)/gi)){let n=e[1].trim();n&&!n.startsWith("#")&&!/^data:/i.test(n)&&t.push(n)}return/@import/i.test(r)&&t.push("@import"),/<script\b/i.test(r)&&t.push("<script>"),/<foreignObject\b/i.test(r)&&t.push("<foreignObject>"),t}function Km(r){let t=Mm(qm(r),`chart-${Om(4).toString("hex")}`),e=Fm(t);if(e.length){let n=[...new Set(e)].slice(0,3).join(", ");throw new Error(`the rendered chart references external resources (${n}), which a self-contained HTML page blocks. Remove image:// symbols / external image fills from the spec (use plain colors or a data: URI), or use output:'svg' to write a file instead.`)}return t}function Gm(r){let{Resvg:t}=Am();return new t(r,{font:{fontFiles:Pm(),loadSystemFonts:!0,defaultFontFamily:lo}}).render().asPng()}var po={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)
857
911
  You can render charts LOCALLY with the chart_render tool \u2014 pass a standard
858
912
  Apache ECharts option object as \`spec\` (any chart type: bar, line, pie,
859
- radar, scatter, heatmap, \u2026). It renders server-side to SVG/PNG files in the
860
- run's output folder (auto-attached to the run as artifacts) and returns the
861
- file paths. No browser, no external chart service \u2014 the data never leaves
862
- the machine. Don't set animation (it's forced off). Default 800\xD7600 PNG.`,resolve({sessionPath:r,nodeName:t}={}){let e=_u();if(!e)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&t?Ge(r,t):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:[e,"../dist/chartRender.js","chartRenderSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){if(r!=="chart_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let e=t?.spec;if(!Ae(e))return JSON.stringify({error:"spec must be a plain ECharts option OBJECT (e.g. { xAxis: {...}, yAxis: {...}, series: [...] }) \u2014 got "+(e===null?"null":Array.isArray(e)?"an array":typeof e)+". Pass the option object itself, not a string or an array."});let n=As(t?.width,fu),i=As(t?.height,hu),s=["svg","png","both"].includes(t?.output)?t.output:"png",o=vu(t?.filename)||`chart-${Date.now()}`,a;try{a=Iu(Su(e),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=ku(),d=[];if(s==="svg"||s==="both"){let l=Ge(c,`${o}.svg`);Os(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=Nu(a)}catch(u){return JSON.stringify({error:`PNG rasterization failed: ${u.message}. Retry with output:'svg' if you only need the vector.`})}let p=Ge(c,`${o}.png`);Os(p,l),d.push({path:p,format:"png",bytes:l.length})}return JSON.stringify({ok:!0,width:n,height:i,files:d})}catch(e){return JSON.stringify({error:`chart_render failed: ${e.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{existsSync as Ou}from"fs";import{fileURLToPath as Tu}from"url";import{dirname as Au,resolve as Ru}from"path";function Eu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Au(Tu(import.meta.url)),t=Ru(r,"..","bin","mcp-skill.mjs");return Ou(t)?t:null}var ju=[{name:"trivial",max:5},{name:"small",max:30},{name:"medium",max:150},{name:"large",max:600},{name:"huge",max:1/0}];function xu(r,t){let e=(Number(r)||0)+(Number(t)||0);for(let n of ju)if(e<=n.max)return n.name;return"huge"}function Lu(r){let e=String(r||"").toLowerCase().split("/").pop()||"",n=e.match(/\.(test|spec)\.[a-z0-9]+$/);if(n)return`.${n[1]}`;let i=e.lastIndexOf(".");return i<=0?/^(dockerfile|makefile|jenkinsfile|procfile|gemfile|rakefile)$/i.test(e)?e.toLowerCase():"":e.slice(i)}var $u={code:[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".rb",".php",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".scala",".m",".dart",".ex",".exs",".clj",".sh",".bash"],test:[".test",".spec"],docs:[".md",".mdx",".rst",".txt",".adoc"],config:[".json",".yml",".yaml",".toml",".ini",".env",".cfg",".conf",".lock",".xml",".properties","dockerfile","makefile","jenkinsfile","procfile",".tf",".gradle"],style:[".css",".scss",".sass",".less",".styl"],data:[".csv",".tsv",".sql",".parquet",".proto",".graphql",".gql"]},Pu=(()=>{let r={};for(let[t,e]of Object.entries($u))for(let n of e)r[n]=t;return r})();function Cu(r){return Pu[String(r||"").toLowerCase()]||"other"}function Uu(r,t={}){let e=Array.isArray(r)?r:[],n=[],i={},s={code:0,test:0,docs:0,config:0,style:0,data:0,other:0},o=0,a=0,c={path:"",changed:-1};for(let m of e){if(!m||typeof m!="object")continue;let f=String(m.path||m.newPath||m.filename||m.new_path||"").trim();if(!f)continue;n.push(f);let h=Number(m.additions??m.add??0)||0,b=Number(m.deletions??m.del??0)||0;o+=h,a+=b;let g=Lu(f);i[g||"(none)"]=(i[g||"(none)"]||0)+1,s[Cu(g)]+=1;let _=h+b;_>c.changed&&(c={path:f,changed:_})}let d=Number(t.additions),l=Number(t.deletions),p=Number.isFinite(d)?d:o,u=Number.isFinite(l)?l:a;return{filesChanged:n.length,filePaths:n,extCounts:i,kindCounts:s,additions:p,deletions:u,sizeBucket:xu(p,u),largestFile:c.path||null,dirs:[...new Set(n.map(m=>m.includes("/")?m.split("/")[0]:"(root)"))].sort()}}function Bu(r){let t="",e=String(r||"");for(let n=0;n<e.length;n++){let i=e[n];i==="*"?e[n+1]==="*"?(t+=".*",n++,e[n+1]==="/"&&n++):t+="[^/]*":i==="?"?t+="[^/]":"\\^$.|+()[]{}".includes(i)?t+=`\\${i}`:t+=i}return new RegExp(`^${t}$`)}function Ju(r,t){let e=Array.isArray(r)?r.map(String):[],n=(Array.isArray(t)?t:[]).filter(Boolean).map(Bu);if(!n.length)return{total:e.length,hits:0,ratio:0,matched:[]};let i=e.filter(s=>n.some(o=>o.test(s)));return{total:e.length,hits:i.length,ratio:e.length?Number((i.length/e.length).toFixed(4)):0,matched:i}}function qu(r,t){let e=(Array.isArray(r)?r:[]).map(Number).filter(s=>Number.isFinite(s)),n=Number(t);if(!e.length||!Number.isFinite(n))return null;let i=e.filter(s=>s<=n).length;return Number((i/e.length*100).toFixed(1))}var Cs={id:"code-stats",serverName:"code_stats",allowedTools:["mcp__code_stats__*"],description:"Deterministic code statistics \u2014 pure, reproducible facts from changed-file lists + numbers (extension/work-kind mix, size bucket, core-path glob coverage, percentile rank). Zero LLM, zero network.",promptFragment:`## Code Stats (DETERMINISTIC facts \u2014 pure, reproducible, zero-LLM)
913
+ radar, scatter, heatmap, \u2026). No browser, no external chart service \u2014 the data
914
+ never leaves the machine. Don't set animation (it's forced off).
915
+
916
+ Pick the destination with \`output\`:
917
+ - **Building an HTML page / artifact / report \u2192 \`output:'svg-inline'\`.** It
918
+ returns the \`svg\` markup in the result; paste that <svg> element straight
919
+ into your HTML. A published page is self-contained and blocks every external
920
+ host, so a file path is useless there \u2014 inline is the ONLY way a chart shows
921
+ up. Never hand-write bar/gauge markup with percentage widths; let ECharts
922
+ compute the geometry from the data so the bars cannot come out wrong.
923
+ - **Attaching a chart to the run \u2192 \`output:'png'\` (default), \`'svg'\` or
924
+ \`'both'\`.** Writes files to the run's output folder (auto-uploaded as run
925
+ artifacts) and returns the paths. Default 800\xD7600.`,resolve({sessionPath:r,nodeName:t}={}){let e=$m();if(!e)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&t?Ze(r,t):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:[e,"../dist/chartRender.js","chartRenderSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){if(r!=="chart_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let e=t?.spec;if(!$e(e))return JSON.stringify({error:"spec must be a plain ECharts option OBJECT (e.g. { xAxis: {...}, yAxis: {...}, series: [...] }) \u2014 got "+(e===null?"null":Array.isArray(e)?"an array":typeof e)+". Pass the option object itself, not a string or an array."});let n=no(t?.width,Em),i=no(t?.height,xm),s=["svg","png","both","svg-inline"].includes(t?.output)?t.output:"png",o=Jm(t?.filename)||`chart-${Date.now()}`,a;try{a=Dm(Bm(e),n,i)}catch(d){return JSON.stringify({error:`Chart render failed: ${d.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."});if(s==="svg-inline"){let d;try{d=Km(a)}catch(u){return JSON.stringify({error:`Chart cannot be inlined: ${u.message}`})}let p=Buffer.byteLength(d,"utf-8");return p>ro?JSON.stringify({error:`Rendered SVG is ${Math.round(p/1024)}KB, over the ${Math.round(ro/1024)}KB inline limit. Inline SVG is returned through the conversation and pasted into the page, so it must stay small. Aggregate or sample the data down (a readable chart rarely needs >1000 points), or use output:'svg' to write a file instead.`}):JSON.stringify({ok:!0,width:n,height:i,svg:d,bytes:p,files:[]})}let c=Cm(),l=[];if(s==="svg"||s==="both"){let d=Ze(c,`${o}.svg`);eo(d,a,"utf-8"),l.push({path:d,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}if(s==="png"||s==="both"){let d;try{d=Gm(a)}catch(u){return JSON.stringify({error:`PNG rasterization failed: ${u.message}. Retry with output:'svg' if you only need the vector.`})}let p=Ze(c,`${o}.png`);eo(p,d),l.push({path:p,format:"png",bytes:d.length})}return JSON.stringify({ok:!0,width:n,height:i,files:l})}catch(e){return JSON.stringify({error:`chart_render failed: ${e.message}`})}},tools:[{name:"chart_render",description:`Render a chart LOCALLY (no external service) from a standard Apache ECharts option. Pass the raw ECharts option as \`spec\` \u2014 every ECharts chart type works (bar, line, pie, radar, scatter, heatmap, \u2026). USE output:'svg-inline' WHEN BUILDING AN HTML PAGE, ARTIFACT OR REPORT: it returns the chart as an \`svg\` string (self-contained, no external refs) to paste directly into your HTML \u2014 a published page blocks external hosts, so a file path will not render there, and hand-written bar markup is never needed because ECharts computes the geometry. Otherwise output 'png' (default) / 'svg' / 'both' writes files to the run output folder and returns their paths. 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","svg-inline"],description:"Destination. 'svg-inline' writes NO file and returns the SVG markup in the result for pasting into an HTML page/artifact \u2014 use this whenever you are building HTML. 'png' (default) / 'svg' / 'both' write files to the run output folder and return their paths."},filename:{type:"string",description:"Optional file basename (no extension); defaults to chart-<timestamp>."}},required:["spec"]}}]};import{existsSync as Hm}from"fs";import{fileURLToPath as zm}from"url";import{dirname as Ym,resolve as Wm}from"path";function Zm(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ym(zm(import.meta.url)),t=Wm(r,"..","bin","mcp-skill.mjs");return Hm(t)?t:null}var Vm=[{name:"trivial",max:5},{name:"small",max:30},{name:"medium",max:150},{name:"large",max:600},{name:"huge",max:1/0}];function Xm(r,t){let e=(Number(r)||0)+(Number(t)||0);for(let n of Vm)if(e<=n.max)return n.name;return"huge"}function Qm(r){let e=String(r||"").toLowerCase().split("/").pop()||"",n=e.match(/\.(test|spec)\.[a-z0-9]+$/);if(n)return`.${n[1]}`;let i=e.lastIndexOf(".");return i<=0?/^(dockerfile|makefile|jenkinsfile|procfile|gemfile|rakefile)$/i.test(e)?e.toLowerCase():"":e.slice(i)}var ef={code:[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".rb",".php",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".scala",".m",".dart",".ex",".exs",".clj",".sh",".bash"],test:[".test",".spec"],docs:[".md",".mdx",".rst",".txt",".adoc"],config:[".json",".yml",".yaml",".toml",".ini",".env",".cfg",".conf",".lock",".xml",".properties","dockerfile","makefile","jenkinsfile","procfile",".tf",".gradle"],style:[".css",".scss",".sass",".less",".styl"],data:[".csv",".tsv",".sql",".parquet",".proto",".graphql",".gql"]},tf=(()=>{let r={};for(let[t,e]of Object.entries(ef))for(let n of e)r[n]=t;return r})();function rf(r){return tf[String(r||"").toLowerCase()]||"other"}function nf(r,t={}){let e=Array.isArray(r)?r:[],n=[],i={},s={code:0,test:0,docs:0,config:0,style:0,data:0,other:0},o=0,a=0,c={path:"",changed:-1};for(let m of e){if(!m||typeof m!="object")continue;let f=String(m.path||m.newPath||m.filename||m.new_path||"").trim();if(!f)continue;n.push(f);let h=Number(m.additions??m.add??0)||0,_=Number(m.deletions??m.del??0)||0;o+=h,a+=_;let y=Qm(f);i[y||"(none)"]=(i[y||"(none)"]||0)+1,s[rf(y)]+=1;let b=h+_;b>c.changed&&(c={path:f,changed:b})}let l=Number(t.additions),d=Number(t.deletions),p=Number.isFinite(l)?l:o,u=Number.isFinite(d)?d:a;return{filesChanged:n.length,filePaths:n,extCounts:i,kindCounts:s,additions:p,deletions:u,sizeBucket:Xm(p,u),largestFile:c.path||null,dirs:[...new Set(n.map(m=>m.includes("/")?m.split("/")[0]:"(root)"))].sort()}}function sf(r){let t="",e=String(r||"");for(let n=0;n<e.length;n++){let i=e[n];i==="*"?e[n+1]==="*"?(t+=".*",n++,e[n+1]==="/"&&n++):t+="[^/]*":i==="?"?t+="[^/]":"\\^$.|+()[]{}".includes(i)?t+=`\\${i}`:t+=i}return new RegExp(`^${t}$`)}function of(r,t){let e=Array.isArray(r)?r.map(String):[],n=(Array.isArray(t)?t:[]).filter(Boolean).map(sf);if(!n.length)return{total:e.length,hits:0,ratio:0,matched:[]};let i=e.filter(s=>n.some(o=>o.test(s)));return{total:e.length,hits:i.length,ratio:e.length?Number((i.length/e.length).toFixed(4)):0,matched:i}}function af(r,t){let e=(Array.isArray(r)?r:[]).map(Number).filter(s=>Number.isFinite(s)),n=Number(t);if(!e.length||!Number.isFinite(n))return null;let i=e.filter(s=>s<=n).length;return Number((i/e.length*100).toFixed(1))}var uo={id:"code-stats",serverName:"code_stats",allowedTools:["mcp__code_stats__*"],description:"Deterministic code statistics \u2014 pure, reproducible facts from changed-file lists + numbers (extension/work-kind mix, size bucket, core-path glob coverage, percentile rank). Zero LLM, zero network.",promptFragment:`## Code Stats (DETERMINISTIC facts \u2014 pure, reproducible, zero-LLM)
863
926
  These tools COMPUTE reproducible facts from data you already have. Use them so
864
927
  your numbers are auditable and survive challenge (same input \u2192 same output).
865
928
 
@@ -877,7 +940,7 @@ Tools:
877
940
  reproducible "works in the core vs the edges" number.
878
941
  - code_stats_percentile: Given \`values\` (a cohort's numbers) + a \`value\`,
879
942
  returns the 0-100 percentile rank. Use to express every metric as a rank
880
- within the team (reproducible + comparable across teams), not a raw number.`,resolve(){let r=Eu();return r?{type:"stdio",command:"node",args:[r,"../dist/codeStats.js","codeStatsSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,t){try{switch(r){case"code_stats_commit_facts":return JSON.stringify(Uu(t?.files,{additions:t?.additions,deletions:t?.deletions}));case"code_stats_glob_hit":return JSON.stringify(Ju(t?.paths,t?.globs));case"code_stats_percentile":return JSON.stringify({percentile:qu(t?.values,t?.value)});default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"code_stats_commit_facts",description:"Deterministic per-commit facts from its changed-file list. Pass files: [{path, additions, deletions}] (gitlab_get_commit / github_get_commit shape). Returns filePaths, extCounts, kindCounts (code/test/docs/config/style/data/other), additions, deletions, sizeBucket (trivial/small/medium/large/huge), largestFile, dirs. Pure \u2014 same input always same output.",input_schema:{type:"object",properties:{files:{type:"array",description:"Changed files. Each { path (or newPath/filename), additions?, deletions? }.",items:{type:"object",properties:{path:{type:"string"},additions:{type:"number"},deletions:{type:"number"}}}},additions:{type:"number",description:"Optional commit-level total additions override (else summed from files)."},deletions:{type:"number",description:"Optional commit-level total deletions override."}},required:["files"]}},{name:"code_stats_glob_hit",description:"How many of paths match ANY of globs (supports **, *, ?). Returns { total, hits, ratio, matched }. Use for reproducible core-path coverage against the caller's own core globs.",input_schema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"File paths to test."},globs:{type:"array",items:{type:"string"},description:'Glob patterns, e.g. ["src/payment/**", "auth/**"].'}},required:["paths","globs"]}},{name:"code_stats_percentile",description:'The 0-100 percentile rank of value within values (cumulative "% at or below"). Reproducible + cross-team comparable. Empty cohort \u2192 null.',input_schema:{type:"object",properties:{values:{type:"array",items:{type:"number"},description:"The cohort's numbers."},value:{type:"number",description:"The value to rank."}},required:["values","value"]}}]};import{existsSync as Du}from"fs";import{fileURLToPath as Mu}from"url";import{dirname as Ku,resolve as Gu}from"path";function Fu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ku(Mu(import.meta.url)),t=Gu(r,"..","bin","mcp-skill.mjs");return Du(t)?t:null}function Hu(r={}){let t=String(r.provider||process.env.ZIBBY_PROGRESS_PROVIDER||(process.env.LARK_RECEIVE_ID?"lark":process.env.SLACK_CHANNEL||process.env.SLACK_BOT_TOKEN?"slack":"")).toLowerCase(),e=String(r.chatId||r.channel||process.env.ZIBBY_PROGRESS_CHAT_ID||(t==="lark"?process.env.LARK_RECEIVE_ID:process.env.SLACK_CHANNEL)||"").trim(),n=String(r.mention||process.env.ZIBBY_PROGRESS_MENTION||"").trim();return{provider:t,chatId:e,mention:n}}var Us={id:"chat-progress",serverName:"chat_progress",allowedTools:["mcp__chat_progress__*"],envKeys:[...P.envKeys||[],...M.envKeys||[],"ZIBBY_PROGRESS_PROVIDER","ZIBBY_PROGRESS_CHAT_ID","ZIBBY_PROGRESS_MENTION","SLACK_CHANNEL","LARK_RECEIVE_ID"],description:"Report progress back to the triggering chat during a long-running job \u2014 a one-line status the human sees while the work runs. General + reusable; fire-and-forget.",promptFragment:`## Chat Progress (tell the human you're still working \u2014 long jobs only)
943
+ within the team (reproducible + comparable across teams), not a raw number.`,resolve(){let r=Zm();return r?{type:"stdio",command:"node",args:[r,"../dist/codeStats.js","codeStatsSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,t){try{switch(r){case"code_stats_commit_facts":return JSON.stringify(nf(t?.files,{additions:t?.additions,deletions:t?.deletions}));case"code_stats_glob_hit":return JSON.stringify(of(t?.paths,t?.globs));case"code_stats_percentile":return JSON.stringify({percentile:af(t?.values,t?.value)});default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"code_stats_commit_facts",description:"Deterministic per-commit facts from its changed-file list. Pass files: [{path, additions, deletions}] (gitlab_get_commit / github_get_commit shape). Returns filePaths, extCounts, kindCounts (code/test/docs/config/style/data/other), additions, deletions, sizeBucket (trivial/small/medium/large/huge), largestFile, dirs. Pure \u2014 same input always same output.",input_schema:{type:"object",properties:{files:{type:"array",description:"Changed files. Each { path (or newPath/filename), additions?, deletions? }.",items:{type:"object",properties:{path:{type:"string"},additions:{type:"number"},deletions:{type:"number"}}}},additions:{type:"number",description:"Optional commit-level total additions override (else summed from files)."},deletions:{type:"number",description:"Optional commit-level total deletions override."}},required:["files"]}},{name:"code_stats_glob_hit",description:"How many of paths match ANY of globs (supports **, *, ?). Returns { total, hits, ratio, matched }. Use for reproducible core-path coverage against the caller's own core globs.",input_schema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"File paths to test."},globs:{type:"array",items:{type:"string"},description:'Glob patterns, e.g. ["src/payment/**", "auth/**"].'}},required:["paths","globs"]}},{name:"code_stats_percentile",description:'The 0-100 percentile rank of value within values (cumulative "% at or below"). Reproducible + cross-team comparable. Empty cohort \u2192 null.',input_schema:{type:"object",properties:{values:{type:"array",items:{type:"number"},description:"The cohort's numbers."},value:{type:"number",description:"The value to rank."}},required:["values","value"]}}]};import{existsSync as cf}from"fs";import{fileURLToPath as lf}from"url";import{dirname as df,resolve as pf}from"path";function uf(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=df(lf(import.meta.url)),t=pf(r,"..","bin","mcp-skill.mjs");return cf(t)?t:null}function mf(r={}){let t=String(r.provider||process.env.ZIBBY_PROGRESS_PROVIDER||(process.env.LARK_RECEIVE_ID?"lark":process.env.SLACK_CHANNEL||process.env.SLACK_BOT_TOKEN?"slack":"")).toLowerCase(),e=String(r.chatId||r.channel||process.env.ZIBBY_PROGRESS_CHAT_ID||(t==="lark"?process.env.LARK_RECEIVE_ID:process.env.SLACK_CHANNEL)||"").trim(),n=String(r.mention||process.env.ZIBBY_PROGRESS_MENTION||"").trim();return{provider:t,chatId:e,mention:n}}var mo={id:"chat-progress",serverName:"chat_progress",allowedTools:["mcp__chat_progress__*"],envKeys:[...P.envKeys||[],...F.envKeys||[],"ZIBBY_PROGRESS_PROVIDER","ZIBBY_PROGRESS_CHAT_ID","ZIBBY_PROGRESS_MENTION","SLACK_CHANNEL","LARK_RECEIVE_ID"],description:"Report progress back to the triggering chat during a long-running job \u2014 a one-line status the human sees while the work runs. General + reusable; fire-and-forget.",promptFragment:`## Chat Progress (tell the human you're still working \u2014 long jobs only)
881
944
  When a run is LONG (many API pages, a shard-capped backfill, dozens of scored
882
945
  items), the human who triggered it can't see the middle \u2014 only the final
883
946
  notify. Post brief milestones so they know it's alive:
@@ -887,11 +950,11 @@ notify. Post brief milestones so they know it's alive:
887
950
  commits, continuing\u2026"). Pass the chat target from your \`notify\` input when
888
951
  you have it (provider + chatId); otherwise it resolves from the runtime.
889
952
  Fire-and-forget \u2014 if it can't post, just keep working; never treat a failed
890
- progress ping as an error.`,resolve(){let r=Fu();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","SLACK_BOT_TOKEN","SLACK_TEAM_ID","ZIBBY_PROGRESS_PROVIDER","ZIBBY_PROGRESS_CHAT_ID","ZIBBY_PROGRESS_MENTION","SLACK_CHANNEL","LARK_RECEIVE_ID"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/chatProgress.js","chatProgressSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){if(r!=="report_progress")return JSON.stringify({error:`Unknown tool: ${r}`});try{let e=String(t?.message||"").trim().slice(0,2e3);if(!e)return JSON.stringify({ok:!1,skipped:"empty message"});let{provider:n,chatId:i,mention:s}=Hu(t);if(!n||!i)return JSON.stringify({ok:!1,skipped:"no chat target"});let o=s&&n==="slack"?`<@${s}> ${e}`:e,a;n==="lark"?a=await M.handleToolCall("lark_send_message",{receive_id:i,text:e}):a=await P.handleToolCall("slack_post_message",{channel:i,text:o});let c=null;try{c=JSON.parse(a)}catch{}return c&&c.error?JSON.stringify({ok:!1,skipped:`post failed: ${c.error}`}):JSON.stringify({ok:!0,provider:n,posted:!0})}catch(e){return JSON.stringify({ok:!1,skipped:`error: ${e.message}`})}},tools:[{name:"report_progress",description:"Post a ONE-LINE progress status to the chat that triggered this run (so the human sees the long job is alive). Fire-and-forget \u2014 never fails the run. Target resolves from your notify input (provider + chatId) or the runtime; you usually just pass the message.",input_schema:{type:"object",properties:{message:{type:"string",description:'A short human status line, e.g. "Scored 60/188 commits, continuing\u2026".'},provider:{type:"string",enum:["lark","slack"],description:"Optional \u2014 the chat provider (from your notify input). Defaults from the runtime."},chatId:{type:"string",description:"Optional \u2014 the target chat/channel id (from your notify input). Defaults from the runtime."}},required:["message"]}}]};import{createRequire as zu}from"node:module";import{existsSync as Ds,mkdirSync as Yu,writeFileSync as Bs}from"node:fs";import{dirname as Ms,join as He,resolve as Ks}from"node:path";import{fileURLToPath as Gs}from"node:url";var Wu=zu(import.meta.url),Mr=null;function Zu(){return Mr||(Mr=Wu("@resvg/resvg-js")),Mr}var Fs=1200,Vu=627,Xu=4096,Qu=320,em="#3b82f6",Re="Noto Sans",tm=3;function rm(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ms(Gs(import.meta.url)),t=Ks(r,"..","bin","mcp-skill.mjs");return Ds(t)?t:null}function nm(){let r=Ms(Gs(import.meta.url)),t=Ks(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(e=>He(t,e)).filter(e=>Ds(e))}function im(){let r=process.env.ZIBBY_NODE_SESSION_PATH,t=process.env.ZIBBY_SESSION_PATH,e=r||(t?He(t,"social-card"):He(process.cwd(),".zibby","output","social-cards"));return Yu(e,{recursive:!0}),e}function Js(r,t){let e=Number(r);return Number.isFinite(e)?Math.max(Qu,Math.min(Xu,Math.round(e))):t}function Fe(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function sm(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function om(r,t){if(typeof r!="string")return t;let e=r.trim();return/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(e)?e:t}function Hs(r,t,e){return String(r).length*t*e}function Kr(r,t,e,n){let i=String(r).trim().split(/\s+/).filter(Boolean),s=[],o="";for(let a of i){let c=o?`${o} ${a}`:a;o&&Hs(c,e,n)>t?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function am(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 qs(r,t,e,n,i){let s=(Array.isArray(r)?r:[]).map(b=>String(b??"").trim()).filter(Boolean).slice(0,tm);if(s.length<2)return null;let o=24,a=54,c=26,d=90,l=17,p=s.map(b=>Math.max(96,Hs(b,o,.58)+c*2)),u=p.reduce((b,g)=>b+g,0)+d*(s.length-1),m=t-u/2,f=e+a/2,h=[];for(let b=0;b<s.length;b++){let g=p[b];if(h.push(`<rect x="${m.toFixed(1)}" y="${e}" width="${g.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+g/2).toFixed(1)}" y="${(f+o*.35).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${o}" font-weight="700" fill="${n.pillText}">${Fe(s[b])}</text>`),m+=g,b<s.length-1){let _=m,y=m+d,k=(_+y)/2;h.push(`<line x1="${_.toFixed(1)}" y1="${f}" x2="${y.toFixed(1)}" y2="${f}" stroke="${i}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${k.toFixed(1)}" cy="${f}" r="${l}" fill="${i}"/>`,`<path d="M ${(k-8).toFixed(1)} ${f.toFixed(1)} l 5 5 l 9 -11" fill="none" stroke="${n.checkFg}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`),m=y}}return{svg:h.join(`
891
- `),height:a}}function cm(r){let{width:t,height:e,theme:n,accent:i}=r,s=am(n),o=t/2,a=Math.round(t*.07),c=t-a*2,d=String(r.headline).trim(),l=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",p=r.subhead?String(r.subhead).trim():"",u=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=t/Fs,h=Math.round(22*f),b=Math.round(29*f),g=p?Kr(p,c,b,.52):[],_=Math.round(b*1.28),y=4,k=Math.round(26*f),O=Math.round(20*f),Y=Math.round(24*f),je=Math.round(30*f),R=!!(u||m),A=a,D=R?Math.round(110*f):a,j=e-A-D,be=qs(r.diagram,o,0,s,i),on=(C,ue)=>{let Ye=y+k;return l&&(Ye+=h+O),Ye+=ue.length*Math.round(C*1.16),g.length&&(Ye+=Y+g.length*_),be&&(Ye+=je+be.height),Ye},sr=[76,66,58,50,44,38].map(C=>Math.round(C*f)),Eo=4,xe=sr[sr.length-1],or=Kr(d,c,xe,.6);for(let C of sr){let ue=Kr(d,c,C,.6);if(ue.length<=Eo&&on(C,ue)<=j){xe=C,or=ue;break}}let jo=Math.round(xe*1.16),xo=on(xe,or),W=A+Math.max(0,(j-xo)/2),oe=[];oe.push(`<rect x="0" y="0" width="${t}" height="${e}" fill="${s.bg}"/>`);let an=Math.round(60*f);oe.push(`<rect x="${(o-an/2).toFixed(1)}" y="${W}" width="${an}" height="${y}" rx="2" fill="${i}"/>`),W+=y+k,l&&(oe.push(`<text x="${o}" y="${(W+h*.82).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${i}">${Fe(l)}</text>`),W+=h+O);for(let C of or)oe.push(`<text x="${o}" y="${(W+xe*.82).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${xe}" font-weight="700" fill="${s.fg}">${Fe(C)}</text>`),W+=jo;if(g.length){W+=Y;for(let C of g)oe.push(`<text x="${o}" y="${(W+b*.82).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${b}" font-weight="400" fill="${s.muted}">${Fe(C)}</text>`),W+=_}if(be){W+=je;let C=qs(r.diagram,o,W,s,i);C&&oe.push(C.svg)}if(R){let C=Math.round(24*f),ue=e-Math.round(46*f);m&&oe.push(`<text x="${a}" y="${ue}" text-anchor="start" font-family="${Re}" font-size="${C}" font-weight="400" fill="${s.muted}">${Fe(m)}</text>`),u&&oe.push(`<text x="${t-a}" y="${ue}" text-anchor="end" font-family="${Re}" font-size="${C}" font-weight="700" fill="${i}">${Fe(u)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${e}" viewBox="0 0 ${t} ${e}">
892
- ${oe.join(`
953
+ progress ping as an error.`,resolve(){let r=uf();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","SLACK_BOT_TOKEN","SLACK_TEAM_ID","ZIBBY_PROGRESS_PROVIDER","ZIBBY_PROGRESS_CHAT_ID","ZIBBY_PROGRESS_MENTION","SLACK_CHANNEL","LARK_RECEIVE_ID"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/chatProgress.js","chatProgressSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){if(r!=="report_progress")return JSON.stringify({error:`Unknown tool: ${r}`});try{let e=String(t?.message||"").trim().slice(0,2e3);if(!e)return JSON.stringify({ok:!1,skipped:"empty message"});let{provider:n,chatId:i,mention:s}=mf(t);if(!n||!i)return JSON.stringify({ok:!1,skipped:"no chat target"});let o=s&&n==="slack"?`<@${s}> ${e}`:e,a;n==="lark"?a=await F.handleToolCall("lark_send_message",{receive_id:i,text:e}):a=await P.handleToolCall("slack_post_message",{channel:i,text:o});let c=null;try{c=JSON.parse(a)}catch{}return c&&c.error?JSON.stringify({ok:!1,skipped:`post failed: ${c.error}`}):JSON.stringify({ok:!0,provider:n,posted:!0})}catch(e){return JSON.stringify({ok:!1,skipped:`error: ${e.message}`})}},tools:[{name:"report_progress",description:"Post a ONE-LINE progress status to the chat that triggered this run (so the human sees the long job is alive). Fire-and-forget \u2014 never fails the run. Target resolves from your notify input (provider + chatId) or the runtime; you usually just pass the message.",input_schema:{type:"object",properties:{message:{type:"string",description:'A short human status line, e.g. "Scored 60/188 commits, continuing\u2026".'},provider:{type:"string",enum:["lark","slack"],description:"Optional \u2014 the chat provider (from your notify input). Defaults from the runtime."},chatId:{type:"string",description:"Optional \u2014 the target chat/channel id (from your notify input). Defaults from the runtime."}},required:["message"]}}]};import{createRequire as ff}from"node:module";import{existsSync as go,mkdirSync as hf,writeFileSync as fo}from"node:fs";import{dirname as bo,join as Xe,resolve as _o}from"node:path";import{fileURLToPath as ko}from"node:url";var yf=ff(import.meta.url),rn=null;function gf(){return rn||(rn=yf("@resvg/resvg-js")),rn}var wo=1200,bf=627,_f=4096,kf=320,wf="#3b82f6",Pe="Noto Sans",Sf=3;function vf(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=bo(ko(import.meta.url)),t=_o(r,"..","bin","mcp-skill.mjs");return go(t)?t:null}function If(){let r=bo(ko(import.meta.url)),t=_o(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(e=>Xe(t,e)).filter(e=>go(e))}function Nf(){let r=process.env.ZIBBY_NODE_SESSION_PATH,t=process.env.ZIBBY_SESSION_PATH,e=r||(t?Xe(t,"social-card"):Xe(process.cwd(),".zibby","output","social-cards"));return hf(e,{recursive:!0}),e}function ho(r,t){let e=Number(r);return Number.isFinite(e)?Math.max(kf,Math.min(_f,Math.round(e))):t}function Ve(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Of(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Tf(r,t){if(typeof r!="string")return t;let e=r.trim();return/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(e)?e:t}function So(r,t,e){return String(r).length*t*e}function nn(r,t,e,n){let i=String(r).trim().split(/\s+/).filter(Boolean),s=[],o="";for(let a of i){let c=o?`${o} ${a}`:a;o&&So(c,e,n)>t?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function Rf(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 yo(r,t,e,n,i){let s=(Array.isArray(r)?r:[]).map(_=>String(_??"").trim()).filter(Boolean).slice(0,Sf);if(s.length<2)return null;let o=24,a=54,c=26,l=90,d=17,p=s.map(_=>Math.max(96,So(_,o,.58)+c*2)),u=p.reduce((_,y)=>_+y,0)+l*(s.length-1),m=t-u/2,f=e+a/2,h=[];for(let _=0;_<s.length;_++){let y=p[_];if(h.push(`<rect x="${m.toFixed(1)}" y="${e}" width="${y.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+y/2).toFixed(1)}" y="${(f+o*.35).toFixed(1)}" text-anchor="middle" font-family="${Pe}" font-size="${o}" font-weight="700" fill="${n.pillText}">${Ve(s[_])}</text>`),m+=y,_<s.length-1){let b=m,g=m+l,k=(b+g)/2;h.push(`<line x1="${b.toFixed(1)}" y1="${f}" x2="${g.toFixed(1)}" y2="${f}" stroke="${i}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${k.toFixed(1)}" cy="${f}" r="${d}" fill="${i}"/>`,`<path d="M ${(k-8).toFixed(1)} ${f.toFixed(1)} l 5 5 l 9 -11" fill="none" stroke="${n.checkFg}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`),m=g}}return{svg:h.join(`
954
+ `),height:a}}function Af(r){let{width:t,height:e,theme:n,accent:i}=r,s=Rf(n),o=t/2,a=Math.round(t*.07),c=t-a*2,l=String(r.headline).trim(),d=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",p=r.subhead?String(r.subhead).trim():"",u=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=t/wo,h=Math.round(22*f),_=Math.round(29*f),y=p?nn(p,c,_,.52):[],b=Math.round(_*1.28),g=4,k=Math.round(26*f),O=Math.round(20*f),q=Math.round(24*f),ye=Math.round(30*f),T=!!(u||m),A=a,M=T?Math.round(110*f):a,x=e-A-M,Ie=yo(r.diagram,o,0,s,i),kn=(C,ge)=>{let et=g+k;return d&&(et+=h+O),et+=ge.length*Math.round(C*1.16),y.length&&(et+=q+y.length*b),Ie&&(et+=ye+Ie.height),et},yr=[76,66,58,50,44,38].map(C=>Math.round(C*f)),sa=4,Ue=yr[yr.length-1],gr=nn(l,c,Ue,.6);for(let C of yr){let ge=nn(l,c,C,.6);if(ge.length<=sa&&kn(C,ge)<=x){Ue=C,gr=ge;break}}let oa=Math.round(Ue*1.16),aa=kn(Ue,gr),W=A+Math.max(0,(x-aa)/2),le=[];le.push(`<rect x="0" y="0" width="${t}" height="${e}" fill="${s.bg}"/>`);let wn=Math.round(60*f);le.push(`<rect x="${(o-wn/2).toFixed(1)}" y="${W}" width="${wn}" height="${g}" rx="2" fill="${i}"/>`),W+=g+k,d&&(le.push(`<text x="${o}" y="${(W+h*.82).toFixed(1)}" text-anchor="middle" font-family="${Pe}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${i}">${Ve(d)}</text>`),W+=h+O);for(let C of gr)le.push(`<text x="${o}" y="${(W+Ue*.82).toFixed(1)}" text-anchor="middle" font-family="${Pe}" font-size="${Ue}" font-weight="700" fill="${s.fg}">${Ve(C)}</text>`),W+=oa;if(y.length){W+=q;for(let C of y)le.push(`<text x="${o}" y="${(W+_*.82).toFixed(1)}" text-anchor="middle" font-family="${Pe}" font-size="${_}" font-weight="400" fill="${s.muted}">${Ve(C)}</text>`),W+=b}if(Ie){W+=ye;let C=yo(r.diagram,o,W,s,i);C&&le.push(C.svg)}if(T){let C=Math.round(24*f),ge=e-Math.round(46*f);m&&le.push(`<text x="${a}" y="${ge}" text-anchor="start" font-family="${Pe}" font-size="${C}" font-weight="400" fill="${s.muted}">${Ve(m)}</text>`),u&&le.push(`<text x="${t-a}" y="${ge}" text-anchor="end" font-family="${Pe}" font-size="${C}" font-weight="700" fill="${i}">${Ve(u)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${e}" viewBox="0 0 ${t} ${e}">
955
+ ${le.join(`
893
956
  `)}
894
- </svg>`}function lm(r){let{Resvg:t}=Zu();return new t(r,{font:{fontFiles:nm(),loadSystemFonts:!0,defaultFontFamily:Re}}).render().asPng()}var zs={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)
957
+ </svg>`}function Ef(r){let{Resvg:t}=gf();return new t(r,{font:{fontFiles:If(),loadSystemFonts:!0,defaultFontFamily:Pe}}).render().asPng()}var vo={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)
895
958
  You can render a BRANDED concept card PNG with the social_card_render tool \u2014 the
896
959
  clean, high-signal LinkedIn "concept card" style (bold headline + small uppercase
897
960
  eyebrow + optional stat/footer + optional A\u2014\u2713\u2014B diagram). Give it STRUCTURED
@@ -905,15 +968,15 @@ fields that capture the ONE key idea of your post:
905
968
  It renders server-side to a PNG in the run's output folder and returns
906
969
  { ok:true, files:[{ path, format:'png', bytes }] }. Pass the returned \`path\` as
907
970
  \`imagePath\` when you draft/publish a LinkedIn post to ATTACH the card as the
908
- post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:t}={}){let e=rm();if(!e)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&t?He(r,t):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:[e,"../dist/socialCard.js","socialCardSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){if(r!=="social_card_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let e=t?.headline;if(typeof e!="string"||!e.trim())return JSON.stringify({error:"headline (the big bold line) is required and must be a non-empty string."});let n=Js(t?.width,Fs),i=Js(t?.height,Vu),s=t?.theme==="light"?"light":"dark",o=om(t?.accent,em),a;try{a=cm({width:n,height:i,theme:s,accent:o,headline:e,eyebrow:t?.eyebrow,subhead:t?.subhead,stat:t?.stat,footer:t?.footer,diagram:t?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=lm(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=im(),l=sm(t?.filename)||`social-card-${Date.now()}`,p=He(d,`${l}.png`);Bs(p,c);let u=[{path:p,format:"png",bytes:c.length}];if(t?.output==="both"||t?.output==="svg"){let m=He(d,`${l}.svg`);Bs(m,a,"utf-8"),u.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:i,theme:s,files:u})}catch(e){return JSON.stringify({error:`social_card_render failed: ${e.message}`})}},tools:[{name:"social_card_render",description:'Render a BRANDED "concept card" PNG LOCALLY (no external service) from structured fields \u2014 the clean LinkedIn concept-card style: bold headline + small uppercase eyebrow + optional supporting subhead, stat, footer, and an A\u2014\u2713\u2014B diagram. Returns { ok:true, files:[{ path, format:"png", bytes }] }. Pass the returned `path` as `imagePath` to a LinkedIn post tool to attach it as the post image. Example: { "headline":"No more copy-paste between AI tools", "eyebrow":"MY WORKFLOW", "stat":"11.8k stars", "footer":"Apache 2.0", "diagram":["Claude Code","Codex"] }.',input_schema:{type:"object",properties:{headline:{type:"string",description:"REQUIRED. The big, bold line \u2014 the single key idea/takeaway. Word-wrapped + auto-sized."},eyebrow:{type:"string",description:'Small uppercase kicker above the headline (e.g. "MY WORKFLOW", "OPEN SOURCE"). Rendered uppercased in the accent color.'},subhead:{type:"string",description:"One supporting line under the headline (muted)."},stat:{type:"string",description:'Optional stat, shown bottom-right in the accent color (e.g. "11.8k stars", "3x faster").'},footer:{type:"string",description:'Optional footer, shown bottom-left (muted) (e.g. "Apache 2.0", a repo name).'},diagram:{type:"array",items:{type:"string"},description:'Optional 2-3 short labels rendered as a chain of pills joined by a checkmark (A \u2014\u2713\u2014 B), e.g. ["Claude Code","Codex"].'},theme:{type:"string",enum:["dark","light"],description:"Card theme (default 'dark' \u2014 near-black bg, off-white text)."},accent:{type:"string",description:'Accent hex color (e.g. "#f97316"). Defaults to a tasteful blue (#3b82f6).'},width:{type:"number",description:"Image width in px (default 1200 \u2014 LinkedIn 1.91:1 link image)."},height:{type:"number",description:"Image height in px (default 627)."},filename:{type:"string",description:"Optional file basename (no extension); defaults to social-card-<timestamp>."},output:{type:"string",enum:["png","both"],description:"Which file(s) to write (default 'png'; 'both' also writes the .svg)."}},required:["headline"]}}]};import{spawnSync as dm}from"node:child_process";import{existsSync as q,readdirSync as Zs,statSync as Vs,writeFileSync as Fr,mkdirSync as Hr}from"node:fs";import{dirname as Gr,extname as er,join as U,relative as pm,resolve as Qt}from"node:path";import{tmpdir as zr}from"node:os";import{fileURLToPath as um}from"node:url";import{SKILL_META as mm}from"@zibby/skill-ids";import{binPath as fm}from"@zibby/bin-oxlint";import{binPath as hm}from"@zibby/bin-semgrep";function ym(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=fm();if(r&&q(r))return r}catch{}return"oxlint"}function gm(){if(process.env.SEMGREP_CORE_BIN)return process.env.SEMGREP_CORE_BIN;try{let r=hm();if(r&&q(r))return r}catch{}return"semgrep-core"}function _m(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Gr(um(import.meta.url)),t=Qt(r,"..","bin","mcp-skill.mjs");return q(t)?t:null}var Xs=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),bm=400,km={plugins:["react","typescript","unicorn","oxc"],categories:{correctness:"error",suspicious:"warn"},rules:{"react/react-in-jsx-scope":"off","react/jsx-max-depth":"off","react/no-array-index-key":"off","react/jsx-key":"error","react/no-unknown-property":"error","no-unused-vars":"warn",eqeqeq:"warn"}},wm=[".oxlintrc.json",".oxlintrc","oxlint.json"],Vt=null;function Sm(){if(Vt&&q(Vt))return Vt;try{let r=U(zr(),"zibby-code-scan");Hr(r,{recursive:!0});let t=U(r,"oxlintrc.curated.json");return Fr(t,JSON.stringify(km),"utf-8"),Vt=t,t}catch{return null}}var Qs={".java":"java",".py":"python",".go":"go",".rb":"ruby",".php":"php"},Ys=Object.keys(Qs),eo={rules:[{id:"zibby-java-command-injection",languages:["java"],severity:"ERROR",message:"Command execution (Runtime.exec / ProcessBuilder) \u2014 command injection risk if the argument is attacker-influenced. Validate/allow-list the input or avoid a shell.",patterns:[{"pattern-either":[{pattern:"Runtime.getRuntime().exec(...)"},{pattern:"new ProcessBuilder(...)"}]}]},{id:"zibby-python-subprocess-shell",languages:["python"],severity:"ERROR",message:"subprocess call with shell=True \u2014 command injection risk. Pass an argv list and shell=False.",pattern:"subprocess.$F(..., shell=True, ...)"},{id:"zibby-python-yaml-load",languages:["python"],severity:"WARNING",message:"yaml.load without a safe loader can instantiate arbitrary Python objects. Use yaml.safe_load.",pattern:"yaml.load(...)"},{id:"zibby-go-command-injection",languages:["go"],severity:"WARNING",message:"os/exec with a non-constant command \u2014 verify the value is not attacker-controlled (command injection).",pattern:"exec.Command($CMD, ...)"},{id:"zibby-ruby-command-injection",languages:["ruby"],severity:"ERROR",message:"Shell/eval execution (system / eval) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...)"},{pattern:"eval(...)"}]}]},{id:"zibby-php-command-injection",languages:["php"],severity:"ERROR",message:"Shell/eval execution (system / exec / shell_exec) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...);"},{pattern:"exec(...);"},{pattern:"shell_exec(...);"}]}]}]},vm=[".semgrep.yml",".semgrep.yaml","semgrep.yml","semgrep.yaml"],Xt=null;function Im(){if(Xt&&q(Xt))return Xt;try{let r=U(zr(),"zibby-code-scan");Hr(r,{recursive:!0});let t=U(r,"semgrep.curated.rules.json");return Fr(t,JSON.stringify(eo),"utf-8"),Xt=t,t}catch{return null}}function Nm(r){return vm.map(e=>U(r,e)).find(e=>q(e))||Im()}function Om(r){let t=[];for(let e of Array.isArray(r)?r:[]){if(typeof e!="string"||!e)continue;let n=Qs[er(e).toLowerCase()];if(!n)continue;let i=e.replace(/\\/g,"/");t.push(["CodeTarget",{path:{fpath:i,ppath:`/${i.replace(/^\/+/,"")}`},analyzer:n,products:["sast"]}])}return["Targets",t]}var Tm=0;function Am(r){let t=Om(r),e=t[1].length,n=U(zr(),"zibby-code-scan");Hr(n,{recursive:!0});let i=U(n,`semgrep.targets.${process.pid}.${Tm++}.json`);return Fr(i,JSON.stringify(t),"utf-8"),{path:i,count:e}}function Ws(r){let t=typeof r=="string"?r.toUpperCase():"";return t==="ERROR"?"error":t==="INFO"||t==="INVENTORY"||t==="EXPERIMENT"?"info":"warning"}var Rm=Object.fromEntries(eo.rules.map(r=>[r.id,r.severity]));function Em(r,t){if(t)return Ws(t);let e=Rm[r];return e?Ws(e):"warning"}function jm(r){let t=String(r||""),e=t.indexOf("{");if(e<0)return[];let n;try{n=JSON.parse(t.slice(e))}catch{return[]}return(n&&Array.isArray(n.results)?n.results:[]).map(s=>{if(!s||typeof s!="object")return null;let o=s.start&&typeof s.start=="object"?s.start:{},a=s.extra&&typeof s.extra=="object"?s.extra:{};return{file:s.path||"",line:Number.isFinite(o.line)?o.line:"",severity:Em(s.check_id,a.severity),rule:s.check_id||"",message:(a.message||"").trim()}}).filter(s=>s&&(s.file||s.message))}function xm(r,t,e=4e3){let n=new Set(t.map(o=>o.toLowerCase())),i=[r],s=0;for(;i.length;){let o=i.pop(),a;try{a=Zs(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(++s>e)return!1;if(c.isDirectory())!Xs.has(c.name)&&!c.name.startsWith(".")&&i.push(U(o,c.name));else if(c.isFile()&&n.has(er(c.name).toLowerCase()))return!0}}return!1}function Lm(r){let t=String(r||"").trim();if(!t)return[];let e;try{e=JSON.parse(t)}catch{return[]}return(Array.isArray(e)?e:e&&Array.isArray(e.diagnostics)?e.diagnostics:[]).map(i=>{if(!i||typeof i!="object")return null;let s=Array.isArray(i.labels)&&i.labels.length?i.labels[0]:null,o=s&&s.span?s.span:null;return{file:i.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:i.severity||"warning",rule:i.code||"",message:i.message||""}}).filter(i=>i&&(i.file||i.message))}function $m(r){let t=String(r||"").trim();if(!t)return[];let e;try{e=JSON.parse(t)}catch{return[]}return Array.isArray(e)?e.map(n=>n&&typeof n=="object"?{file:n.filename||"",line:n.location&&Number.isFinite(n.location.row)?n.location.row:"",severity:"warning",rule:n.code||"",message:n.message||""}:null).filter(n=>n&&(n.file||n.message)):[]}function Pm(r){let t=String(r||"").trim();if(!t)return[];let e=[];for(let n of t.split(`
909
- `)){let i=n.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{continue}if(!s||typeof s!="object")continue;let o=s.location||{};e.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""})}return e.filter(n=>n.file||n.message)}var Cm=[{id:"oxlint",detect:r=>q(U(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>ym(),args:(r,t={})=>{let e=t.baseDir||".",i=wm.some(o=>q(U(e,o)))?null:Sm();return["--format","json",...i?["--config",i]:[],...r]},parse:Lm},{id:"semgrep",detect:r=>xm(r,Ys),langs:Ys,bin:()=>gm(),args:(r,t={})=>{let e=t.baseDir||".",n=Nm(e),{path:i}=Am(r);return[...n?["-rules",n]:[],"-targets",i,"-json"]},parse:jm},{id:"ruff",detect:r=>q(U(r,"pyproject.toml"))||q(U(r,"requirements.txt"))||q(U(r,"setup.py")),langs:[".py"],bin:()=>process.env.RUFF_BIN||"ruff",args:r=>["check","--output-format","json",...r],parse:$m},{id:"staticcheck",detect:r=>q(U(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:Pm}];function Um(r,t,e){let n=[],i=new Set(t.map(o=>o.toLowerCase())),s=[r];for(;s.length&&n.length<e;){let o=s.pop(),a;try{a=Zs(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(n.length>=e)break;c.isDirectory()?!Xs.has(c.name)&&!c.name.startsWith(".")&&s.push(U(o,c.name)):c.isFile()&&i.has(er(c.name).toLowerCase())&&n.push(U(o,c.name))}}return n}function Bm(r,t,e){let n=e.map(a=>pm(t,a)).filter(Boolean);if(!n.length)return{scanner:r.id,skipped:"no matching files"};let i=r.bin(),s=dm(i,r.args(n,{baseDir:t}),{cwd:t,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(s.error){let a=s.error.code==="ENOENT"?`binary not installed (${i})`:String(s.error.message||s.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(s.stdout,s.stderr,s.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:n.length,findings:o}}var to={id:"code-scan",serverName:"code_scan",meta:mm["code-scan"],allowedTools:["mcp__code_scan__*"],description:"Code scan \u2014 run the RIGHT deterministic linter/analyzer for a checked-out repo (auto-detects the stack: JS/TS\u2192oxlint; Java/Python/Go/Ruby/PHP\u2192semgrep) and return structured findings. Fully local; the code never leaves the box.",promptFragment:`## Code Scan (deterministic linter, auto-detects the stack)
971
+ post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:t}={}){let e=vf();if(!e)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&t?Xe(r,t):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:[e,"../dist/socialCard.js","socialCardSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){if(r!=="social_card_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let e=t?.headline;if(typeof e!="string"||!e.trim())return JSON.stringify({error:"headline (the big bold line) is required and must be a non-empty string."});let n=ho(t?.width,wo),i=ho(t?.height,bf),s=t?.theme==="light"?"light":"dark",o=Tf(t?.accent,wf),a;try{a=Af({width:n,height:i,theme:s,accent:o,headline:e,eyebrow:t?.eyebrow,subhead:t?.subhead,stat:t?.stat,footer:t?.footer,diagram:t?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=Ef(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let l=Nf(),d=Of(t?.filename)||`social-card-${Date.now()}`,p=Xe(l,`${d}.png`);fo(p,c);let u=[{path:p,format:"png",bytes:c.length}];if(t?.output==="both"||t?.output==="svg"){let m=Xe(l,`${d}.svg`);fo(m,a,"utf-8"),u.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:i,theme:s,files:u})}catch(e){return JSON.stringify({error:`social_card_render failed: ${e.message}`})}},tools:[{name:"social_card_render",description:'Render a BRANDED "concept card" PNG LOCALLY (no external service) from structured fields \u2014 the clean LinkedIn concept-card style: bold headline + small uppercase eyebrow + optional supporting subhead, stat, footer, and an A\u2014\u2713\u2014B diagram. Returns { ok:true, files:[{ path, format:"png", bytes }] }. Pass the returned `path` as `imagePath` to a LinkedIn post tool to attach it as the post image. Example: { "headline":"No more copy-paste between AI tools", "eyebrow":"MY WORKFLOW", "stat":"11.8k stars", "footer":"Apache 2.0", "diagram":["Claude Code","Codex"] }.',input_schema:{type:"object",properties:{headline:{type:"string",description:"REQUIRED. The big, bold line \u2014 the single key idea/takeaway. Word-wrapped + auto-sized."},eyebrow:{type:"string",description:'Small uppercase kicker above the headline (e.g. "MY WORKFLOW", "OPEN SOURCE"). Rendered uppercased in the accent color.'},subhead:{type:"string",description:"One supporting line under the headline (muted)."},stat:{type:"string",description:'Optional stat, shown bottom-right in the accent color (e.g. "11.8k stars", "3x faster").'},footer:{type:"string",description:'Optional footer, shown bottom-left (muted) (e.g. "Apache 2.0", a repo name).'},diagram:{type:"array",items:{type:"string"},description:'Optional 2-3 short labels rendered as a chain of pills joined by a checkmark (A \u2014\u2713\u2014 B), e.g. ["Claude Code","Codex"].'},theme:{type:"string",enum:["dark","light"],description:"Card theme (default 'dark' \u2014 near-black bg, off-white text)."},accent:{type:"string",description:'Accent hex color (e.g. "#f97316"). Defaults to a tasteful blue (#3b82f6).'},width:{type:"number",description:"Image width in px (default 1200 \u2014 LinkedIn 1.91:1 link image)."},height:{type:"number",description:"Image height in px (default 627)."},filename:{type:"string",description:"Optional file basename (no extension); defaults to social-card-<timestamp>."},output:{type:"string",enum:["png","both"],description:"Which file(s) to write (default 'png'; 'both' also writes the .svg)."}},required:["headline"]}}]};import{spawnSync as xf}from"node:child_process";import{existsSync as D,readdirSync as Oo,statSync as To,writeFileSync as on,mkdirSync as an}from"node:fs";import{dirname as sn,extname as pr,join as U,relative as jf,resolve as dr}from"node:path";import{tmpdir as cn}from"node:os";import{fileURLToPath as Lf}from"node:url";import{SKILL_META as $f}from"@zibby/skill-ids";import{binPath as Pf}from"@zibby/bin-oxlint";import{binPath as Cf}from"@zibby/bin-semgrep";function Uf(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=Pf();if(r&&D(r))return r}catch{}return"oxlint"}function Bf(){if(process.env.SEMGREP_CORE_BIN)return process.env.SEMGREP_CORE_BIN;try{let r=Cf();if(r&&D(r))return r}catch{}return"semgrep-core"}function Jf(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=sn(Lf(import.meta.url)),t=dr(r,"..","bin","mcp-skill.mjs");return D(t)?t:null}var Ro=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),Df=400,qf={plugins:["react","typescript","unicorn","oxc"],categories:{correctness:"error",suspicious:"warn"},rules:{"react/react-in-jsx-scope":"off","react/jsx-max-depth":"off","react/no-array-index-key":"off","react/jsx-key":"error","react/no-unknown-property":"error","no-unused-vars":"warn",eqeqeq:"warn"}},Mf=[".oxlintrc.json",".oxlintrc","oxlint.json"],cr=null;function Ff(){if(cr&&D(cr))return cr;try{let r=U(cn(),"zibby-code-scan");an(r,{recursive:!0});let t=U(r,"oxlintrc.curated.json");return on(t,JSON.stringify(qf),"utf-8"),cr=t,t}catch{return null}}var Ao={".java":"java",".py":"python",".go":"go",".rb":"ruby",".php":"php"},Io=Object.keys(Ao),Eo={rules:[{id:"zibby-java-command-injection",languages:["java"],severity:"ERROR",message:"Command execution (Runtime.exec / ProcessBuilder) \u2014 command injection risk if the argument is attacker-influenced. Validate/allow-list the input or avoid a shell.",patterns:[{"pattern-either":[{pattern:"Runtime.getRuntime().exec(...)"},{pattern:"new ProcessBuilder(...)"}]}]},{id:"zibby-python-subprocess-shell",languages:["python"],severity:"ERROR",message:"subprocess call with shell=True \u2014 command injection risk. Pass an argv list and shell=False.",pattern:"subprocess.$F(..., shell=True, ...)"},{id:"zibby-python-yaml-load",languages:["python"],severity:"WARNING",message:"yaml.load without a safe loader can instantiate arbitrary Python objects. Use yaml.safe_load.",pattern:"yaml.load(...)"},{id:"zibby-go-command-injection",languages:["go"],severity:"WARNING",message:"os/exec with a non-constant command \u2014 verify the value is not attacker-controlled (command injection).",pattern:"exec.Command($CMD, ...)"},{id:"zibby-ruby-command-injection",languages:["ruby"],severity:"ERROR",message:"Shell/eval execution (system / eval) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...)"},{pattern:"eval(...)"}]}]},{id:"zibby-php-command-injection",languages:["php"],severity:"ERROR",message:"Shell/eval execution (system / exec / shell_exec) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...);"},{pattern:"exec(...);"},{pattern:"shell_exec(...);"}]}]}]},Kf=[".semgrep.yml",".semgrep.yaml","semgrep.yml","semgrep.yaml"],lr=null;function Gf(){if(lr&&D(lr))return lr;try{let r=U(cn(),"zibby-code-scan");an(r,{recursive:!0});let t=U(r,"semgrep.curated.rules.json");return on(t,JSON.stringify(Eo),"utf-8"),lr=t,t}catch{return null}}function Hf(r){return Kf.map(e=>U(r,e)).find(e=>D(e))||Gf()}function zf(r){let t=[];for(let e of Array.isArray(r)?r:[]){if(typeof e!="string"||!e)continue;let n=Ao[pr(e).toLowerCase()];if(!n)continue;let i=e.replace(/\\/g,"/");t.push(["CodeTarget",{path:{fpath:i,ppath:`/${i.replace(/^\/+/,"")}`},analyzer:n,products:["sast"]}])}return["Targets",t]}var Yf=0;function Wf(r){let t=zf(r),e=t[1].length,n=U(cn(),"zibby-code-scan");an(n,{recursive:!0});let i=U(n,`semgrep.targets.${process.pid}.${Yf++}.json`);return on(i,JSON.stringify(t),"utf-8"),{path:i,count:e}}function No(r){let t=typeof r=="string"?r.toUpperCase():"";return t==="ERROR"?"error":t==="INFO"||t==="INVENTORY"||t==="EXPERIMENT"?"info":"warning"}var Zf=Object.fromEntries(Eo.rules.map(r=>[r.id,r.severity]));function Vf(r,t){if(t)return No(t);let e=Zf[r];return e?No(e):"warning"}function Xf(r){let t=String(r||""),e=t.indexOf("{");if(e<0)return[];let n;try{n=JSON.parse(t.slice(e))}catch{return[]}return(n&&Array.isArray(n.results)?n.results:[]).map(s=>{if(!s||typeof s!="object")return null;let o=s.start&&typeof s.start=="object"?s.start:{},a=s.extra&&typeof s.extra=="object"?s.extra:{};return{file:s.path||"",line:Number.isFinite(o.line)?o.line:"",severity:Vf(s.check_id,a.severity),rule:s.check_id||"",message:(a.message||"").trim()}}).filter(s=>s&&(s.file||s.message))}function Qf(r,t,e=4e3){let n=new Set(t.map(o=>o.toLowerCase())),i=[r],s=0;for(;i.length;){let o=i.pop(),a;try{a=Oo(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(++s>e)return!1;if(c.isDirectory())!Ro.has(c.name)&&!c.name.startsWith(".")&&i.push(U(o,c.name));else if(c.isFile()&&n.has(pr(c.name).toLowerCase()))return!0}}return!1}function eh(r){let t=String(r||"").trim();if(!t)return[];let e;try{e=JSON.parse(t)}catch{return[]}return(Array.isArray(e)?e:e&&Array.isArray(e.diagnostics)?e.diagnostics:[]).map(i=>{if(!i||typeof i!="object")return null;let s=Array.isArray(i.labels)&&i.labels.length?i.labels[0]:null,o=s&&s.span?s.span:null;return{file:i.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:i.severity||"warning",rule:i.code||"",message:i.message||""}}).filter(i=>i&&(i.file||i.message))}function th(r){let t=String(r||"").trim();if(!t)return[];let e;try{e=JSON.parse(t)}catch{return[]}return Array.isArray(e)?e.map(n=>n&&typeof n=="object"?{file:n.filename||"",line:n.location&&Number.isFinite(n.location.row)?n.location.row:"",severity:"warning",rule:n.code||"",message:n.message||""}:null).filter(n=>n&&(n.file||n.message)):[]}function rh(r){let t=String(r||"").trim();if(!t)return[];let e=[];for(let n of t.split(`
972
+ `)){let i=n.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{continue}if(!s||typeof s!="object")continue;let o=s.location||{};e.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""})}return e.filter(n=>n.file||n.message)}var nh=[{id:"oxlint",detect:r=>D(U(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>Uf(),args:(r,t={})=>{let e=t.baseDir||".",i=Mf.some(o=>D(U(e,o)))?null:Ff();return["--format","json",...i?["--config",i]:[],...r]},parse:eh},{id:"semgrep",detect:r=>Qf(r,Io),langs:Io,bin:()=>Bf(),args:(r,t={})=>{let e=t.baseDir||".",n=Hf(e),{path:i}=Wf(r);return[...n?["-rules",n]:[],"-targets",i,"-json"]},parse:Xf},{id:"ruff",detect:r=>D(U(r,"pyproject.toml"))||D(U(r,"requirements.txt"))||D(U(r,"setup.py")),langs:[".py"],bin:()=>process.env.RUFF_BIN||"ruff",args:r=>["check","--output-format","json",...r],parse:th},{id:"staticcheck",detect:r=>D(U(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:rh}];function ih(r,t,e){let n=[],i=new Set(t.map(o=>o.toLowerCase())),s=[r];for(;s.length&&n.length<e;){let o=s.pop(),a;try{a=Oo(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(n.length>=e)break;c.isDirectory()?!Ro.has(c.name)&&!c.name.startsWith(".")&&s.push(U(o,c.name)):c.isFile()&&i.has(pr(c.name).toLowerCase())&&n.push(U(o,c.name))}}return n}function sh(r,t,e){let n=e.map(a=>jf(t,a)).filter(Boolean);if(!n.length)return{scanner:r.id,skipped:"no matching files"};let i=r.bin(),s=xf(i,r.args(n,{baseDir:t}),{cwd:t,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(s.error){let a=s.error.code==="ENOENT"?`binary not installed (${i})`:String(s.error.message||s.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(s.stdout,s.stderr,s.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:n.length,findings:o}}var xo={id:"code-scan",serverName:"code_scan",meta:$f["code-scan"],allowedTools:["mcp__code_scan__*"],description:"Code scan \u2014 run the RIGHT deterministic linter/analyzer for a checked-out repo (auto-detects the stack: JS/TS\u2192oxlint; Java/Python/Go/Ruby/PHP\u2192semgrep) and return structured findings. Fully local; the code never leaves the box.",promptFragment:`## Code Scan (deterministic linter, auto-detects the stack)
910
973
  After you've cloned the repo, call \`scan_code\` to get DETERMINISTIC linter
911
974
  findings for WHATEVER stack this repo is \u2014 it auto-detects (JS/TS\u2192oxlint;
912
975
  Java/Python/Go/Ruby/PHP\u2192semgrep) and runs the matching tool. Pass \`files\` (the changed files, ideal for
913
976
  a review) or \`dir\` (a directory to scan). Findings are GROUND-TRUTH CANDIDATES:
914
977
  triage them for THIS change, verify each in context (false positives exist \u2014
915
978
  trace before asserting), fold noise, and turn the real ones into inline
916
- suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=_m();return r?{type:"stdio",command:"node",args:[r,"../dist/code-scan.js","codeScanSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,t){if(r!=="scan_code")return JSON.stringify({error:`Unknown tool: ${r}`});try{let e=Array.isArray(t?.files)?t.files.filter(a=>typeof a=="string"&&a.trim()):null,n;if(t?.dir&&typeof t.dir=="string"?n=Qt(t.dir):e&&e.length?n=Jm(e.map(a=>Qt(a))):n=process.cwd(),!q(n)||!Vs(n).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${n}`});let i=e?e.map(a=>Qt(n,a)):null,s=[],o=0;for(let a of Cm){let c=!1;try{c=!!a.detect(n)}catch{c=!1}if(!c)continue;let d=new Set(a.langs.map(u=>u.toLowerCase())),l=i?i.filter(u=>d.has(er(u).toLowerCase())):Um(n,a.langs,bm),p=Bm(a,n,l);Array.isArray(p.findings)&&(o+=p.findings.length),s.push(p)}return s.length?JSON.stringify({ok:!0,baseDir:n,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:n,scanners:[],totalFindings:0,note:"No known stack detected (no package.json / pyproject / go.mod \u2026). Review by hand."})}catch(e){return JSON.stringify({error:`scan_code failed: ${e.message}`})}},tools:[{name:"scan_code",description:"Run the right deterministic linter for a checked-out repo and return structured findings. Auto-detects the stack (JS/TS \u2192 oxlint; Java/Python/Go/Ruby/PHP \u2192 semgrep OSS) and runs each matching tool, scoped to files in its languages. Pass `files` (e.g. the changed files of the PR \u2014 recommended for a review) OR `dir` (a directory to scan). Returns { scanners: [ { scanner, findings: [ { file, line, severity, rule, message } ] } ] }. Findings are CANDIDATES \u2014 verify each in context before asserting. Best-effort: a stack whose linter is not installed is skipped with a note.",input_schema:{type:"object",properties:{dir:{type:"string",description:"Absolute path to the checked-out repo (or subdirectory) to scan. Defaults to the current working directory."},files:{type:"array",items:{type:"string"},description:"Explicit list of files to scan (paths relative to `dir`, or absolute). Best for a code review \u2014 pass the PR's changed files. When omitted, the whole `dir` is walked (bounded)."}}}}]};function Jm(r){if(!r.length)return process.cwd();if(r.length===1)return Gr(r[0]);let t=r.map(s=>s.split("/")),e=t[0],n=[];for(let s=0;s<e.length;s++){let o=e[s];if(t.every(a=>a[s]===o))n.push(o);else break}let i=n.join("/");return i&&q(i)&&Vs(i).isDirectory()?i:Gr(r[0])}import{dirname as qm,resolve as Dm}from"path";import{fileURLToPath as Mm}from"url";import{existsSync as Km}from"fs";function Gm(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=qm(Mm(import.meta.url)),t=Dm(r,"..","bin","mcp-skill.mjs");return Km(t)?t:null}function Fm(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function Hm(){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 zm={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:[]}},ro={id:"trigger-agent",callsBackend:!0,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=Gm();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","PROJECT_ID","WORKFLOW_TYPE","PROGRESS_API_URL","ZIBBY_ACCOUNT_API_URL","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_USER_TOKEN"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/triggerAgent.js","triggerAgentSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(r,t={}){if(r!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${r}`});try{let e=process.env.PROJECT_ID,n=Fm(),i=typeof t.workflowType=="string"&&t.workflowType.trim()?t.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!e)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!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=`${Hm()}/projects/${encodeURIComponent(e)}/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:t.input&&typeof t.input=="object"?t.input:{}}),signal:o.signal})}finally{clearTimeout(a)}let d=await c.text().catch(()=>""),l;try{l=d?JSON.parse(d):{}}catch{l={raw:d}}if(!c.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${c.status})`,detail:l&&(l.error||l.message)||d.slice(0,300)});let p=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:p,note:"run started (fire-and-forget)"})}catch(e){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${e?.message||String(e)}`})}},tools:[zm]};import{spawnSync as Ym}from"node:child_process";import{existsSync as Yr,mkdirSync as no,readdirSync as Wm,writeFileSync as Zm}from"node:fs";import{createHash as Vm}from"node:crypto";import{join as tr}from"node:path";import{SKILL_META as Xm}from"@zibby/skill-ids";function io(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function so(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?tr(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function Qm(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",t=tr(r,".zibby","repos");try{if(Yr(t)){let e=Wm(t,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>tr(t,n.name));if(e.length===1)return e[0];if(e.length>1)return t}}catch{}return null}function ef(r){return Vm("sha256").update(r).digest("hex").slice(0,16)}var oo={id:"codebase-memory",serverName:"codebase_memory",meta:Xm["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)
979
+ suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=Jf();return r?{type:"stdio",command:"node",args:[r,"../dist/code-scan.js","codeScanSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,t){if(r!=="scan_code")return JSON.stringify({error:`Unknown tool: ${r}`});try{let e=Array.isArray(t?.files)?t.files.filter(a=>typeof a=="string"&&a.trim()):null,n;if(t?.dir&&typeof t.dir=="string"?n=dr(t.dir):e&&e.length?n=oh(e.map(a=>dr(a))):n=process.cwd(),!D(n)||!To(n).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${n}`});let i=e?e.map(a=>dr(n,a)):null,s=[],o=0;for(let a of nh){let c=!1;try{c=!!a.detect(n)}catch{c=!1}if(!c)continue;let l=new Set(a.langs.map(u=>u.toLowerCase())),d=i?i.filter(u=>l.has(pr(u).toLowerCase())):ih(n,a.langs,Df),p=sh(a,n,d);Array.isArray(p.findings)&&(o+=p.findings.length),s.push(p)}return s.length?JSON.stringify({ok:!0,baseDir:n,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:n,scanners:[],totalFindings:0,note:"No known stack detected (no package.json / pyproject / go.mod \u2026). Review by hand."})}catch(e){return JSON.stringify({error:`scan_code failed: ${e.message}`})}},tools:[{name:"scan_code",description:"Run the right deterministic linter for a checked-out repo and return structured findings. Auto-detects the stack (JS/TS \u2192 oxlint; Java/Python/Go/Ruby/PHP \u2192 semgrep OSS) and runs each matching tool, scoped to files in its languages. Pass `files` (e.g. the changed files of the PR \u2014 recommended for a review) OR `dir` (a directory to scan). Returns { scanners: [ { scanner, findings: [ { file, line, severity, rule, message } ] } ] }. Findings are CANDIDATES \u2014 verify each in context before asserting. Best-effort: a stack whose linter is not installed is skipped with a note.",input_schema:{type:"object",properties:{dir:{type:"string",description:"Absolute path to the checked-out repo (or subdirectory) to scan. Defaults to the current working directory."},files:{type:"array",items:{type:"string"},description:"Explicit list of files to scan (paths relative to `dir`, or absolute). Best for a code review \u2014 pass the PR's changed files. When omitted, the whole `dir` is walked (bounded)."}}}}]};function oh(r){if(!r.length)return process.cwd();if(r.length===1)return sn(r[0]);let t=r.map(s=>s.split("/")),e=t[0],n=[];for(let s=0;s<e.length;s++){let o=e[s];if(t.every(a=>a[s]===o))n.push(o);else break}let i=n.join("/");return i&&D(i)&&To(i).isDirectory()?i:sn(r[0])}import{dirname as ah,resolve as ch}from"path";import{fileURLToPath as lh}from"url";import{existsSync as dh}from"fs";function ph(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ah(lh(import.meta.url)),t=ch(r,"..","bin","mcp-skill.mjs");return dh(t)?t:null}function uh(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function mh(){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 fh={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:[]}},jo={id:"trigger-agent",callsBackend:!0,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=ph();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","PROJECT_ID","WORKFLOW_TYPE","PROGRESS_API_URL","ZIBBY_ACCOUNT_API_URL","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_USER_TOKEN"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/triggerAgent.js","triggerAgentSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(r,t={}){if(r!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${r}`});try{let e=process.env.PROJECT_ID,n=uh(),i=typeof t.workflowType=="string"&&t.workflowType.trim()?t.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!e)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!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=`${mh()}/projects/${encodeURIComponent(e)}/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:t.input&&typeof t.input=="object"?t.input:{}}),signal:o.signal})}finally{clearTimeout(a)}let l=await c.text().catch(()=>""),d;try{d=l?JSON.parse(l):{}}catch{d={raw:l}}if(!c.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${c.status})`,detail:d&&(d.error||d.message)||l.slice(0,300)});let p=d.executionId||d.execution?.id||d.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:p,note:"run started (fire-and-forget)"})}catch(e){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${e?.message||String(e)}`})}},tools:[fh]};import{spawnSync as hh}from"node:child_process";import{existsSync as ln,mkdirSync as Lo,readdirSync as yh,writeFileSync as gh}from"node:fs";import{createHash as bh}from"node:crypto";import{join as ur}from"node:path";import{SKILL_META as _h}from"@zibby/skill-ids";function $o(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function Po(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?ur(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function kh(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",t=ur(r,".zibby","repos");try{if(ln(t)){let e=yh(t,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>ur(t,n.name));if(e.length===1)return e[0];if(e.length>1)return t}}catch{}return null}function wh(r){return bh("sha256").update(r).digest("hex").slice(0,16)}var Co={id:"codebase-memory",serverName:"codebase_memory",meta:_h["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)
917
980
  The checked-out repository is indexed into a queryable code graph + semantic
918
981
  index. Reach for these instead of blindly grepping when you need structure,
919
982
  relationships, or "where does X live / what depends on Y":
@@ -925,8 +988,8 @@ relationships, or "where does X live / what depends on Y":
925
988
  - get_code_snippet / search_code: pull the exact code for a node / text match.
926
989
  - index_status / list_projects: confirm the index is present before querying.
927
990
  The repo is indexed for you at the start of the run; if a query comes back
928
- empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=so();try{no(r,{recursive:!0})}catch{}let t={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(t.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:io(),args:[],env:t,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=Qm();if(!r)return{};let t=so();try{no(t,{recursive:!0})}catch{}let e=tr(t,`.cbm-indexed-${ef(r)}`);if(Yr(e))return{};let n=io();if(!Yr(n)&&!process.env.CBM_BIN)return{};let i=Ym(n,["cli","index_repository",JSON.stringify({repo_path:r})],{env:{...process.env,CBM_CACHE_DIR:t},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{Zm(e,`${new Date().toISOString()} status=${i.status}
929
- `)}catch{}}catch{}return{}}};import{existsSync as ao,readFileSync as tf}from"node:fs";import{homedir as rf}from"node:os";import{join as nf,dirname as sf,resolve as of}from"node:path";import{fileURLToPath as af}from"node:url";import{SKILL_META as cf}from"@zibby/skill-ids";var lf=3e4,Wr=1;function df(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=sf(af(import.meta.url)),t=of(r,"..","bin","mcp-skill.mjs");return ao(t)?t:null}function pf(){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=nf(rf(),".zibby","config.json");return ao(r)&&JSON.parse(tf(r,"utf-8")).sessionToken||null}catch{return null}}function uf(){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 mf(){let r={};for(let[t,e]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(t);if(!n)continue;let i=typeof e=="string"?e.trim():"";i&&(r[n[1]]=i)}return r}function Zr(r){let t=mf(),e=Object.keys(t),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(t,n)?{storeId:t[n],name:n}:{error:`unknown store '${n}'; available: ${e.join(", ")}`}:e.length===1?{storeId:t[e[0]],name:e[0]}:e.length===0?{error:"no knowledge-base store is bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${e.join(", ")})`}}async function Vr(r,t,e){let n=pf();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). The knowledge base is only available inside a Zibby run.");let i=`${uf()}/datasets/stores/${encodeURIComponent(r)}/${t}`,s={Authorization:`Bearer ${n}`,"Content-Type":"application/json"},o=JSON.stringify(e),a;for(let c=0;c<=Wr;c++){let d=new AbortController,l=setTimeout(()=>d.abort(),lf);try{let p=await fetch(i,{method:"POST",headers:s,body:o,signal:d.signal}),u=await p.text().catch(()=>"");if(p.status>=500&&c<Wr){a=new Error(`store ${p.status}`);continue}if(!p.ok)throw new Error(`gbrain ${t} failed (${p.status}): ${u.slice(0,300)}`);try{return JSON.parse(u)}catch{throw new Error(`store returned non-JSON: ${u.slice(0,200)}`)}}catch(p){if(a=p,!((p?.name==="AbortError"||p?.code==="ECONNREFUSED"||/fetch failed|network/i.test(String(p?.message)))&&c<Wr))break}finally{clearTimeout(l)}}throw a||new Error(`gbrain ${t} request failed`)}var co={id:"gbrain",callsBackend:!0,serverName:"gbrain",allowedTools:["mcp__gbrain__*"],meta:cf.gbrain,description:"Knowledge base (GBrain) \u2014 ingest source documents into, semantically query, and prune a per-tenant Postgres/pgvector brain (a `postgres`-type store, brokered by the control-plane)",promptFragment:`## Knowledge Base (GBrain \u2014 per-tenant document brain)
991
+ empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=Po();try{Lo(r,{recursive:!0})}catch{}let t={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(t.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:$o(),args:[],env:t,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=kh();if(!r)return{};let t=Po();try{Lo(t,{recursive:!0})}catch{}let e=ur(t,`.cbm-indexed-${wh(r)}`);if(ln(e))return{};let n=$o();if(!ln(n)&&!process.env.CBM_BIN)return{};let i=hh(n,["cli","index_repository",JSON.stringify({repo_path:r})],{env:{...process.env,CBM_CACHE_DIR:t},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{gh(e,`${new Date().toISOString()} status=${i.status}
992
+ `)}catch{}}catch{}return{}}};import{existsSync as Uo,readFileSync as Sh}from"node:fs";import{homedir as vh}from"node:os";import{join as Ih,dirname as Nh,resolve as Oh}from"node:path";import{fileURLToPath as Th}from"node:url";import{SKILL_META as Rh}from"@zibby/skill-ids";var Ah=3e4,dn=1;function Eh(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Nh(Th(import.meta.url)),t=Oh(r,"..","bin","mcp-skill.mjs");return Uo(t)?t:null}function xh(){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=Ih(vh(),".zibby","config.json");return Uo(r)&&JSON.parse(Sh(r,"utf-8")).sessionToken||null}catch{return null}}function jh(){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 Lh(){let r={};for(let[t,e]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(t);if(!n)continue;let i=typeof e=="string"?e.trim():"";i&&(r[n[1]]=i)}return r}function pn(r){let t=Lh(),e=Object.keys(t),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(t,n)?{storeId:t[n],name:n}:{error:`unknown store '${n}'; available: ${e.join(", ")}`}:e.length===1?{storeId:t[e[0]],name:e[0]}:e.length===0?{error:"no knowledge-base store is bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${e.join(", ")})`}}async function un(r,t,e){let n=xh();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). The knowledge base is only available inside a Zibby run.");let i=`${jh()}/datasets/stores/${encodeURIComponent(r)}/${t}`,s={Authorization:`Bearer ${n}`,"Content-Type":"application/json"},o=JSON.stringify(e),a;for(let c=0;c<=dn;c++){let l=new AbortController,d=setTimeout(()=>l.abort(),Ah);try{let p=await fetch(i,{method:"POST",headers:s,body:o,signal:l.signal}),u=await p.text().catch(()=>"");if(p.status>=500&&c<dn){a=new Error(`store ${p.status}`);continue}if(!p.ok)throw new Error(`gbrain ${t} failed (${p.status}): ${u.slice(0,300)}`);try{return JSON.parse(u)}catch{throw new Error(`store returned non-JSON: ${u.slice(0,200)}`)}}catch(p){if(a=p,!((p?.name==="AbortError"||p?.code==="ECONNREFUSED"||/fetch failed|network/i.test(String(p?.message)))&&c<dn))break}finally{clearTimeout(d)}}throw a||new Error(`gbrain ${t} request failed`)}var Bo={id:"gbrain",callsBackend:!0,serverName:"gbrain",allowedTools:["mcp__gbrain__*"],meta:Rh.gbrain,description:"Knowledge base (GBrain) \u2014 ingest source documents into, semantically query, and prune a per-tenant Postgres/pgvector brain (a `postgres`-type store, brokered by the control-plane)",promptFragment:`## Knowledge Base (GBrain \u2014 per-tenant document brain)
930
993
  You have a per-tenant KNOWLEDGE BASE (a Postgres + pgvector "brain"), bound as a
931
994
  \`postgres\`-type store in the "AVAILABLE STORES" block below. Ingested documents
932
995
  are addressed by a STABLE \`sourceId\` so re-ingesting the same source UPSERTS
@@ -937,7 +1000,7 @@ Tools:
937
1000
  Pass deleted:true to remove a source that no longer exists upstream.
938
1001
  - gbrain_query({ query, topK, store? }): semantic search; returns the topK most
939
1002
  relevant document chunks with their sourceId and relevance score.
940
- - gbrain_delete({ sourceIds, store? }): remove documents by their stable sourceId(s).`,resolve(){let r=df();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/gbrain.js","gbrainSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"gbrain_ingest":{let e=Array.isArray(t?.docs)?t.docs:null;if(!e)return JSON.stringify({error:"docs is required (array of { sourceId, markdown, deleted? })"});if(e.length===0)return JSON.stringify({ok:!0,upserted:0,deleted:0,chunks:0,note:"empty docs \u2014 nothing to ingest"});if(e.find(a=>!a||typeof a.sourceId!="string"||!a.sourceId.trim())!==void 0)return JSON.stringify({error:"every doc requires a non-empty string sourceId"});let i=e.find(a=>a.deleted!==!0&&(typeof a.markdown!="string"||!a.markdown.length));if(i!==void 0)return JSON.stringify({error:`doc "${i.sourceId}" has no markdown (required unless deleted:true)`});let s=Zr(t?.store);if(s.error)return JSON.stringify({error:s.error});let o=await Vr(s.storeId,"ingest",{docs:e});return JSON.stringify({...o,store:s.name,storeId:s.storeId})}case"gbrain_query":{let e=typeof t?.query=="string"?t.query.trim():"";if(!e)return JSON.stringify({error:"query is required"});let n=Zr(t?.store);if(n.error)return JSON.stringify({error:n.error});let i={query:e};Number.isInteger(t?.topK)&&t.topK>0&&(i.topK=Math.min(t.topK,50));let s=await Vr(n.storeId,"query",i);return JSON.stringify({...s,store:n.name,storeId:n.storeId})}case"gbrain_delete":{let e=Array.isArray(t?.sourceIds)?t.sourceIds.filter(s=>typeof s=="string"&&s.trim()):null;if(!e||e.length===0)return JSON.stringify({error:"sourceIds is required (non-empty array of strings)"});let n=Zr(t?.store);if(n.error)return JSON.stringify({error:n.error});let i=await Vr(n.storeId,"delete",{sourceIds:e});return JSON.stringify({...i,store:n.name,storeId:n.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:String(e?.message||e)})}},tools:[{name:"gbrain_ingest",description:'Upsert documents into the knowledge base. Each doc is { sourceId, markdown, deleted? }; sourceId is a STABLE id (e.g. "owner/repo#docs/x.md" or a Lark doc token) so re-ingesting the same source UPDATES in place instead of duplicating. Set deleted:true to remove a source.',input_schema:{type:"object",properties:{docs:{type:"array",description:"Documents to upsert.",items:{type:"object",properties:{sourceId:{type:"string",description:"Stable source id \u2014 the upsert/delete key."},markdown:{type:"string",description:"The normalized markdown content of the document."},deleted:{type:"boolean",description:"When true, remove this sourceId from the brain (markdown ignored)."}},required:["sourceId"]}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["docs"]}},{name:"gbrain_query",description:"Semantic-search the knowledge base and return the most relevant document chunks (each with its sourceId and relevance score).",input_schema:{type:"object",properties:{query:{type:"string",description:"Natural-language query."},topK:{type:"integer",description:"How many chunks to return (default 8, max 50)."},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["query"]}},{name:"gbrain_delete",description:"Remove documents from the knowledge base by their stable sourceId(s).",input_schema:{type:"object",properties:{sourceIds:{type:"array",description:"Stable source ids to delete.",items:{type:"string"}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["sourceIds"]}}]};import{existsSync as pe,readFileSync as ut,readdirSync as Xr,mkdirSync as ff,writeFileSync as ze,statSync as uo}from"fs";import{join as E,resolve as Qr,relative as mo,dirname as fo}from"path";import{fileURLToPath as hf}from"url";import{createRequire as yf}from"module";var gf=yf(import.meta.url),_f=`## Workflow Builder
1003
+ - gbrain_delete({ sourceIds, store? }): remove documents by their stable sourceId(s).`,resolve(){let r=Eh();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/gbrain.js","gbrainSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"gbrain_ingest":{let e=Array.isArray(t?.docs)?t.docs:null;if(!e)return JSON.stringify({error:"docs is required (array of { sourceId, markdown, deleted? })"});if(e.length===0)return JSON.stringify({ok:!0,upserted:0,deleted:0,chunks:0,note:"empty docs \u2014 nothing to ingest"});if(e.find(a=>!a||typeof a.sourceId!="string"||!a.sourceId.trim())!==void 0)return JSON.stringify({error:"every doc requires a non-empty string sourceId"});let i=e.find(a=>a.deleted!==!0&&(typeof a.markdown!="string"||!a.markdown.length));if(i!==void 0)return JSON.stringify({error:`doc "${i.sourceId}" has no markdown (required unless deleted:true)`});let s=pn(t?.store);if(s.error)return JSON.stringify({error:s.error});let o=await un(s.storeId,"ingest",{docs:e});return JSON.stringify({...o,store:s.name,storeId:s.storeId})}case"gbrain_query":{let e=typeof t?.query=="string"?t.query.trim():"";if(!e)return JSON.stringify({error:"query is required"});let n=pn(t?.store);if(n.error)return JSON.stringify({error:n.error});let i={query:e};Number.isInteger(t?.topK)&&t.topK>0&&(i.topK=Math.min(t.topK,50));let s=await un(n.storeId,"query",i);return JSON.stringify({...s,store:n.name,storeId:n.storeId})}case"gbrain_delete":{let e=Array.isArray(t?.sourceIds)?t.sourceIds.filter(s=>typeof s=="string"&&s.trim()):null;if(!e||e.length===0)return JSON.stringify({error:"sourceIds is required (non-empty array of strings)"});let n=pn(t?.store);if(n.error)return JSON.stringify({error:n.error});let i=await un(n.storeId,"delete",{sourceIds:e});return JSON.stringify({...i,store:n.name,storeId:n.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:String(e?.message||e)})}},tools:[{name:"gbrain_ingest",description:'Upsert documents into the knowledge base. Each doc is { sourceId, markdown, deleted? }; sourceId is a STABLE id (e.g. "owner/repo#docs/x.md" or a Lark doc token) so re-ingesting the same source UPDATES in place instead of duplicating. Set deleted:true to remove a source.',input_schema:{type:"object",properties:{docs:{type:"array",description:"Documents to upsert.",items:{type:"object",properties:{sourceId:{type:"string",description:"Stable source id \u2014 the upsert/delete key."},markdown:{type:"string",description:"The normalized markdown content of the document."},deleted:{type:"boolean",description:"When true, remove this sourceId from the brain (markdown ignored)."}},required:["sourceId"]}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["docs"]}},{name:"gbrain_query",description:"Semantic-search the knowledge base and return the most relevant document chunks (each with its sourceId and relevance score).",input_schema:{type:"object",properties:{query:{type:"string",description:"Natural-language query."},topK:{type:"integer",description:"How many chunks to return (default 8, max 50)."},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["query"]}},{name:"gbrain_delete",description:"Remove documents from the knowledge base by their stable sourceId(s).",input_schema:{type:"object",properties:{sourceIds:{type:"array",description:"Stable source ids to delete.",items:{type:"string"}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["sourceIds"]}}]};import{existsSync as he,readFileSync as wt,readdirSync as mn,mkdirSync as $h,writeFileSync as Qe,statSync as qo}from"fs";import{join as E,resolve as fn,relative as Mo,dirname as Fo}from"path";import{fileURLToPath as Ph}from"url";import{createRequire as Ch}from"module";var Uh=Ch(import.meta.url),Bh=`## Workflow Builder
941
1004
 
942
1005
  You can help users build custom AI workflows using the Zibby workflow framework.
943
1006
 
@@ -1047,9 +1110,9 @@ Call with no arguments to see all available topics.
1047
1110
  - Workflow names must be kebab-case (e.g., ticket-triage, pr-review).
1048
1111
  - State flows through: each node's validated output is stored under its name in state (e.g., state.classify_ticket).
1049
1112
  - Downstream nodes reference upstream outputs in their prompt function (e.g., \\\`\\\${JSON.stringify(state.classify_ticket, null, 2)}\\\`).
1050
- - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,ho=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function yo(r){return`${r.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}Workflow`}function pt(r){return`${r.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}Node`}function bf(r){let t=r?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function kf(r){let t=Qr(r,".zibby.config.mjs");if(!pe(t))return{};try{return(await import(t)).default||{}}catch{return{}}}function wf(){try{let r=fo(gf.resolve("@zibby/core/package.json")),t=E(r,"templates","browser-test-automation"),e=ut(E(t,"nodes","preflight.mjs"),"utf-8"),n=ut(E(t,"graph.mjs"),"utf-8");return{preflight:e,graph:n}}catch{return null}}var lo=fo(hf(import.meta.url));function go(){let r=Qr(lo,"..","..","..","docsite","docs");if(pe(r))return r;let t=Qr(lo,"..","docs");return pe(t)?t:null}function po(){let r=go();if(!r)return[];try{let t=(e,n="")=>{let i=[];for(let s of Xr(e)){let o=E(e,s);try{if(uo(o).isDirectory())i=i.concat(t(o,`${n}${s}/`));else if(s.endsWith(".md")){let a=`${n}${s.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return t(r)}catch{return[]}}function _o(r){let t=go();if(!t)return null;let e=E(t,`${r}.md`);if(!pe(e))return null;try{return ut(e,"utf-8")}catch{return null}}function Sf(r){let t=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(`
1113
+ - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,Ko=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function Go(r){return`${r.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}Workflow`}function kt(r){return`${r.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}Node`}function Jh(r){let t=r?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function Dh(r){let t=fn(r,".zibby.config.mjs");if(!he(t))return{};try{return(await import(t)).default||{}}catch{return{}}}function qh(){try{let r=Fo(Uh.resolve("@zibby/core/package.json")),t=E(r,"templates","browser-test-automation"),e=wt(E(t,"nodes","preflight.mjs"),"utf-8"),n=wt(E(t,"graph.mjs"),"utf-8");return{preflight:e,graph:n}}catch{return null}}var Jo=Fo(Ph(import.meta.url));function Ho(){let r=fn(Jo,"..","..","..","docsite","docs");if(he(r))return r;let t=fn(Jo,"..","docs");return he(t)?t:null}function Do(){let r=Ho();if(!r)return[];try{let t=(e,n="")=>{let i=[];for(let s of mn(e)){let o=E(e,s);try{if(qo(o).isDirectory())i=i.concat(t(o,`${n}${s}/`));else if(s.endsWith(".md")){let a=`${n}${s.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return t(r)}catch{return[]}}function zo(r){let t=Ho();if(!t)return null;let e=E(t,`${r}.md`);if(!he(e))return null;try{return wt(e,"utf-8")}catch{return null}}function Mh(r){let t=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",l=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${a}. ${c}.${l?` ${l}`:""}`}).join(`
1051
1114
  `),e=r.edges.map(o=>o.condition?`- ${o.from} \u2192 ${o.to} (conditional: ${o.condition})`:`- ${o.from} \u2192 ${o.to}`).join(`
1052
- `),n=wf(),i=_o("custom-workflows"),s="";return n&&(s+=`
1115
+ `),n=qh(),i=zo("custom-workflows"),s="";return n&&(s+=`
1053
1116
  ## Real working examples from the Zibby framework
1054
1117
 
1055
1118
  ### Example node (preflight.mjs) \u2014 a prompt-only node with Zod schema and onComplete hook:
@@ -1126,7 +1189,7 @@ Return a JSON object with this exact structure:
1126
1189
  }
1127
1190
  }
1128
1191
 
1129
- IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function bo(r,t){let e=await kf(t),n=bf(e);try{let{invokeAgent:i}=await import("@zibby/core"),s=Sf(r),o=await i(s,{state:{agentType:n,config:e,cwd:t,workspace:t}},{model:e?.agent?.[n]?.model||"auto",workspace:t,config:e,timeout:12e4}),c=(typeof o=="string"?o:o?.raw||JSON.stringify(o?.structured||o)).match(/\{[\s\S]*\}/);if(!c)throw new Error("Agent did not return valid JSON");return JSON.parse(c[0])}catch(i){return console.warn(`Agent code generation failed (${i.message}), using templates`),vf(r)}}function vf(r){let t={};for(let e of r.nodes){let n=pt(e.name),i=`${e.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,s=e.outputFields?.length?e.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
1192
+ IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function Yo(r,t){let e=await Dh(t),n=Jh(e);try{let{invokeAgent:i}=await import("@zibby/core"),s=Mh(r),o=await i(s,{state:{agentType:n,config:e,cwd:t,workspace:t}},{model:e?.agent?.[n]?.model||"auto",workspace:t,config:e,timeout:12e4}),c=(typeof o=="string"?o:o?.raw||JSON.stringify(o?.structured||o)).match(/\{[\s\S]*\}/);if(!c)throw new Error("Agent did not return valid JSON");return JSON.parse(c[0])}catch(i){return console.warn(`Agent code generation failed (${i.message}), using templates`),Fh(r)}}function Fh(r){let t={};for(let e of r.nodes){let n=kt(e.name),i=`${e.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,s=e.outputFields?.length?e.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
1130
1193
  `):` summary: z.string().describe('Summary of the result'),
1131
1194
  status: z.enum(['ok', 'warn', 'error']).describe('Overall status'),`,o=r.edges.filter(c=>c.to===e.name&&c.from!=="START").map(c=>`Previous step (${c.from}): \${JSON.stringify(state.${c.from} || {}, null, 2)}`).join(`
1132
1195
  `),a=o?`${e.description}
@@ -1148,12 +1211,12 @@ export const ${n} = {
1148
1211
  prompt: (state) => \`${a}\`,
1149
1212
  outputSchema: ${i},
1150
1213
  };
1151
- `}}return{nodes:t}}function If(r,t,e,n){let i=t.toLowerCase(),s=yo(i),o=E(r,".zibby","workflows",i),a=E(o,"nodes");ff(a,{recursive:!0});let c=e.nodes.map(g=>g.name);for(let g of e.nodes){let _=n.nodes?.[g.name]?.code;_&&ze(E(a,`${g.name.replace(/_/g,"-")}.mjs`),_,"utf-8")}let d=c.map(g=>{let _=pt(g),y=g.replace(/_/g,"-");return`export { ${_} } from './${y}.mjs';`});ze(E(a,"index.mjs"),`${d.join(`
1214
+ `}}return{nodes:t}}function Kh(r,t,e,n){let i=t.toLowerCase(),s=Go(i),o=E(r,".zibby","workflows",i),a=E(o,"nodes");$h(a,{recursive:!0});let c=e.nodes.map(y=>y.name);for(let y of e.nodes){let b=n.nodes?.[y.name]?.code;b&&Qe(E(a,`${y.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let l=c.map(y=>{let b=kt(y),g=y.replace(/_/g,"-");return`export { ${b} } from './${g}.mjs';`});Qe(E(a,"index.mjs"),`${l.join(`
1152
1215
  `)}
1153
- `,"utf-8");let l=c[0],p=c.map(g=>pt(g)).join(", "),u=c.map(g=>` graph.addNode('${g}', ${pt(g)});`).join(`
1154
- `),m=e.edges.map(g=>g.condition?` graph.addConditionalEdges('${g.from}', (state) => {
1155
- ${g.condition}
1156
- });`:` graph.addEdge('${g.from}', '${g.to}');`).join(`
1216
+ `,"utf-8");let d=c[0],p=c.map(y=>kt(y)).join(", "),u=c.map(y=>` graph.addNode('${y}', ${kt(y)});`).join(`
1217
+ `),m=e.edges.map(y=>y.condition?` graph.addConditionalEdges('${y.from}', (state) => {
1218
+ ${y.condition}
1219
+ });`:` graph.addEdge('${y.from}', '${y.to}');`).join(`
1157
1220
  `),f=`import { WorkflowAgent, WorkflowGraph } from '@zibby/core';
1158
1221
  import { ${p} } from './nodes/index.mjs';
1159
1222
 
@@ -1163,7 +1226,7 @@ export class ${s} extends WorkflowAgent {
1163
1226
 
1164
1227
  ${u}
1165
1228
 
1166
- graph.setEntryPoint('${l}');
1229
+ graph.setEntryPoint('${d}');
1167
1230
  ${m}
1168
1231
 
1169
1232
  return graph;
@@ -1173,18 +1236,18 @@ ${m}
1173
1236
  console.log(\`[${i}] workflow complete \u2014 success: \${result.success !== false}\`);
1174
1237
  }
1175
1238
  }
1176
- `;ze(E(o,"graph.mjs"),f,"utf-8");let h={name:i,description:e.description||`${s} workflow`,entryClass:s,triggers:{api:!0}};ze(E(o,"workflow.json"),`${JSON.stringify(h,null,2)}
1177
- `,"utf-8");let b=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(g=>`nodes/${g.replace(/_/g,"-")}.mjs`)];return{workflowDir:mo(r,o),files:b,className:s,slug:i}}async function Nf(r){let{name:t,description:e,nodes:n,edges:i}=r;if(!t||!ho.test(t.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${t}". 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:t.toLowerCase(),description:e||`${yo(t.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 Of(r,t){let{name:e,spec:n}=r,i=(e||n?.name||"").toLowerCase();if(!i||!ho.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=E(t,".zibby","workflows",i);if(pe(s))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await bo(n,t),a=If(t,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 Tf(r,t){let{workflowName:e,nodeName:n,description:i,inputFields:s,outputFields:o}=r,a=(e||"").toLowerCase(),c=(n||"").replace(/-/g,"_"),d=E(t,".zibby","workflows",a);if(!pe(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:i||`Process ${c}`,inputFields:s||[],outputFields:o||[]}],edges:[]},u=(await bo(l,t)).nodes?.[c]?.code;if(!u)return JSON.stringify({error:"Failed to generate node code."});let m=E(d,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;ze(E(m,f),u,"utf-8");let h=E(m,"index.mjs"),b=pt(c),g=`export { ${b} } from './${c.replace(/_/g,"-")}.mjs';
1178
- `,_=pe(h)?ut(h,"utf-8"):"";return _.includes(b)||ze(h,_+g,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:b,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Af(r,t){let{name:e,projectId:n}=r,i=(e||"").toLowerCase();if(!i)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let s=E(t,".zibby","workflows",i);if(!pe(s))return JSON.stringify({error:`Workflow "${i}" not found at .zibby/workflows/${i}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${E(t,"packages/cli/bin/zibby.js")}" deploy ${i} --project ${n}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:a.trim()})}catch{try{let{execSync:a}=await import("child_process"),c=a(`npx zibby deploy ${i} --project ${n}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:c.trim()})}catch(a){return JSON.stringify({error:`Deploy failed: ${a.message}`})}}}function Rf(r){let t=E(r,".zibby","workflows");if(!pe(t))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=Xr(t).filter(i=>{try{return uo(E(t,i)).isDirectory()}catch{return!1}}).map(i=>{let s=E(t,i,"workflow.json"),o={};try{o=JSON.parse(ut(s,"utf-8"))}catch{}let a=E(t,i,"nodes"),c=0;try{c=Xr(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:c,path:mo(r,E(t,i))}});return JSON.stringify({workflows:n})}var ko={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:_f,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,t,e){let n=e?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Nf(t);case"build_workflow":return await Of(t,n);case"add_node":return await Tf(t,n);case"deploy_workflow":return await Af(t,n);case"list_workflows":return Rf(n);case"explore_framework_docs":{let i=(t.topic||"").trim();if(!i){let o=po();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=_o(i);if(!s){let o=po();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 Ef}from"@zibby/core/backend-client.js";var tn=Object.freeze({id:"openai_billing",callsBackend:!0,requiresIntegration:I.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),rn=Object.freeze({id:"anthropic_billing",callsBackend:!0,requiresIntegration:I.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),nn=Object.freeze({id:"cursor_admin",callsBackend:!0,requiresIntegration:I.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function wo(r){return Math.floor(r/1e3)}function en(r){return new Date(r).toISOString().slice(0,10)}function So(r){return new Date(r).toISOString()}async function mt(r){let t=await Ef(r);if(!t?.token)throw new Error(`${r} token resolver returned no token`);return t.token}async function vo({startMs:r,endMs:t,groupBy:e=["project_id","line_item"]}){let n=await mt("openai_billing"),i=[],s=0,o=e.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.openai.com/v1/organization/costs?${[`start_time=${wo(r)}`,`end_time=${wo(t)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=en((m.start_time||0)*1e3);for(let h of m.results||[])i.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function jf(){let r=await mt("openai_billing"),e=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`OpenAI projects API ${e.status}: ${s.slice(0,200)}`)}let n=await e.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function Io({startMs:r,endMs:t,groupBy:e=["workspace_id"]}){let n=await mt("anthropic_billing"),i=[],s=0,o=e.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(So(r))}`,`ending_at=${encodeURIComponent(So(t))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])i.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function xf(){let r=await mt("anthropic_billing"),e=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Anthropic workspaces ${e.status}: ${s.slice(0,200)}`)}let n=await e.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function No({startMs:r,endMs:t}){let e=await mt("cursor_admin"),n=en(r),i=en(t),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${i}`,o=await fetch(s,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${l.slice(0,200)}`)}let a=await o.json(),c=[],d=0;for(let l of a.data||[]){d+=1;let p=l.date;for(let u of l.userMetrics||[]){for(let m of u.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:p,costUsd:Number(m.totalCents??0)/100,userEmail:u.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!u.modelUsage||u.modelUsage.length===0)&&c.push({provider:"cursor",day:p,costUsd:Number(u.totalCents??0)/100,userEmail:u.email})}}return{ok:!0,items:c,rawBuckets:d}}async function Lf({startMs:r,endMs:t}){let[e,n,i]=await Promise.allSettled([vo({startMs:r,endMs:t}),Io({startMs:r,endMs:t}),No({startMs:r,endMs:t})]),s=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=s(e),a=s(n),c=s(i),d=[{provider:"openai",totalUsd:o.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,p)=>l+(p.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function $f(r,t){let e=new Map;for(let n of r){let i=t(n);if(!i)continue;let s=e.get(i)||{key:i,totalUsd:0,count:0};s.totalUsd+=n.costUsd||0,s.count+=1,e.set(i,s)}return[...e.values()].sort((n,i)=>i.totalUsd-n.totalUsd)}function Pf(r){if(!r.length)return{mean:0,stddev:0};let t=r.reduce((n,i)=>n+i,0)/r.length,e=r.reduce((n,i)=>n+(i-t)**2,0)/r.length;return{mean:t,stddev:Math.sqrt(e)}}import{SKILL_IDS as tk}from"@zibby/skill-ids";import{z as w}from"zod";var ft=["ok","info","warn","critical"],Cf=w.object({primary:w.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:w.object({value:w.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:w.enum(["up","down","flat"]).optional(),severity:w.enum(ft).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:w.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),Uf=w.object({kind:w.literal("trend"),title:w.string().max(120).optional(),labels:w.array(w.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:w.array(w.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:w.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:w.enum(ft).optional()}),Bf=w.object({kind:w.literal("table"),title:w.string().max(120).optional(),headers:w.array(w.string().max(40)).min(1).max(8),rows:w.array(w.array(w.union([w.string().max(200),w.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),Jf=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(ft).default("info").optional(),items:w.array(w.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),qf=w.object({kind:w.literal("breakdown"),title:w.string().max(120).optional(),rows:w.array(w.object({label:w.string().min(1).max(80),value:w.string().min(1).max(80),sub:w.string().max(120).optional(),severity:w.enum(ft).optional()})).min(1).max(20)}),Df=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),Mf=w.discriminatedUnion("kind",[Uf,Bf,Jf,qf,Df]),ht=w.object({title:w.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:w.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:Cf,sections:w.array(Mf).max(20).default([]).superRefine((r,t)=>{r.forEach((e,n)=>{e.kind==="trend"&&e.labels.length!==e.values.length&&t.addIssue({code:w.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),e.kind==="table"&&!e.rows.every(i=>i.length===e.headers.length)&&t.addIssue({code:w.ZodIssueCode.custom,path:[n,"rows"],message:"every row must have headers.length entries"})})}),footer:w.object({viewUrl:w.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:w.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),B=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),rr=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),Kf=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function nr(r,t,e=12){if(!Number.isFinite(r)||!Number.isFinite(t)||t<=0)return"";let n=Math.max(0,Math.min(1,r/t)),i=Math.round(n*e);return"\u2593".repeat(i)+"\u2591".repeat(e-i)}function yt(r,t){let e=String(r);return e.length>=t?e:e+" ".repeat(t-e.length)}function ir(r,t){let e=String(r);return e.length>=t?e:" ".repeat(t-e.length)+e}function Ao({headers:r,rows:t}){let e=r.map((o,a)=>{let c=Math.max(String(o).length,...t.map(d=>String(d[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>yt(a,e[c])).join(" "),i=e.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),i,...t.map(o=>n(o))].join(`
1179
- `)+"\n```"}function Gf(r){let t=ht.parse(r),e=[];e.push({type:"header",text:{type:"plain_text",text:t.title.slice(0,150),emoji:!0}}),t.subtitle&&e.push({type:"context",elements:[{type:"mrkdwn",text:t.subtitle}]});let n=[`*${t.headline.primary}*`];if(t.headline.delta){let s=rr[t.headline.delta.direction]||"",o=t.headline.delta.severity?B[t.headline.delta.severity]:"";n.push(`${s} ${t.headline.delta.value} ${o}`.trim())}let i=n.join(" ");t.headline.summary&&(i+=`
1180
- `+t.headline.summary),e.push({type:"section",text:{type:"mrkdwn",text:i}});for(let s of t.sections)switch(e.push({type:"divider"}),s.title&&e.push({type:"section",text:{type:"mrkdwn",text:`*${s.title}*`}}),s.kind){case"trend":{let o=Math.max(...s.values),a=s.labels.map((c,d)=>{let l=s.values[d],p=nr(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?` ${B[s.severity]}`:"";return`${yt(c,10)} ${ir(l.toLocaleString(),8)} ${p}${m}`});e.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1181
- `)+"\n```"}});break}case"table":{e.push({type:"section",text:{type:"mrkdwn",text:Ao(s)}});break}case"callouts":{let o=B[s.tone||"info"];e.push({type:"section",text:{type:"mrkdwn",text:s.items.map(a=>`${o} ${a}`).join(`
1239
+ `;Qe(E(o,"graph.mjs"),f,"utf-8");let h={name:i,description:e.description||`${s} workflow`,entryClass:s,triggers:{api:!0}};Qe(E(o,"workflow.json"),`${JSON.stringify(h,null,2)}
1240
+ `,"utf-8");let _=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(y=>`nodes/${y.replace(/_/g,"-")}.mjs`)];return{workflowDir:Mo(r,o),files:_,className:s,slug:i}}async function Gh(r){let{name:t,description:e,nodes:n,edges:i}=r;if(!t||!Ko.test(t.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${t}". 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:t.toLowerCase(),description:e||`${Go(t.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 Hh(r,t){let{name:e,spec:n}=r,i=(e||n?.name||"").toLowerCase();if(!i||!Ko.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=E(t,".zibby","workflows",i);if(he(s))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await Yo(n,t),a=Kh(t,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 zh(r,t){let{workflowName:e,nodeName:n,description:i,inputFields:s,outputFields:o}=r,a=(e||"").toLowerCase(),c=(n||"").replace(/-/g,"_"),l=E(t,".zibby","workflows",a);if(!he(l))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let d={name:a,description:"",nodes:[{name:c,description:i||`Process ${c}`,inputFields:s||[],outputFields:o||[]}],edges:[]},u=(await Yo(d,t)).nodes?.[c]?.code;if(!u)return JSON.stringify({error:"Failed to generate node code."});let m=E(l,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;Qe(E(m,f),u,"utf-8");let h=E(m,"index.mjs"),_=kt(c),y=`export { ${_} } from './${c.replace(/_/g,"-")}.mjs';
1241
+ `,b=he(h)?wt(h,"utf-8"):"";return b.includes(_)||Qe(h,b+y,"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 Yh(r,t){let{name:e,projectId:n}=r,i=(e||"").toLowerCase();if(!i)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let s=E(t,".zibby","workflows",i);if(!he(s))return JSON.stringify({error:`Workflow "${i}" not found at .zibby/workflows/${i}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${E(t,"packages/cli/bin/zibby.js")}" deploy ${i} --project ${n}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:a.trim()})}catch{try{let{execSync:a}=await import("child_process"),c=a(`npx zibby deploy ${i} --project ${n}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:c.trim()})}catch(a){return JSON.stringify({error:`Deploy failed: ${a.message}`})}}}function Wh(r){let t=E(r,".zibby","workflows");if(!he(t))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=mn(t).filter(i=>{try{return qo(E(t,i)).isDirectory()}catch{return!1}}).map(i=>{let s=E(t,i,"workflow.json"),o={};try{o=JSON.parse(wt(s,"utf-8"))}catch{}let a=E(t,i,"nodes"),c=0;try{c=mn(a).filter(l=>l.endsWith(".mjs")&&l!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:c,path:Mo(r,E(t,i))}});return JSON.stringify({workflows:n})}var Wo={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:Bh,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,t,e){let n=e?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Gh(t);case"build_workflow":return await Hh(t,n);case"add_node":return await zh(t,n);case"deploy_workflow":return await Yh(t,n);case"list_workflows":return Wh(n);case"explore_framework_docs":{let i=(t.topic||"").trim();if(!i){let o=Do();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=zo(i);if(!s){let o=Do();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 Zh}from"@zibby/core/backend-client.js";var yn=Object.freeze({id:"openai_billing",callsBackend:!0,requiresIntegration:I.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),gn=Object.freeze({id:"anthropic_billing",callsBackend:!0,requiresIntegration:I.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),bn=Object.freeze({id:"cursor_admin",callsBackend:!0,requiresIntegration:I.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Zo(r){return Math.floor(r/1e3)}function hn(r){return new Date(r).toISOString().slice(0,10)}function Vo(r){return new Date(r).toISOString()}async function St(r){let t=await Zh(r);if(!t?.token)throw new Error(`${r} token resolver returned no token`);return t.token}async function Xo({startMs:r,endMs:t,groupBy:e=["project_id","line_item"]}){let n=await St("openai_billing"),i=[],s=0,o=e.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let d=`https://api.openai.com/v1/organization/costs?${[`start_time=${Zo(r)}`,`end_time=${Zo(t)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(d,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=hn((m.start_time||0)*1e3);for(let h of m.results||[])i.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Vh(){let r=await St("openai_billing"),e=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`OpenAI projects API ${e.status}: ${s.slice(0,200)}`)}let n=await e.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function Qo({startMs:r,endMs:t,groupBy:e=["workspace_id"]}){let n=await St("anthropic_billing"),i=[],s=0,o=e.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let d=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(Vo(r))}`,`ending_at=${encodeURIComponent(Vo(t))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(d,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])i.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Xh(){let r=await St("anthropic_billing"),e=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Anthropic workspaces ${e.status}: ${s.slice(0,200)}`)}let n=await e.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function ea({startMs:r,endMs:t}){let e=await St("cursor_admin"),n=hn(r),i=hn(t),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${i}`,o=await fetch(s,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${d.slice(0,200)}`)}let a=await o.json(),c=[],l=0;for(let d of a.data||[]){l+=1;let p=d.date;for(let u of d.userMetrics||[]){for(let m of u.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:p,costUsd:Number(m.totalCents??0)/100,userEmail:u.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!u.modelUsage||u.modelUsage.length===0)&&c.push({provider:"cursor",day:p,costUsd:Number(u.totalCents??0)/100,userEmail:u.email})}}return{ok:!0,items:c,rawBuckets:l}}async function Qh({startMs:r,endMs:t}){let[e,n,i]=await Promise.allSettled([Xo({startMs:r,endMs:t}),Qo({startMs:r,endMs:t}),ea({startMs:r,endMs:t})]),s=d=>d.status==="fulfilled"?d.value:{ok:!1,error:d.reason?.message||String(d.reason),items:[]},o=s(e),a=s(n),c=s(i),l=[{provider:"openai",totalUsd:o.items.reduce((d,p)=>d+(p.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((d,p)=>d+(p.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((d,p)=>d+(p.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:l}}function ey(r,t){let e=new Map;for(let n of r){let i=t(n);if(!i)continue;let s=e.get(i)||{key:i,totalUsd:0,count:0};s.totalUsd+=n.costUsd||0,s.count+=1,e.set(i,s)}return[...e.values()].sort((n,i)=>i.totalUsd-n.totalUsd)}function ty(r){if(!r.length)return{mean:0,stddev:0};let t=r.reduce((n,i)=>n+i,0)/r.length,e=r.reduce((n,i)=>n+(i-t)**2,0)/r.length;return{mean:t,stddev:Math.sqrt(e)}}import{SKILL_IDS as Rw}from"@zibby/skill-ids";import{z as w}from"zod";var vt=["ok","info","warn","critical"],ry=w.object({primary:w.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:w.object({value:w.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:w.enum(["up","down","flat"]).optional(),severity:w.enum(vt).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:w.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),ny=w.object({kind:w.literal("trend"),title:w.string().max(120).optional(),labels:w.array(w.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:w.array(w.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:w.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:w.enum(vt).optional()}),iy=w.object({kind:w.literal("table"),title:w.string().max(120).optional(),headers:w.array(w.string().max(40)).min(1).max(8),rows:w.array(w.array(w.union([w.string().max(200),w.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),sy=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(vt).default("info").optional(),items:w.array(w.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),oy=w.object({kind:w.literal("breakdown"),title:w.string().max(120).optional(),rows:w.array(w.object({label:w.string().min(1).max(80),value:w.string().min(1).max(80),sub:w.string().max(120).optional(),severity:w.enum(vt).optional()})).min(1).max(20)}),ay=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),cy=w.discriminatedUnion("kind",[ny,iy,sy,oy,ay]),It=w.object({title:w.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:w.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:ry,sections:w.array(cy).max(20).default([]).superRefine((r,t)=>{r.forEach((e,n)=>{e.kind==="trend"&&e.labels.length!==e.values.length&&t.addIssue({code:w.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),e.kind==="table"&&!e.rows.every(i=>i.length===e.headers.length)&&t.addIssue({code:w.ZodIssueCode.custom,path:[n,"rows"],message:"every row must have headers.length entries"})})}),footer:w.object({viewUrl:w.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:w.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),B=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),mr=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),ly=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function fr(r,t,e=12){if(!Number.isFinite(r)||!Number.isFinite(t)||t<=0)return"";let n=Math.max(0,Math.min(1,r/t)),i=Math.round(n*e);return"\u2593".repeat(i)+"\u2591".repeat(e-i)}function Nt(r,t){let e=String(r);return e.length>=t?e:e+" ".repeat(t-e.length)}function hr(r,t){let e=String(r);return e.length>=t?e:" ".repeat(t-e.length)+e}function na({headers:r,rows:t}){let e=r.map((o,a)=>{let c=Math.max(String(o).length,...t.map(l=>String(l[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>Nt(a,e[c])).join(" "),i=e.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),i,...t.map(o=>n(o))].join(`
1242
+ `)+"\n```"}function dy(r){let t=It.parse(r),e=[];e.push({type:"header",text:{type:"plain_text",text:t.title.slice(0,150),emoji:!0}}),t.subtitle&&e.push({type:"context",elements:[{type:"mrkdwn",text:t.subtitle}]});let n=[`*${t.headline.primary}*`];if(t.headline.delta){let s=mr[t.headline.delta.direction]||"",o=t.headline.delta.severity?B[t.headline.delta.severity]:"";n.push(`${s} ${t.headline.delta.value} ${o}`.trim())}let i=n.join(" ");t.headline.summary&&(i+=`
1243
+ `+t.headline.summary),e.push({type:"section",text:{type:"mrkdwn",text:i}});for(let s of t.sections)switch(e.push({type:"divider"}),s.title&&e.push({type:"section",text:{type:"mrkdwn",text:`*${s.title}*`}}),s.kind){case"trend":{let o=Math.max(...s.values),a=s.labels.map((c,l)=>{let d=s.values[l],p=fr(d,o),m=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&d===o||s.highlight==="min"&&d===Math.min(...s.values))&&s.severity?` ${B[s.severity]}`:"";return`${Nt(c,10)} ${hr(d.toLocaleString(),8)} ${p}${m}`});e.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1244
+ `)+"\n```"}});break}case"table":{e.push({type:"section",text:{type:"mrkdwn",text:na(s)}});break}case"callouts":{let o=B[s.tone||"info"];e.push({type:"section",text:{type:"mrkdwn",text:s.items.map(a=>`${o} ${a}`).join(`
1182
1245
  `)}});break}case"breakdown":{let o=s.rows.map(a=>({type:"mrkdwn",text:`*${a.label}*
1183
1246
  ${a.value}${a.sub?`
1184
- _${a.sub}_`:""}${a.severity?` ${B[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)e.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{e.push({type:"section",text:{type:"mrkdwn",text:s.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let s=[];t.footer.viewUrl&&s.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:t.footer.viewUrl,style:"primary"}),t.footer.rerunUrl&&s.push({type:"button",text:{type:"plain_text",text:"Run again"},url:t.footer.rerunUrl}),e.push({type:"divider"}),e.push({type:"actions",elements:s})}return e}function Ff(r){let t=ht.parse(r),e=[],n=[`**${t.headline.primary}**`];if(t.headline.delta){let o=rr[t.headline.delta.direction]||"",a=t.headline.delta.severity?B[t.headline.delta.severity]:"";n.push(`${o} ${t.headline.delta.value} ${a}`.trim())}let i=n.join(" ");t.headline.summary&&(i+=`
1185
- `+t.headline.summary),e.push({tag:"div",text:{tag:"lark_md",content:i}});for(let o of t.sections)switch(e.push({tag:"hr"}),o.title&&e.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let a=Math.max(...o.values),c=o.labels.map((d,l)=>{let p=o.values[l],u=nr(p,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&p===a||o.highlight==="min"&&p===Math.min(...o.values))&&o.severity?` ${B[o.severity]}`:"";return`${yt(d,10)} ${ir(p.toLocaleString(),8)} ${u}${f}`});e.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1186
- `)+"\n```"}});break}case"table":{e.push({tag:"div",text:{tag:"lark_md",content:Ao(o)}});break}case"callouts":{let a=B[o.tone||"info"];e.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
1187
- `)}});break}case"breakdown":{let a=o.rows.map(c=>{let d=c.severity?` ${B[c.severity]}`:"",l=c.sub?` *${c.sub}*`:"";return`**${c.label}** ${c.value}${l}${d}`});e.push({tag:"div",text:{tag:"lark_md",content:a.join(`
1188
- `)}});break}case"paragraph":{e.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let o=[];t.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:t.footer.viewUrl,type:"primary"}),t.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:t.footer.rerunUrl,type:"default"}),e.push({tag:"hr"}),e.push({tag:"action",actions:o})}let s="blue";return t.headline.delta?.severity&&(s=Kf[t.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:t.title.slice(0,200)},subtitle:t.subtitle?{tag:"plain_text",content:t.subtitle.slice(0,200)}:void 0,template:s},elements:e}}var Hf=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),Oo=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function Ee(r,t={}){let e={type:"text",text:{content:String(r).slice(0,2e3)}};return t.annotations&&(e.annotations=t.annotations),[e]}function sn(r,t){let e={object:"block",type:"paragraph",paragraph:{rich_text:Ee(r)}};return t&&(e.paragraph.color=t),e}function zf(r){return{object:"block",type:"code",code:{rich_text:Ee(r),language:"plain text"}}}function Yf(r){let t=ht.parse(r),e=[];e.push({object:"block",type:"heading_1",heading_1:{rich_text:Ee(t.title.slice(0,200))}}),t.subtitle&&e.push(sn(t.subtitle,"gray_background"));let n=[{type:"text",text:{content:t.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(t.headline.delta){let s=rr[t.headline.delta.direction]||"",o=t.headline.delta.severity?B[t.headline.delta.severity]:"",a=` ${s} ${t.headline.delta.value} ${o}`.trimEnd();n.push({type:"text",text:{content:a}})}e.push({object:"block",type:"paragraph",paragraph:{rich_text:n}}),t.headline.summary&&e.push(sn(t.headline.summary));for(let s of t.sections)switch(e.push({object:"block",type:"divider",divider:{}}),s.title&&e.push({object:"block",type:"heading_2",heading_2:{rich_text:Ee(s.title)}}),s.kind){case"trend":{let o=Math.max(...s.values),a=Math.min(...s.values),c=s.labels.map((d,l)=>{let p=s.values[l],u=nr(p,o),f=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&p===o||s.highlight==="min"&&p===a)&&s.severity?` ${B[s.severity]}`:"";return`${yt(d,10)} ${ir(p.toLocaleString(),8)} ${u}${f}`});e.push(zf(c.join(`
1189
- `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>Ee(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>Ee(String(d)))}}));e.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=Oo[o],c=Hf[o];for(let d of s.items)e.push({object:"block",type:"callout",callout:{rich_text:Ee(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:` ${B[o.severity]}`}}),e.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{e.push(sn(s.text));break}}t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)&&(e.push({object:"block",type:"divider",divider:{}}),t.footer.viewUrl&&e.push({object:"block",type:"embed",embed:{url:t.footer.viewUrl}}),t.footer.rerunUrl&&e.push({object:"block",type:"embed",embed:{url:t.footer.rerunUrl}}));let i=t.headline.delta?.severity?Oo[t.headline.delta.severity]:void 0;return{blocks:e,title:t.title.slice(0,200),icon:i}}function To(r){return String(r??"").replace(/\|/g,"\\|")}function Wf(r){let t=ht.parse(r),e=[];e.push(`# ${t.title}`),t.subtitle&&e.push("",t.subtitle);let n=[`**${t.headline.primary}**`];if(t.headline.delta){let i=rr[t.headline.delta.direction]||"",s=t.headline.delta.severity?B[t.headline.delta.severity]:"";n.push(`${i} ${t.headline.delta.value} ${s}`.trim())}e.push("",n.join(" ")),t.headline.summary&&e.push("",t.headline.summary);for(let i of t.sections)switch(e.push("","---",""),i.title&&e.push(`## ${i.title}`,""),i.kind){case"trend":{let s=Math.max(...i.values),o=Math.min(...i.values),a=i.labels.map((c,d)=>{let l=i.values[d],p=nr(l,s),m=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&l===s||i.highlight==="min"&&l===o)&&i.severity?` ${B[i.severity]}`:"";return`${yt(c,10)} ${ir(l.toLocaleString(),8)} ${p}${m}`});e.push("```",...a,"```");break}case"table":{e.push(`| ${i.headers.map(To).join(" | ")} |`),e.push(`| ${i.headers.map(()=>"---").join(" | ")} |`);for(let s of i.rows)e.push(`| ${s.map(To).join(" | ")} |`);break}case"callouts":{let s=B[i.tone||"info"];for(let o of i.items)e.push(`- ${s} ${o}`);break}case"breakdown":{for(let s of i.rows){let o=s.sub?` _${s.sub}_`:"",a=s.severity?` ${B[s.severity]}`:"";e.push(`- **${s.label}**: ${s.value}${o}${a}`)}break}case"paragraph":{e.push(i.text);break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let i=[];t.footer.viewUrl&&i.push(`[View in Zibby](${t.footer.viewUrl})`),t.footer.rerunUrl&&i.push(`[Run again](${t.footer.rerunUrl})`),e.push("","---","",i.join(" \xB7 "))}return e.join(`
1190
- `)}import{createRequire as Zf}from"module";import{fileURLToPath as Vf}from"url";import{registerHandlers as Xf}from"@zibby/core/function-skill-registry.js";import{registerSkill as Qf}from"@zibby/agent-workflow";var eh=Zf(import.meta.url);function th(){try{return eh.resolve("@zibby/core/function-bridge.js")}catch{return null}}var rh=import.meta.url;function nh(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let e=new Error().stack;for(let n=2;n<e.length;n++){let i=e[n].getFileName();if(i&&i!==rh&&!i.startsWith("node:"))return i.startsWith("file://")?Vf(i):i}return null}finally{Error.prepareStackTrace=r}}function ih(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let t={},e=[];for(let[n,i]of Object.entries(r))if(typeof i=="string")t[n]={type:i},e.push(n);else{let{required:s,...o}=i;t[n]=o,s!==!1&&e.push(n)}return{type:"object",properties:t,required:e}}function sh(r,t,e){if(typeof e.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n={[r]:e.handler},i=[{name:r,description:e.description||"",input_schema:ih(e.input)}];return Xf(r,n,i),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:e.description||`Function skill: ${r}`,envKeys:[],tools:i,resolve(){let s=th();return s?{command:"node",args:[s,t,r]}:null}}}function oh(r,t){return{id:r,type:"mcp",serverName:t.serverName||r,allowedTools:t.allowedTools||[`mcp__${t.serverName||r}__*`],description:t.description||`MCP skill: ${r}`,envKeys:t.envKeys||[],tools:t.tools||[],resolve:t.resolve,...t.cursorKey&&{cursorKey:t.cursorKey},...t.sessionEnvKey&&{sessionEnvKey:t.sessionEnvKey}}}function Ro(r,t){let e;if("handler"in t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n=nh();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);e=sh(r,n,t)}else if(typeof t.resolve=="function")e=oh(r,t);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return Qf(e),e}var ah=Ro;import{registerSkill as ok,getSkill as ak,hasSkill as ck,getAllSkills as lk,listSkillIds as dk}from"@zibby/agent-workflow";var v=r=>ch(ln(r));v(dn);v(mn);v($e);v(Pe);v(Tn);v(Rn);v(jn);v(Cn);v(Un);v(qn);v(P);v(M);v(Kn);v(Vn);v(ti);v(oi);v(fi);v(hi);v(Ct);v(gi);v(Di);v(fe);v(Hi);v(bi);v(Ii);v(os);v(ms);v(bs);v(Ns);v(Ps);v(Cs);v(Us);v(zs);v(to);v(ro);v(oo);v(co);v(ko);v(tn);v(rn);v(nn);v({...P,id:"slack_notify"});export{I as INTEGRATIONS,Do as INTEGRATION_REGISTRY,ft as REPORT_SEVERITIES,tk as SKILLS,rn as anthropicBillingSkill,Ns as artifactSkill,dn as browserSkill,Ps as chartRenderSkill,os as chatMemorySkill,hi as chatNotifySkill,Us as chatProgressSkill,to as codeScanSkill,Cs as codeStatsSkill,oo as codebaseMemorySkill,Ii as coreToolsSkill,nn as cursorAdminSkill,bs as datasetStoreSkill,Kn as discordSkill,Lf as fetchAllProviders,Io as fetchAnthropicCosts,xf as fetchAnthropicWorkspaces,No as fetchCursorSpend,vo as fetchOpenAICosts,jf as fetchOpenAIProjects,Tn as figmaSkill,ah as functionSkill,co as gbrainSkill,lk as getAllSkills,ak as getSkill,fe as gitSkill,Hi as gitWriteSkill,$e as githubSkill,Pe as gitlabSkill,oi as googleDocsSkill,$f as groupByKey,ck as hasSkill,Rn as hubspotSkill,mn as jiraSkill,ms as kvMemorySkill,fi as larkDocsSkill,M as larkSkill,jn as linearSkill,ti as linkedinSkill,dk as listSkillIds,Pf as meanStddev,gi as memorySkill,Vn as notionSkill,tn as openaiBillingSkill,qn as opendesignSkill,Un as planeSkill,ok as registerSkill,ht as reportObjectSchema,Gf as reportToBlockKit,Ff as reportToLarkCard,Wf as reportToMarkdown,Yf as reportToNotionBlocks,Di as runnerSkill,Ct as sentrySkill,Ro as skill,bi as skillInstallerSkill,P as slackSkill,zs as socialCardSkill,Di as testRunnerSkill,Cn as vikunjaSkill,ko as workflowBuilderSkill};
1247
+ _${a.sub}_`:""}${a.severity?` ${B[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)e.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{e.push({type:"section",text:{type:"mrkdwn",text:s.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let s=[];t.footer.viewUrl&&s.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:t.footer.viewUrl,style:"primary"}),t.footer.rerunUrl&&s.push({type:"button",text:{type:"plain_text",text:"Run again"},url:t.footer.rerunUrl}),e.push({type:"divider"}),e.push({type:"actions",elements:s})}return e}function py(r){let t=It.parse(r),e=[],n=[`**${t.headline.primary}**`];if(t.headline.delta){let o=mr[t.headline.delta.direction]||"",a=t.headline.delta.severity?B[t.headline.delta.severity]:"";n.push(`${o} ${t.headline.delta.value} ${a}`.trim())}let i=n.join(" ");t.headline.summary&&(i+=`
1248
+ `+t.headline.summary),e.push({tag:"div",text:{tag:"lark_md",content:i}});for(let o of t.sections)switch(e.push({tag:"hr"}),o.title&&e.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let a=Math.max(...o.values),c=o.labels.map((l,d)=>{let p=o.values[d],u=fr(p,a),f=(o.highlight==="last"&&d===o.labels.length-1||o.highlight==="max"&&p===a||o.highlight==="min"&&p===Math.min(...o.values))&&o.severity?` ${B[o.severity]}`:"";return`${Nt(l,10)} ${hr(p.toLocaleString(),8)} ${u}${f}`});e.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1249
+ `)+"\n```"}});break}case"table":{e.push({tag:"div",text:{tag:"lark_md",content:na(o)}});break}case"callouts":{let a=B[o.tone||"info"];e.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
1250
+ `)}});break}case"breakdown":{let a=o.rows.map(c=>{let l=c.severity?` ${B[c.severity]}`:"",d=c.sub?` *${c.sub}*`:"";return`**${c.label}** ${c.value}${d}${l}`});e.push({tag:"div",text:{tag:"lark_md",content:a.join(`
1251
+ `)}});break}case"paragraph":{e.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let o=[];t.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:t.footer.viewUrl,type:"primary"}),t.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:t.footer.rerunUrl,type:"default"}),e.push({tag:"hr"}),e.push({tag:"action",actions:o})}let s="blue";return t.headline.delta?.severity&&(s=ly[t.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:t.title.slice(0,200)},subtitle:t.subtitle?{tag:"plain_text",content:t.subtitle.slice(0,200)}:void 0,template:s},elements:e}}var uy=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),ta=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function Ce(r,t={}){let e={type:"text",text:{content:String(r).slice(0,2e3)}};return t.annotations&&(e.annotations=t.annotations),[e]}function _n(r,t){let e={object:"block",type:"paragraph",paragraph:{rich_text:Ce(r)}};return t&&(e.paragraph.color=t),e}function my(r){return{object:"block",type:"code",code:{rich_text:Ce(r),language:"plain text"}}}function fy(r){let t=It.parse(r),e=[];e.push({object:"block",type:"heading_1",heading_1:{rich_text:Ce(t.title.slice(0,200))}}),t.subtitle&&e.push(_n(t.subtitle,"gray_background"));let n=[{type:"text",text:{content:t.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(t.headline.delta){let s=mr[t.headline.delta.direction]||"",o=t.headline.delta.severity?B[t.headline.delta.severity]:"",a=` ${s} ${t.headline.delta.value} ${o}`.trimEnd();n.push({type:"text",text:{content:a}})}e.push({object:"block",type:"paragraph",paragraph:{rich_text:n}}),t.headline.summary&&e.push(_n(t.headline.summary));for(let s of t.sections)switch(e.push({object:"block",type:"divider",divider:{}}),s.title&&e.push({object:"block",type:"heading_2",heading_2:{rich_text:Ce(s.title)}}),s.kind){case"trend":{let o=Math.max(...s.values),a=Math.min(...s.values),c=s.labels.map((l,d)=>{let p=s.values[d],u=fr(p,o),f=(s.highlight==="last"&&d===s.labels.length-1||s.highlight==="max"&&p===o||s.highlight==="min"&&p===a)&&s.severity?` ${B[s.severity]}`:"";return`${Nt(l,10)} ${hr(p.toLocaleString(),8)} ${u}${f}`});e.push(my(c.join(`
1252
+ `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>Ce(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(l=>Ce(String(l)))}}));e.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=ta[o],c=uy[o];for(let l of s.items)e.push({object:"block",type:"callout",callout:{rich_text:Ce(l),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:` ${B[o.severity]}`}}),e.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{e.push(_n(s.text));break}}t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)&&(e.push({object:"block",type:"divider",divider:{}}),t.footer.viewUrl&&e.push({object:"block",type:"embed",embed:{url:t.footer.viewUrl}}),t.footer.rerunUrl&&e.push({object:"block",type:"embed",embed:{url:t.footer.rerunUrl}}));let i=t.headline.delta?.severity?ta[t.headline.delta.severity]:void 0;return{blocks:e,title:t.title.slice(0,200),icon:i}}function ra(r){return String(r??"").replace(/\|/g,"\\|")}function hy(r){let t=It.parse(r),e=[];e.push(`# ${t.title}`),t.subtitle&&e.push("",t.subtitle);let n=[`**${t.headline.primary}**`];if(t.headline.delta){let i=mr[t.headline.delta.direction]||"",s=t.headline.delta.severity?B[t.headline.delta.severity]:"";n.push(`${i} ${t.headline.delta.value} ${s}`.trim())}e.push("",n.join(" ")),t.headline.summary&&e.push("",t.headline.summary);for(let i of t.sections)switch(e.push("","---",""),i.title&&e.push(`## ${i.title}`,""),i.kind){case"trend":{let s=Math.max(...i.values),o=Math.min(...i.values),a=i.labels.map((c,l)=>{let d=i.values[l],p=fr(d,s),m=(i.highlight==="last"&&l===i.labels.length-1||i.highlight==="max"&&d===s||i.highlight==="min"&&d===o)&&i.severity?` ${B[i.severity]}`:"";return`${Nt(c,10)} ${hr(d.toLocaleString(),8)} ${p}${m}`});e.push("```",...a,"```");break}case"table":{e.push(`| ${i.headers.map(ra).join(" | ")} |`),e.push(`| ${i.headers.map(()=>"---").join(" | ")} |`);for(let s of i.rows)e.push(`| ${s.map(ra).join(" | ")} |`);break}case"callouts":{let s=B[i.tone||"info"];for(let o of i.items)e.push(`- ${s} ${o}`);break}case"breakdown":{for(let s of i.rows){let o=s.sub?` _${s.sub}_`:"",a=s.severity?` ${B[s.severity]}`:"";e.push(`- **${s.label}**: ${s.value}${o}${a}`)}break}case"paragraph":{e.push(i.text);break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let i=[];t.footer.viewUrl&&i.push(`[View in Zibby](${t.footer.viewUrl})`),t.footer.rerunUrl&&i.push(`[Run again](${t.footer.rerunUrl})`),e.push("","---","",i.join(" \xB7 "))}return e.join(`
1253
+ `)}import{createRequire as yy}from"module";import{fileURLToPath as gy}from"url";import{registerHandlers as by}from"@zibby/core/function-skill-registry.js";import{registerSkill as _y}from"@zibby/agent-workflow";var ky=yy(import.meta.url);function wy(){try{return ky.resolve("@zibby/core/function-bridge.js")}catch{return null}}var Sy=import.meta.url;function vy(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let e=new Error().stack;for(let n=2;n<e.length;n++){let i=e[n].getFileName();if(i&&i!==Sy&&!i.startsWith("node:"))return i.startsWith("file://")?gy(i):i}return null}finally{Error.prepareStackTrace=r}}function Iy(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let t={},e=[];for(let[n,i]of Object.entries(r))if(typeof i=="string")t[n]={type:i},e.push(n);else{let{required:s,...o}=i;t[n]=o,s!==!1&&e.push(n)}return{type:"object",properties:t,required:e}}function Ny(r,t,e){if(typeof e.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n={[r]:e.handler},i=[{name:r,description:e.description||"",input_schema:Iy(e.input)}];return by(r,n,i),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:e.description||`Function skill: ${r}`,envKeys:[],tools:i,resolve(){let s=wy();return s?{command:"node",args:[s,t,r]}:null}}}function Oy(r,t){return{id:r,type:"mcp",serverName:t.serverName||r,allowedTools:t.allowedTools||[`mcp__${t.serverName||r}__*`],description:t.description||`MCP skill: ${r}`,envKeys:t.envKeys||[],tools:t.tools||[],resolve:t.resolve,...t.cursorKey&&{cursorKey:t.cursorKey},...t.sessionEnvKey&&{sessionEnvKey:t.sessionEnvKey}}}function ia(r,t){let e;if("handler"in t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n=vy();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);e=Ny(r,n,t)}else if(typeof t.resolve=="function")e=Oy(r,t);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return _y(e),e}var Ty=ia;import{registerSkill as $w,getSkill as Pw,hasSkill as Cw,getAllSkills as Uw,listSkillIds as Bw}from"@zibby/agent-workflow";var v=r=>Ry(vn(r));v(In);v(Tn);v(Je);v(De);v(qn);v(Fn);v(Gn);v(Zn);v(Vn);v(ei);v(P);v(F);v(ni);v(pi);v(hi);v(ki);v(Ri);v(Ai);v(Gt);v(xi);v(ts);v(_e);v(os);v(Li);v(Bi);v(ks);v(Ts);v(Ls);v(Qs);v(po);v(Ds);v(uo);v(mo);v(vo);v(xo);v(jo);v(Co);v(Bo);v(Wo);v(yn);v(gn);v(bn);v({...P,id:"slack_notify"});export{I as INTEGRATIONS,ya as INTEGRATION_REGISTRY,Q as REPORT_CODES,vt as REPORT_SEVERITIES,Rw as SKILLS,gn as anthropicBillingSkill,Qs as artifactSkill,In as browserSkill,po as chartRenderSkill,ks as chatMemorySkill,Ai as chatNotifySkill,mo as chatProgressSkill,ir as checkRenderedReport,xo as codeScanSkill,uo as codeStatsSkill,Co as codebaseMemorySkill,Bi as coreToolsSkill,bn as cursorAdminSkill,Ls as datasetStoreSkill,ni as discordSkill,Qh as fetchAllProviders,Qo as fetchAnthropicCosts,Xh as fetchAnthropicWorkspaces,ea as fetchCursorSpend,Xo as fetchOpenAICosts,Vh as fetchOpenAIProjects,qn as figmaSkill,Ty as functionSkill,Bo as gbrainSkill,Uw as getAllSkills,Pw as getSkill,_e as gitSkill,os as gitWriteSkill,Je as githubSkill,De as gitlabSkill,ki as googleDocsSkill,ey as groupByKey,Cw as hasSkill,Fn as hubspotSkill,Tn as jiraSkill,Ts as kvMemorySkill,Ri as larkDocsSkill,F as larkSkill,Gn as linearSkill,hi as linkedinSkill,Bw as listSkillIds,ty as meanStddev,xi as memorySkill,pi as notionSkill,yn as openaiBillingSkill,ei as opendesignSkill,Vn as planeSkill,$w as registerSkill,Ds as reportCheckSkill,It as reportObjectSchema,dy as reportToBlockKit,py as reportToLarkCard,hy as reportToMarkdown,fy as reportToNotionBlocks,ts as runnerSkill,Gt as sentrySkill,ia as skill,Li as skillInstallerSkill,P as slackSkill,vo as socialCardSkill,ts as testRunnerSkill,Zn as vikunjaSkill,Wo as workflowBuilderSkill};