@zibby/skills 0.1.79 → 0.1.80

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
@@ -3,13 +3,13 @@ If you DO NOT have access to browser tools \u2192 return {"success": false, "ste
3
3
  DO NOT return success: true unless you ACTUALLY called browser tools.`,resolve({sessionPath:r,workspace:e,nodeName:t,headless:n}={}){let i=fs(),s=r&&t?ps(r,t):null,o=s||r||e||"test-results",a=ys({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:_s([i,"--isolated",`--save-video=${hs}`,`--viewport-size=${gs}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as ks}from"module";import{resolveIntegrationToken as ws,clearTokenCache as Ss}from"@zibby/core/backend-client.js";var N=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),bs=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var Is=ks(import.meta.url);function vs(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return Is.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var Ns=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Os(r,e){if(!e||!e.length)return r;let t=r;for(let n of e)n.type==="strong"?t=`**${t}**`:n.type==="em"?t=`_${t}_`:n.type==="code"?t=`\`${t}\``:n.type==="strike"?t=`~~${t}~~`:n.type==="link"&&n.attrs?.href&&(t=`[${t}](${n.attrs.href})`);return t}function tt(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(Os(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
6
+ Override: set MCP_BROWSER_PATH to the path of mcp-browser-zibby.js.`);return{command:"node",args:_s([i,"--isolated",`--save-video=${hs}`,`--viewport-size=${gs}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as ks}from"module";import{resolveIntegrationToken as ws,clearTokenCache as Ss}from"@zibby/core/backend-client.js";var N=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),bs=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var Is=ks(import.meta.url);function vs(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return Is.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var Ns=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Os(r,e){if(!e||!e.length)return r;let t=r;for(let n of e)n.type==="strong"?t=`**${t}**`:n.type==="em"?t=`_${t}_`:n.type==="code"?t=`\`${t}\``:n.type==="strike"?t=`~~${t}~~`:n.type==="link"&&n.attrs?.href&&(t=`[${t}](${n.attrs.href})`);return t}function et(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(Os(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
7
7
  `);continue}if(n.type==="rule"){t.push(`
8
8
  ---
9
- `);continue}let i=n.content?tt(n.content,e+1):"";if(n.type==="listItem")t.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${tt(o.content||[],e+1).trim()}`);t.push(`
9
+ `);continue}let i=n.content?et(n.content,e+1):"";if(n.type==="listItem")t.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${et(o.content||[],e+1).trim()}`);t.push(`
10
10
  ${s.join(`
11
11
  `)}
12
- `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${tt(o.content||[],e+1).trim()}`);t.push(`
12
+ `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${et(o.content||[],e+1).trim()}`);t.push(`
13
13
  ${s.join(`
14
14
  `)}
15
15
  `)}else if(n.type==="heading"){let s=n.attrs?.level||2;t.push(`
@@ -21,7 +21,7 @@ ${"#".repeat(s)} ${i.trim()}
21
21
  ${i}
22
22
  `):t.push(i)}return t.join("").replace(/\n{3,}/g,`
23
23
 
24
- `)}function Ne(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Et(r){return Ne(r).replace(/[a-z0-9]+/g,"")}function rt(r,e){let t=Ne(r),n=Ne(e);if(!t||!n)return 0;if(t===n)return 1;if(t.length===1||n.length===1)return t===n?1:0;let i=l=>{let u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},s=i(t),o=i(n),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,u]of s.entries()){let p=o.get(l)||0;a+=Math.min(u,p)}return 2*a/Math.max(1,c+d)}function ae(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Rs(r,e=[]){let t=Array.isArray(e)?e:[];if(t.length===0)return{requested:r||null,resolved:null,strategy:"none"};let n=t.filter(a=>!a.subtask),i=n.length>0?n:t,s=ae(r);if(s){let a=i.find(l=>ae(l.name)===s);if(a)return{requested:r,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(p=>ae(p)===s))continue;let u=i.find(p=>l.some(m=>ae(m)===ae(p.name)));if(u)return{requested:r,resolved:u,strategy:"alias"}}let d=i.map(l=>({t:l,score:rt(r,l.name)})).sort((l,u)=>u.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:r,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(d=>ae(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 wr(r){let e=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,t=await E(`/rest/api/3/issue/createmeta?${e}`),n=Array.isArray(t?.projects)?t.projects:[],s=n.find(a=>String(a?.key||"").toUpperCase()===String(r||"").toUpperCase())||n[0]||null;return(Array.isArray(s?.issuetypes)?s.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function Sr(r,e){if(!r)throw new Error("projectKey is required");let t="sprint is not EMPTY";e==="active"?t="sprint in openSprints()":e==="closed"?t="sprint in closedSprints()":e==="future"&&(t="sprint in futureSprints()");let n=`project = ${r} AND ${t} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(n)}&maxResults=100&fields=customfield_10020`,s=await E(`/rest/api/3/search/jql?${i}`),o=new Map;for(let a of s.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let d={active:0,future:1,closed:2},l=(d[a.state]??3)-(d[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function Ts(r,{sprintId:e,sprintName:t,target:n}={}){let i=Array.isArray(r)?r:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(e!=null&&String(e).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(e))||null,selectedBy:"id"};if(t&&String(t).trim()){let o=String(t).trim(),a=i.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(d=>({s:d,score:rt(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 As(r,e){let t=r?.fields?.customfield_10020;return Array.isArray(t)?t.some(n=>String(n?.id)===String(e)):!1}async function xs({issueKey:r,projectKey:e,sprintId:t,attempts:n=3,delayMs:i=450}){let s=[];for(let o=0;o<n;o++){try{let a=`project = ${e} AND key = ${r} AND sprint = ${t}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,d=await E(`/rest/api/3/search/jql?${c}`);if(Number(d?.total||0)>0)return s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let u=await E(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),p=As(u,t);if(s.push({attempt:o+1,jql:!1,issueField:p}),p)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<n-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:s}}async function $t({issueKey:r,projectKey:e,sprintId:t,sprintName:n,target:i}){if(!r)return{ok:!1,error:"issueKey is required"};let s=e;if(!s&&(s=(await E(`/rest/api/3/issue/${r}?fields=project`))?.fields?.project?.key||null,!s))return{ok:!1,error:`Could not resolve project for ${r}`};let o=await Sr(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=Ts(o,{sprintId:t,sprintName:n,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:t??null,sprintName:n??null,target:i??"current"},availableSprints:o.map(u=>({id:u.id,name:u.name,state:u.state}))};await E(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await xs({issueKey:r,projectKey:s,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:r,projectKey:s,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:d.method,verified:l,verificationTrace:d.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${r} in sprint ${a.id}`}}async function E(r,e={}){let t=async()=>{let{token:n,cloudId:i}=await ws("jira");if(typeof n!="string"||!n)throw new Error(`Invalid jira token type: ${typeof n}`);if(!i)throw new Error("Invalid jira cloudId: missing");let s=`https://api.atlassian.com/ex/jira/${i}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let a=await o.text().catch(()=>"");if(!a||!a.trim())return{};try{return JSON.parse(a)}catch{return{raw:a}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw n;return Ss("jira"),t()}}var Ir={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:N.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
24
+ `)}function Ne(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function xt(r){return Ne(r).replace(/[a-z0-9]+/g,"")}function tt(r,e){let t=Ne(r),n=Ne(e);if(!t||!n)return 0;if(t===n)return 1;if(t.length===1||n.length===1)return t===n?1:0;let i=l=>{let u=new Map;for(let p=0;p<l.length-1;p++){let m=l.slice(p,p+2);u.set(m,(u.get(m)||0)+1)}return u},s=i(t),o=i(n),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,u]of s.entries()){let p=o.get(l)||0;a+=Math.min(u,p)}return 2*a/Math.max(1,c+d)}function ae(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Rs(r,e=[]){let t=Array.isArray(e)?e:[];if(t.length===0)return{requested:r||null,resolved:null,strategy:"none"};let n=t.filter(a=>!a.subtask),i=n.length>0?n:t,s=ae(r);if(s){let a=i.find(l=>ae(l.name)===s);if(a)return{requested:r,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(p=>ae(p)===s))continue;let u=i.find(p=>l.some(m=>ae(m)===ae(p.name)));if(u)return{requested:r,resolved:u,strategy:"alias"}}let d=i.map(l=>({t:l,score:tt(r,l.name)})).sort((l,u)=>u.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:r,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(d=>ae(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 wr(r){let e=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,t=await E(`/rest/api/3/issue/createmeta?${e}`),n=Array.isArray(t?.projects)?t.projects:[],s=n.find(a=>String(a?.key||"").toUpperCase()===String(r||"").toUpperCase())||n[0]||null;return(Array.isArray(s?.issuetypes)?s.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function Sr(r,e){if(!r)throw new Error("projectKey is required");let t="sprint is not EMPTY";e==="active"?t="sprint in openSprints()":e==="closed"?t="sprint in closedSprints()":e==="future"&&(t="sprint in futureSprints()");let n=`project = ${r} AND ${t} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(n)}&maxResults=100&fields=customfield_10020`,s=await E(`/rest/api/3/search/jql?${i}`),o=new Map;for(let a of s.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let d={active:0,future:1,closed:2},l=(d[a.state]??3)-(d[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function Ts(r,{sprintId:e,sprintName:t,target:n}={}){let i=Array.isArray(r)?r:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(e!=null&&String(e).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(e))||null,selectedBy:"id"};if(t&&String(t).trim()){let o=String(t).trim(),a=i.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(d=>({s:d,score:tt(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 As(r,e){let t=r?.fields?.customfield_10020;return Array.isArray(t)?t.some(n=>String(n?.id)===String(e)):!1}async function xs({issueKey:r,projectKey:e,sprintId:t,attempts:n=3,delayMs:i=450}){let s=[];for(let o=0;o<n;o++){try{let a=`project = ${e} AND key = ${r} AND sprint = ${t}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,d=await E(`/rest/api/3/search/jql?${c}`);if(Number(d?.total||0)>0)return s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let u=await E(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),p=As(u,t);if(s.push({attempt:o+1,jql:!1,issueField:p}),p)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<n-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:s}}async function Et({issueKey:r,projectKey:e,sprintId:t,sprintName:n,target:i}){if(!r)return{ok:!1,error:"issueKey is required"};let s=e;if(!s&&(s=(await E(`/rest/api/3/issue/${r}?fields=project`))?.fields?.project?.key||null,!s))return{ok:!1,error:`Could not resolve project for ${r}`};let o=await Sr(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=Ts(o,{sprintId:t,sprintName:n,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:t??null,sprintName:n??null,target:i??"current"},availableSprints:o.map(u=>({id:u.id,name:u.name,state:u.state}))};await E(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await xs({issueKey:r,projectKey:s,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:r,projectKey:s,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:d.method,verified:l,verificationTrace:d.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${r} in sprint ${a.id}`}}async function E(r,e={}){let t=async()=>{let{token:n,cloudId:i}=await ws("jira");if(typeof n!="string"||!n)throw new Error(`Invalid jira token type: ${typeof n}`);if(!i)throw new Error("Invalid jira cloudId: missing");let s=`https://api.atlassian.com/ex/jira/${i}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let a=await o.text().catch(()=>"");if(!a||!a.trim())return{};try{return JSON.parse(a)}catch{return{raw:a}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw n;return Ss("jira"),t()}}var Ir={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:N.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
25
25
  You have direct access to the user's Jira. Use these tools proactively:
26
26
 
27
27
  ### Issue tools
@@ -71,7 +71,7 @@ When user asks to move/transition ticket status:
71
71
  3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
72
72
  4. Call jira_get_issue(issueKey) to verify final status before claiming success.
73
73
  5. If target wording differs (e.g. \u5DF2\u7ECF\u9A8C\u6536 vs \u5DF2\u9A8C\u6536), try toStatus first; only ask user to confirm when no reasonable match exists.
74
- 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=vs();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return process.env.ATLASSIAN_INSTANCE_URL&&(e.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{command:"node",args:[r],env:e,description:this.description}},async handleToolCall(r,e){try{switch(r){case"jira_list_projects":{let t=await E("/rest/api/3/project"),n=(Array.isArray(t)?t:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await E(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let n=await E("/rest/api/3/status"),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let n=await wr(t);return JSON.stringify({projectKey:t,count:n.length,issueTypes:n})}case"jira_search":{let t=e.jql||"",n=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await E(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let n=await E(`/rest/api/3/issue/${t}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name,labels:n.fields?.labels,created:n.fields?.created,updated:n.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:u,sprintName:p,target:m}=e;if(!t||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await wr(t),f=Rs(i,h)}catch{}let y={project:{key:t},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(y.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(y.priority={name:o}),a?.length&&(y.labels=a),c&&(y.assignee={id:c});let _=await E("/rest/api/3/issue",{method:"POST",body:{fields:y}}),b={ok:!0,key:_.key,id:_.id,self:_.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&ae(f.requested)!==ae(f.resolved.name)&&(b.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(b.availableIssueTypes=h.map(g=>g.name)),(d||l)&&(b.sprintMove=await $t({issueKey:_.key,projectKey:t,sprintId:u,sprintName:p,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,i=await Sr(t,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await $t({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await $t({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:n,projectKey:i,status:s,maxResults:o}=e;if(!t&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${t}"`,d=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",u=`${d}${c}${l} ORDER BY status ASC, priority DESC`,p=`jql=${encodeURIComponent(u)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await E(`/rest/api/3/search/jql?${p}`),f=(m.issues||[]).map(y=>({key:y.key,project:y.fields?.project?.key,summary:y.fields?.summary,status:y.fields?.status?.name,assignee:y.fields?.assignee?.displayName||"Unassigned",priority:y.fields?.priority?.name,type:y.fields?.issuetype?.name})),h={};for(let y of f)h[y.status]=(h[y.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:t,maxResults:n}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await E(`/rest/api/3/issue/${t}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=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:t,body:n}=e;return!t||!n?JSON.stringify({error:"issueKey and body are required"}):(await E(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:n}=e;return!t||!n?JSON.stringify({error:"issueKey and fields are required"}):(await E(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:n,toStatus:i,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let u=((await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(p=>({id:p.id,name:p.name,to:p.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:u})}let c=n;if(!c){let u=(await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[],p=Ne(a),m=u.find(f=>Ne(f?.name||"")===p||Ne(f?.to?.name||"")===p);if(!m){let f=Et(a);f.length>=2&&(m=u.find(h=>{let y=Et(h?.name||""),_=Et(h?.to?.name||""),b=y.length>=2&&(y.includes(f)||f.includes(y)),g=_.length>=2&&(_.includes(f)||f.includes(_));return b||g}))}if(!m){let f=u.map(b=>{let g=rt(a,b?.name||""),w=rt(a,b?.to?.name||"");return{t:b,score:Math.max(g,w)}}).sort((b,g)=>g.score-b.score),h=f[0],y=f[1];h&&h.score>=.45&&(!y||h.score-y.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:u.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await E(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await E(`/rest/api/3/issue/${t}?fields=status`);return JSON.stringify({ok:!0,issueKey:t,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as Es}from"fs";import{fileURLToPath as $s}from"url";import{dirname as Ls,resolve as js}from"path";import{resolveIntegrationToken as vr}from"@zibby/core/backend-client.js";function Ps(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ls($s(import.meta.url)),e=js(r,"..","bin","mcp-skill.mjs");return Es(e)?e:null}async function v(r,e={}){let{token:t}=await vr("github"),n=r.startsWith("https://")?r:`https://api.github.com${r}`,i={Authorization:`Bearer ${t}`,Accept:e.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`)}return e.raw?s.text():s.json()}var Oe={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:N.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
74
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=vs();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return process.env.ATLASSIAN_INSTANCE_URL&&(e.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{command:"node",args:[r],env:e,description:this.description}},async handleToolCall(r,e){try{switch(r){case"jira_list_projects":{let t=await E("/rest/api/3/project"),n=(Array.isArray(t)?t:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await E(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let n=await E("/rest/api/3/status"),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let n=await wr(t);return JSON.stringify({projectKey:t,count:n.length,issueTypes:n})}case"jira_search":{let t=e.jql||"",n=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await E(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let n=await E(`/rest/api/3/issue/${t}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name,labels:n.fields?.labels,created:n.fields?.created,updated:n.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:u,sprintName:p,target:m}=e;if(!t||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await wr(t),f=Rs(i,h)}catch{}let y={project:{key:t},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(y.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(y.priority={name:o}),a?.length&&(y.labels=a),c&&(y.assignee={id:c});let _=await E("/rest/api/3/issue",{method:"POST",body:{fields:y}}),b={ok:!0,key:_.key,id:_.id,self:_.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&ae(f.requested)!==ae(f.resolved.name)&&(b.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(b.availableIssueTypes=h.map(g=>g.name)),(d||l)&&(b.sprintMove=await Et({issueKey:_.key,projectKey:t,sprintId:u,sprintName:p,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,i=await Sr(t,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await Et({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await Et({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:n,projectKey:i,status:s,maxResults:o}=e;if(!t&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${t}"`,d=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",u=`${d}${c}${l} ORDER BY status ASC, priority DESC`,p=`jql=${encodeURIComponent(u)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await E(`/rest/api/3/search/jql?${p}`),f=(m.issues||[]).map(y=>({key:y.key,project:y.fields?.project?.key,summary:y.fields?.summary,status:y.fields?.status?.name,assignee:y.fields?.assignee?.displayName||"Unassigned",priority:y.fields?.priority?.name,type:y.fields?.issuetype?.name})),h={};for(let y of f)h[y.status]=(h[y.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:t,maxResults:n}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await E(`/rest/api/3/issue/${t}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=et(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:n}=e;return!t||!n?JSON.stringify({error:"issueKey and body are required"}):(await E(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:n}=e;return!t||!n?JSON.stringify({error:"issueKey and fields are required"}):(await E(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:n,toStatus:i,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let u=((await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(p=>({id:p.id,name:p.name,to:p.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:u})}let c=n;if(!c){let u=(await E(`/rest/api/3/issue/${t}/transitions`)).transitions||[],p=Ne(a),m=u.find(f=>Ne(f?.name||"")===p||Ne(f?.to?.name||"")===p);if(!m){let f=xt(a);f.length>=2&&(m=u.find(h=>{let y=xt(h?.name||""),_=xt(h?.to?.name||""),b=y.length>=2&&(y.includes(f)||f.includes(y)),g=_.length>=2&&(_.includes(f)||f.includes(_));return b||g}))}if(!m){let f=u.map(b=>{let g=tt(a,b?.name||""),w=tt(a,b?.to?.name||"");return{t:b,score:Math.max(g,w)}}).sort((b,g)=>g.score-b.score),h=f[0],y=f[1];h&&h.score>=.45&&(!y||h.score-y.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:u.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await E(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await E(`/rest/api/3/issue/${t}?fields=status`);return JSON.stringify({ok:!0,issueKey:t,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as Es}from"fs";import{fileURLToPath as $s}from"url";import{dirname as Ls,resolve as js}from"path";import{resolveIntegrationToken as vr}from"@zibby/core/backend-client.js";function Ps(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ls($s(import.meta.url)),e=js(r,"..","bin","mcp-skill.mjs");return Es(e)?e:null}async function v(r,e={}){let{token:t}=await vr("github"),n=r.startsWith("https://")?r:`https://api.github.com${r}`,i={Authorization:`Bearer ${t}`,Accept:e.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`)}return e.raw?s.text():s.json()}var Oe={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:N.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
75
75
  You have access to the user's GitHub repositories. Available tools:
76
76
 
77
77
  ### Discovery
@@ -317,16 +317,16 @@ You can send messages and replies on Lark. Use:
317
317
  - lark_get_chat_history: fetch recent messages in a chat
318
318
  - lark_lookup_user_by_email: resolve an email \u2192 open_id for direct DM (prefer this over emailing through lark_send_message when the agent has a user_id already)
319
319
  When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=vo();if(!r)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},tools:[{name:"lark_send_message",description:"Send a text message to a Lark chat, user, or DM. receive_id can be a chat_id (oc_*), open_id (ou_*), union_id (on_*), or email.",input_schema:{type:"object",properties:{receive_id:{type:"string",description:"Target id: chat_id (oc_*), open_id (ou_*), union_id (on_*), or email"},text:{type:"string",description:"Message text"}},required:["receive_id","text"]}},{name:"lark_reply",description:"Reply to an existing Lark message (creates a thread). Use the message_id from the inbound event.",input_schema:{type:"object",properties:{message_id:{type:"string",description:"Lark message id (om_*) to reply to"},text:{type:"string",description:"Reply text"}},required:["message_id","text"]}},{name:"lark_list_chats",description:"List chats (groups + DMs) the bot is a member of.",input_schema:{type:"object",properties:{page_size:{type:"number",description:"Max results (default 50)"}}}},{name:"lark_get_chat_history",description:"Fetch recent messages in a chat.",input_schema:{type:"object",properties:{chat_id:{type:"string",description:"Chat id (oc_*)"},page_size:{type:"number",description:"Max messages (default 20)"}},required:["chat_id"]}},{name:"lark_lookup_user_by_email",description:"Resolve an email address to a Lark user id (open_id). Returns { ok:true, user:{open_id,email,name} } on hit, { ok:false } if no Lark user has that email. Use the open_id as `receive_id` in lark_send_message to DM.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"lark_search_users",description:'Fuzzy-search users by name across chats the bot is a member of. Lark has no public org-wide user search API for bots \u2014 this walks the bot\'s chat memberships and matches names client-side. Best for "send to Sam" style routing where you have a name but no email. Returns up to `limit` ranked matches { open_id, name }.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against user names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}],async handleToolCall(r,e){try{switch(r){case"lark_send_message":{if(!e.receive_id||!e.text)return JSON.stringify({error:"receive_id and text are required"});let t=Ro(e.receive_id),n=await me("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:Lr(e.text)});return JSON.stringify({ok:!0,message_id:n.message_id})}case"lark_reply":{if(!e.message_id||!e.text)return JSON.stringify({error:"message_id and text are required"});let t=await me("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:Lr(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,i=((await me("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(s=>({chat_id:s.chat_id,name:s.name,description:s.description,owner_id:s.owner_id,chat_mode:s.chat_mode}));return JSON.stringify({chats:i})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,i=((await me("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(s=>({message_id:s.message_id,sender_id:s.sender?.id,sender_type:s.sender?.sender_type,msg_type:s.msg_type,content:s.body?.content,create_time:s.create_time}));return JSON.stringify({messages:i})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let n=((await me("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(i=>i.email===e.email&&i.user_id);return JSON.stringify(n?{ok:!0,user:{open_id:n.user_id,email:n.email,name:n.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),i=200,o=((await me("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(l=>l.chat_id),a=new Set,c=[];for(let l of o){if(c.length>=i)break;try{let u=await me("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let p of u.items||[])if(!(!p.member_id||a.has(p.member_id))&&(a.add(p.member_id),c.push({open_id:p.member_id,name:p.name||""}),c.length>=i))break}catch(u){console.warn(`[lark] member scan failed for ${l}: ${u.message}`)}}let d=[];for(let l of c){let u=(l.name||"").toLowerCase();if(!u)continue;let p=0;u.includes(t)&&(p+=100-Math.abs(u.length-t.length)),u===t&&(p+=200),p>0&&d.push({open_id:l.open_id,name:l.name,_score:p})}return d.sort((l,u)=>u._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,n).map(({_score:l,...u})=>u),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}}};import{existsSync as To}from"fs";import{fileURLToPath as Ao}from"url";import{dirname as xo,resolve as Eo}from"path";import{resolveIntegrationToken as $o}from"@zibby/core/backend-client.js";function Lo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=xo(Ao(import.meta.url)),e=Eo(r,"..","bin","mcp-skill.mjs");return To(e)?e:null}var jo=process.env.DISCORD_API_URL||"https://discord.com/api/v10",Po=2e3;function Co(r,e=Po){let t=String(r??"");if(!t.trim())return[];if(t.length<=e)return[t];let n=[],i=t;for(;i.length>e;){let o=i.slice(0,e).lastIndexOf(`
320
- `),a=o>e/2?o+1:e;n.push(i.slice(0,a)),i=i.slice(a)}return i&&n.push(i),n}async function jr(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await $o(N.DISCORD),t=(e&&e.token?String(e.token):"").trim();if(!t)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:t,guildId:(e.guildId||"").trim()}}async function Lt(r,e,{token:t,body:n}={}){let i=t.startsWith("Bot ")?t:`Bot ${t}`,s=await fetch(`${jo}${e}`,{method:r,headers:{Authorization:i,...n!==void 0?{"Content-Type":"application/json"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),o=await s.json().catch(()=>null);if(!s.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${s.status}`;throw new Error(`Discord API error (${s.status}): ${a}`)}return o}async function Uo({token:r,guildId:e},t){let n=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(n)return n;let i=await Lt("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 Pr={id:"discord",serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:N.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord (connected)
320
+ `),a=o>e/2?o+1:e;n.push(i.slice(0,a)),i=i.slice(a)}return i&&n.push(i),n}async function jr(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await $o(N.DISCORD),t=(e&&e.token?String(e.token):"").trim();if(!t)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:t,guildId:(e.guildId||"").trim()}}async function $t(r,e,{token:t,body:n}={}){let i=t.startsWith("Bot ")?t:`Bot ${t}`,s=await fetch(`${jo}${e}`,{method:r,headers:{Authorization:i,...n!==void 0?{"Content-Type":"application/json"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),o=await s.json().catch(()=>null);if(!s.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${s.status}`;throw new Error(`Discord API error (${s.status}): ${a}`)}return o}async function Uo({token:r,guildId:e},t){let n=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(n)return n;let i=await $t("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 Pr={id:"discord",serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:N.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord (connected)
321
321
  You can post to the user's Discord server as their bot. Tools:
322
322
  - discord_send_message(channelId, text) \u2014 post a message to a channel (long text is auto-chunked to Discord's 2000-char limit)
323
- - discord_list_channels(guildId?) \u2014 list the server's text channels (id + name) to find where to post; guildId is optional when the bot is in one server`,resolve(){let r={};for(let t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_SELF_HOST","DISCORD_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[t]&&(r[t]=process.env[t]);let e=Lo();return e?{type:"stdio",command:"node",args:[e,"../dist/discord.js","discordSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,e={}){try{switch(r){case"discord_send_message":{let t=String(e.channelId||"").trim(),n=String(e.text||"");if(!t||!n.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let i=await jr(),s=Co(n),o=[];for(let a of s){let c=await Lt("POST",`/channels/${encodeURIComponent(t)}/messages`,{token:i.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:t,messageIds:o,chunks:s.length})}case"discord_list_channels":{let t=await jr(),n=await Uo(t,e.guildId),i=await Lt("GET",`/guilds/${encodeURIComponent(n)}/channels`,{token:t.token}),s=(Array.isArray(i)?i:[]).filter(o=>o&&(o.type===0||o.type===5)).map(o=>({id:o.id,name:o.name,type:o.type===5?"announcement":"text",...o.topic?{topic:o.topic}:{}}));return JSON.stringify({ok:!0,guildId:n,channels:s})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"discord_send_message",description:"Post a message to a Discord channel as the connected bot. Text over 2000 chars is automatically split into sequential messages.",input_schema:{type:"object",properties:{channelId:{type:"string",description:"Discord channel id (snowflake). Use discord_list_channels to find it."},text:{type:"string",description:"Message text (Discord markdown supported)"}},required:["channelId","text"]}},{name:"discord_list_channels",description:"List the text channels of the connected Discord server (id + name). Pass guildId only when the bot is in multiple servers.",input_schema:{type:"object",properties:{guildId:{type:"string",description:"Discord server (guild) id \u2014 optional when the bot is in exactly one server or one was captured at connect time"}}}}]};import{existsSync as Br,statSync as Do,readFileSync as qo}from"fs";import{fileURLToPath as Jo}from"url";import{basename as Bo,dirname as Mo,resolve as Fo}from"path";import{resolveIntegrationToken as Go,clearTokenCache as Ko}from"@zibby/core/backend-client.js";function Ho(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Mo(Jo(import.meta.url)),e=Fo(r,"..","bin","mcp-skill.mjs");return Br(e)?e:null}var zo="2022-06-28",Wo="https://api.notion.com/v1",nt=2e4,Cr=25,Yo=25,it=100,Ur=500,Zo=20*1024*1024;function ne(r){if(!r||typeof r!="string")return null;let t=r.trim().split(/[?#]/)[0],n=t.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);if(n)return n[0].toLowerCase();let i=t.match(/[0-9a-fA-F]{32}/g);if(i&&i.length){let s=i[i.length-1].toLowerCase();return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}return null}async function Y(r,e={}){let t=async()=>{let{token:n}=await Go("notion");if(typeof n!="string"||!n)throw new Error(`Invalid notion token type: ${typeof n}`);let i=await fetch(`${Wo}${r}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"Notion-Version":zo,Accept:"application/json",...e.body&&!e.formData?{"Content-Type":"application/json"}:{},...e.headers},body:e.formData?e.formData:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Notion API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Ko("notion"),t()}}function Te(r){if(!Array.isArray(r))return"";let e="";for(let t of r){let n=t?.plain_text??t?.text?.content??"";if(!n)continue;let i=t.annotations||{};i.code&&(n=`\`${n}\``),i.bold&&(n=`**${n}**`),i.italic&&(n=`_${n}_`),i.strikethrough&&(n=`~~${n}~~`);let s=t?.href||t?.text?.link?.url;s&&(n=`[${n}](${s})`),e+=n}return e}function Vo(r,e,t){let n=r?.type,i=r?.[n]||{},s=" ".repeat(Math.max(0,e)),o=(d="rich_text")=>Te(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||""}
323
+ - discord_list_channels(guildId?) \u2014 list the server's text channels (id + name) to find where to post; guildId is optional when the bot is in one server`,resolve(){let r={};for(let t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_SELF_HOST","DISCORD_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[t]&&(r[t]=process.env[t]);let e=Lo();return e?{type:"stdio",command:"node",args:[e,"../dist/discord.js","discordSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,e={}){try{switch(r){case"discord_send_message":{let t=String(e.channelId||"").trim(),n=String(e.text||"");if(!t||!n.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let i=await jr(),s=Co(n),o=[];for(let a of s){let c=await $t("POST",`/channels/${encodeURIComponent(t)}/messages`,{token:i.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:t,messageIds:o,chunks:s.length})}case"discord_list_channels":{let t=await jr(),n=await Uo(t,e.guildId),i=await $t("GET",`/guilds/${encodeURIComponent(n)}/channels`,{token:t.token}),s=(Array.isArray(i)?i:[]).filter(o=>o&&(o.type===0||o.type===5)).map(o=>({id:o.id,name:o.name,type:o.type===5?"announcement":"text",...o.topic?{topic:o.topic}:{}}));return JSON.stringify({ok:!0,guildId:n,channels:s})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"discord_send_message",description:"Post a message to a Discord channel as the connected bot. Text over 2000 chars is automatically split into sequential messages.",input_schema:{type:"object",properties:{channelId:{type:"string",description:"Discord channel id (snowflake). Use discord_list_channels to find it."},text:{type:"string",description:"Message text (Discord markdown supported)"}},required:["channelId","text"]}},{name:"discord_list_channels",description:"List the text channels of the connected Discord server (id + name). Pass guildId only when the bot is in multiple servers.",input_schema:{type:"object",properties:{guildId:{type:"string",description:"Discord server (guild) id \u2014 optional when the bot is in exactly one server or one was captured at connect time"}}}}]};import{existsSync as Br,statSync as Do,readFileSync as qo}from"fs";import{fileURLToPath as Jo}from"url";import{basename as Bo,dirname as Mo,resolve as Fo}from"path";import{resolveIntegrationToken as Go,clearTokenCache as Ko}from"@zibby/core/backend-client.js";function Ho(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Mo(Jo(import.meta.url)),e=Fo(r,"..","bin","mcp-skill.mjs");return Br(e)?e:null}var zo="2022-06-28",Wo="https://api.notion.com/v1",rt=2e4,Cr=25,Yo=25,nt=100,Ur=500,Zo=20*1024*1024;function ne(r){if(!r||typeof r!="string")return null;let t=r.trim().split(/[?#]/)[0],n=t.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);if(n)return n[0].toLowerCase();let i=t.match(/[0-9a-fA-F]{32}/g);if(i&&i.length){let s=i[i.length-1].toLowerCase();return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}return null}async function Y(r,e={}){let t=async()=>{let{token:n}=await Go("notion");if(typeof n!="string"||!n)throw new Error(`Invalid notion token type: ${typeof n}`);let i=await fetch(`${Wo}${r}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"Notion-Version":zo,Accept:"application/json",...e.body&&!e.formData?{"Content-Type":"application/json"}:{},...e.headers},body:e.formData?e.formData:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Notion API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Ko("notion"),t()}}function Te(r){if(!Array.isArray(r))return"";let e="";for(let t of r){let n=t?.plain_text??t?.text?.content??"";if(!n)continue;let i=t.annotations||{};i.code&&(n=`\`${n}\``),i.bold&&(n=`**${n}**`),i.italic&&(n=`_${n}_`),i.strikethrough&&(n=`~~${n}~~`);let s=t?.href||t?.text?.link?.url;s&&(n=`[${n}](${s})`),e+=n}return e}function Vo(r,e,t){let n=r?.type,i=r?.[n]||{},s=" ".repeat(Math.max(0,e)),o=(d="rich_text")=>Te(i[d]),a;switch(n){case"paragraph":a=o();break;case"heading_1":a=`# ${o()}`;break;case"heading_2":a=`## ${o()}`;break;case"heading_3":a=`### ${o()}`;break;case"bulleted_list_item":a=`${s}- ${o()}`;break;case"numbered_list_item":a=`${s}1. ${o()}`;break;case"to_do":a=`${s}- [${i.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${s}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${i.icon?.emoji?`${i.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${i.language||""}
324
324
  ${o()}
325
325
  \`\`\``;break}case"divider":a="---";break;case"child_page":a=`[child page: ${i.title||""}]`;break;case"child_database":a=`[child database: ${i.title||""}]`;break;case"bookmark":case"embed":case"link_preview":a=i.url?`<${i.url}>`:"";break;case"equation":a=i.expression?`$${i.expression}$`:"";break;case"table":case"column_list":case"column":a="";break;case"table_row":{let d=(i.cells||[]).map(l=>Te(l).trim());a=`${s}| ${d.join(" | ")} |`;break}default:a=o();break}let c=[];return a&&a.trim()&&c.push(a),t&&t.trim()&&c.push(t),c.join(`
326
- `)}async function Mr(r,e,t){let n=[],i,s=0;do{if(t.used>=nt)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let a=await Y(`/blocks/${r}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await Mr(d.id,e+1,t));let u=Vo(d,e,l);if(u&&(n.push(u),t.used+=u.length+1),t.used>=nt)break}i=a.has_more?a.next_cursor:void 0,s+=1}while(i&&s<Yo);return n.join(`
327
- `)}function Dr(r){let e=r?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let n=Te(t.title).trim();if(n)return n}return""}function Be(r){let e=String(r??"");if(!e)return[{type:"text",text:{content:""}}];let t=[];for(let n=0;n<e.length;n+=2e3)t.push({type:"text",text:{content:e.slice(n,n+2e3)}});return t}function Qo(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:Te(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function Xo(r){if(!r||!r.type)return"";switch(r.type){case"title":return Te(r.title).trim();case"rich_text":return Te(r.rich_text).trim();case"number":return r.number==null?"":String(r.number);case"select":return r.select?.name||"";case"status":return r.status?.name||"";case"multi_select":return(r.multi_select||[]).map(t=>t.name).join(", ");case"checkbox":return r.checkbox?"true":"false";case"url":return r.url||"";case"email":return r.email||"";case"phone_number":return r.phone_number||"";case"date":return r.date?.start||"";case"people":return(r.people||[]).map(t=>t.name||t.id).join(", ");default:return""}}function jt(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function ea(r){let e=String(r??"").replace(/\r\n/g,`
326
+ `)}async function Mr(r,e,t){let n=[],i,s=0;do{if(t.used>=rt)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let a=await Y(`/blocks/${r}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await Mr(d.id,e+1,t));let u=Vo(d,e,l);if(u&&(n.push(u),t.used+=u.length+1),t.used>=rt)break}i=a.has_more?a.next_cursor:void 0,s+=1}while(i&&s<Yo);return n.join(`
327
+ `)}function Dr(r){let e=r?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let n=Te(t.title).trim();if(n)return n}return""}function Be(r){let e=String(r??"");if(!e)return[{type:"text",text:{content:""}}];let t=[];for(let n=0;n<e.length;n+=2e3)t.push({type:"text",text:{content:e.slice(n,n+2e3)}});return t}function Qo(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:Te(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function Xo(r){if(!r||!r.type)return"";switch(r.type){case"title":return Te(r.title).trim();case"rich_text":return Te(r.rich_text).trim();case"number":return r.number==null?"":String(r.number);case"select":return r.select?.name||"";case"status":return r.status?.name||"";case"multi_select":return(r.multi_select||[]).map(t=>t.name).join(", ");case"checkbox":return r.checkbox?"true":"false";case"url":return r.url||"";case"email":return r.email||"";case"phone_number":return r.phone_number||"";case"date":return r.date?.start||"";case"people":return(r.people||[]).map(t=>t.name||t.id).join(", ");default:return""}}function Lt(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function ea(r){let e=String(r??"").replace(/\r\n/g,`
328
328
  `),t=[];for(let n of e.split(`
329
- `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d;s?(c=`heading_${s[1].length}`,d=s[2]):o?(c="bulleted_list_item",d=o[1]):a?(c="numbered_list_item",d=a[1]):(c="paragraph",d=i),t.push({object:"block",type:c,[c]:{rich_text:Be(d)}})}return t}function qr(r){return Array.isArray(r?.blocks)&&r.blocks.length?r.blocks.slice(0,Ur):typeof r?.markdown=="string"&&r.markdown.trim()?ea(r.markdown).slice(0,Ur):null}async function Jr(r,e){for(let t=0;t<e.length;t+=it)await Y(`/blocks/${r}/children`,{method:"PATCH",body:{children:e.slice(t,t+it)}})}function ta(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Br(e)||!Do(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=qo(e);if(t.length>Zo)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return t}async function ra(r){let e=ta(r),t=Bo(r.trim()),n=/\.png$/i.test(t)?"image/png":"image/jpeg",s=(await Y("/file_uploads",{method:"POST",body:{mode:"single_part",filename:t}}))?.id;if(!s)throw new Error("Notion file upload create returned no id");let o=new FormData;return o.set("file",new Blob([e],{type:n}),t),await Y(`/file_uploads/${s}/send`,{method:"POST",formData:o}),s}var Fr={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:N.NOTION,description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion (connected)
329
+ `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d;s?(c=`heading_${s[1].length}`,d=s[2]):o?(c="bulleted_list_item",d=o[1]):a?(c="numbered_list_item",d=a[1]):(c="paragraph",d=i),t.push({object:"block",type:c,[c]:{rich_text:Be(d)}})}return t}function qr(r){return Array.isArray(r?.blocks)&&r.blocks.length?r.blocks.slice(0,Ur):typeof r?.markdown=="string"&&r.markdown.trim()?ea(r.markdown).slice(0,Ur):null}async function Jr(r,e){for(let t=0;t<e.length;t+=nt)await Y(`/blocks/${r}/children`,{method:"PATCH",body:{children:e.slice(t,t+nt)}})}function ta(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Br(e)||!Do(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=qo(e);if(t.length>Zo)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return t}async function ra(r){let e=ta(r),t=Bo(r.trim()),n=/\.png$/i.test(t)?"image/png":"image/jpeg",s=(await Y("/file_uploads",{method:"POST",body:{mode:"single_part",filename:t}}))?.id;if(!s)throw new Error("Notion file upload create returned no id");let o=new FormData;return o.set("file",new Blob([e],{type:n}),t),await Y(`/file_uploads/${s}/send`,{method:"POST",formData:o}),s}var Fr={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:N.NOTION,description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion (connected)
330
330
  You can read Notion content as context AND write to Notion (create pages, append blocks, insert images).
331
331
  - notion_get_page: pass a Notion page id OR a full Notion URL; returns { id, title, url, text } where text is the page flattened to markdown (truncated to ~20k chars). Use the text as reference context.
332
332
  - notion_query_database: pass a database id/URL; returns a small list of rows ({ id, title, url, props }). Use to find a specific page, then notion_get_page it.
@@ -335,7 +335,7 @@ You can read Notion content as context AND write to Notion (create pages, append
335
335
  - notion_insert_image: append an image block to a page. Pass { pageId, imagePath } for a LOCAL png/jpg file (\u226420MB, uploaded via Notion's File Upload API) or { pageId, imageUrl } for an external, publicly reachable image URL. Optional caption. Returns { ok, pageId, url }.
336
336
  - notion_list_comments: pass a page/block id OR URL; returns the open comment discussions on it ({ id, discussionId, text, author }). Use to read the comment thread you are replying to.
337
337
  - notion_add_comment: post a comment. To REPLY in an existing discussion pass { discussionId, text }; to start a NEW top-level comment on a page pass { pageId, text }. Returns { ok, id, discussionId }. Use this to answer a user who @mentioned Zibby in a Notion comment \u2014 reply in the SAME discussionId.
338
- Do not block the task if Notion is unavailable \u2014 these tools return { ok:false, error } on failure; treat a missing page as "no extra context" / "cannot deliver to Notion" and continue.`,resolve(){let r=Ho();return r?{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,n=ne(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await Y(`/pages/${n}`),s=Dr(i),o=i?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,c=await Mr(n,0,{used:0}),d=!1;return c.length>nt&&(c=c.slice(0,nt),d=!0),JSON.stringify({ok:!0,id:n,title:s,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,n=ne(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let s={page_size:Math.max(1,Math.min(Number(e?.maxResults)||Cr,Cr))};e?.filter&&typeof e.filter=="object"&&(s.filter=e.filter);let o=await Y(`/databases/${n}/query`,{method:"POST",body:s}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[u,p]of Object.entries(d.properties||{})){let m=Xo(p);m&&(l[u]=m)}return{id:d.id,title:Dr(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:n,count:c.length,hasMore:!!o.has_more,rows:c})}case"notion_create_page":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let n=e?.databaseId?ne(e.databaseId):null,i=e?.parentPageId?ne(e.parentPageId):ne(e?.parent||e?.pageId);if(!n&&!i)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let s=n?{database_id:n}:{page_id:i},o={title:{title:Be(t)}},a=qr(e)||[],c=a.slice(0,it),d=await Y("/pages",{method:"POST",body:{parent:s,properties:o,...c.length?{children:c}:{}}}),l=d?.id;if(!l)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let u=a.slice(it);return u.length&&await Jr(l,u),JSON.stringify({ok:!0,pageId:l,url:d?.url||jt(l)})}case"notion_append_blocks":{let t=ne(e?.pageId||e?.blockId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=qr(e);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await Jr(t,n),JSON.stringify({ok:!0,pageId:t,url:jt(t)}))}case"notion_insert_image":{let t=ne(e?.pageId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=typeof e?.caption=="string"&&e.caption.trim()?Be(e.caption.trim()):null,i,s;if(typeof e?.imagePath=="string"&&e.imagePath.trim())s=await ra(e.imagePath),i={type:"file_upload",file_upload:{id:s}};else if(typeof e?.imageUrl=="string"&&e.imageUrl.trim())i={type:"external",external:{url:e.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return n&&(i.caption=n),await Y(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:i}]}}),JSON.stringify({ok:!0,pageId:t,url:jt(t),...s?{fileUploadId:s}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,n=ne(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let i=new URLSearchParams({block_id:n,page_size:"100"}),s=await Y(`/comments?${i.toString()}`),a=(Array.isArray(s.results)?s.results:[]).map(Qo);return JSON.stringify({ok:!0,id:n,count:a.length,comments:a})}case"notion_add_comment":{let t=typeof e?.text=="string"?e.text:typeof e?.body=="string"?e.body:"";if(!t||!t.trim())return JSON.stringify({ok:!1,error:"text is required"});let n=e?.discussionId||e?.discussion_id||null,i;if(n)i={discussion_id:String(n),rich_text:Be(t)};else{let o=e?.pageId||e?.page||e?.url||e?.id,a=ne(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:Be(t)}}let s=await Y("/comments",{method:"POST",body:i});return JSON.stringify({ok:!0,id:s?.id||"",discussionId:s?.discussion_id||n||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}},{name:"notion_create_page",description:"Create a new Notion page under a parent page (parentPageId) OR in a database (databaseId) \u2014 exactly one parent is required. Body from markdown (#/##/### headings, - bullets, 1. ordered lists; inline marks kept as literal text) or raw Notion block objects. Long bodies are chunked automatically (Notion caps 100 blocks/request). Returns { ok, pageId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{parentPageId:{type:"string",description:"Parent PAGE id/URL to create the page under (used when databaseId is absent)."},databaseId:{type:"string",description:"Parent DATABASE id/URL to create the page in (title goes into the title property)."},title:{type:"string",description:"Page title."},markdown:{type:"string",description:"Page body as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["title"]}},{name:"notion_append_blocks",description:"Append markdown (or raw Notion blocks) to the END of an existing Notion page. Accepts a page id or full Notion URL. Chunks automatically at Notion's 100-blocks-per-request cap. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["pageId"]}},{name:"notion_insert_image",description:"Append an image block to a Notion page. Pass imagePath for a LOCAL .png/.jpg file (max 20MB \u2014 uploaded via Notion's File Upload API, stored by Notion) or imageUrl for an external publicly-reachable image URL. Optional caption. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 20MB). Preferred for locally rendered charts."},imageUrl:{type:"string",description:"External image URL (must be publicly reachable; used when imagePath is absent)."},caption:{type:"string",description:"Optional image caption."}},required:["pageId"]}},{name:"notion_list_comments",description:"List the open comment discussions on a Notion page/block. Accepts a page/block id OR a full Notion URL. Returns { ok, comments:[{ id, discussionId, text, author }] }. Use to read the comment thread you are replying to.",input_schema:{type:"object",properties:{blockId:{type:"string",description:"Notion page or block id (dashed UUID or 32-char) OR a full Notion URL."}},required:["blockId"]}},{name:"notion_add_comment",description:"Post a comment on Notion. To REPLY within an existing discussion, pass { discussionId, text }. To start a NEW top-level comment on a page, pass { pageId, text }. Returns { ok, id, discussionId }. Use this to answer a user who @mentioned Zibby in a Notion comment (reply in the same discussionId).",input_schema:{type:"object",properties:{discussionId:{type:"string",description:"The discussion_id to reply into (from notion_list_comments). Preferred for replies."},pageId:{type:"string",description:"Page id/URL to start a NEW top-level comment on (used when discussionId is absent)."},text:{type:"string",description:"The comment body (plain text)."}},required:["text"]}}]};import{existsSync as na,readFileSync as ia}from"fs";import{fileURLToPath as sa}from"url";import{dirname as oa,resolve as aa}from"path";import{resolveIntegrationToken as Pt,clearTokenCache as ca}from"@zibby/core/backend-client.js";function la(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=oa(sa(import.meta.url)),e=aa(r,"..","bin","mcp-skill.mjs");return na(e)?e:null}function da(){let r=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!r)return null;let e=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:r,memberId:e}}function ua(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function pa(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var ma="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 Ct(){let r=da();if(r)return r;if(ua()||pa())throw new Error(ma);return null}var fa="202506",ha="https://api.linkedin.com";function Gr(r){if(r==null)return null;let e=String(r).trim();if(!e)return null;let t=e.match(/urn:li:organization:(\d+)/i);return t?t[1]:/^\d+$/.test(e)?e:null}function Kr(r){if(!r)return"";if(r.localizedName)return String(r.localizedName);let e=r.name&&r.name.localized;if(e&&typeof e=="object"){let t=Object.values(e)[0];if(t)return String(t)}return""}function st(r,e){return r?typeof r.get=="function"?r.get(e):r[e]||r[e.toLowerCase()]||null:null}async function fe(r,e={},t="linkedin_business"){let n=async()=>{let i;if(t==="linkedin_personal"){let d=Ct();d&&(i=d.token)}if(i||({token:i}=await Pt(t)),typeof i!="string"||!i)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let s=r.startsWith("https://")?r:`${ha}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,"LinkedIn-Version":fa,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${d.slice(0,300)}`)}let a=await o.text().catch(()=>""),c={};if(a&&a.trim())try{c=JSON.parse(a)}catch{c={raw:a}}return{status:o.status,headers:o.headers,body:c}};try{return await n()}catch(i){let s=String(i?.message||i||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw i;return ca(t),n()}}async function ga(r){let e;if(r==="linkedin_personal"){let t=Ct();t&&(e=t.token)}if(e||({token:e}=await Pt(r)),typeof e!="string"||!e)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return e}function ya(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 Hr(r,e,t,n){if(typeof t!="string"||!t.trim())throw new Error("imagePath (a local image file path) is required to upload an image");let{body:i}=await fe("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:e}}},r),s=i?.value?.uploadUrl,o=i?.value?.image;if(!s||!o)throw new Error(`LinkedIn image initializeUpload returned no uploadUrl/image (got: ${JSON.stringify(i).slice(0,200)})`);let a=ia(t),c=await ga(r),d=await fetch(s,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":n||ya(t)},body:a});if(!d.ok){let l=await d.text().catch(()=>"");throw new Error(`LinkedIn image upload ${d.status}: ${l.slice(0,300)}`)}return o}var zr={id:"linkedin",serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn (connected)
338
+ Do not block the task if Notion is unavailable \u2014 these tools return { ok:false, error } on failure; treat a missing page as "no extra context" / "cannot deliver to Notion" and continue.`,resolve(){let r=Ho();return r?{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,n=ne(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await Y(`/pages/${n}`),s=Dr(i),o=i?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,c=await Mr(n,0,{used:0}),d=!1;return c.length>rt&&(c=c.slice(0,rt),d=!0),JSON.stringify({ok:!0,id:n,title:s,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,n=ne(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let s={page_size:Math.max(1,Math.min(Number(e?.maxResults)||Cr,Cr))};e?.filter&&typeof e.filter=="object"&&(s.filter=e.filter);let o=await Y(`/databases/${n}/query`,{method:"POST",body:s}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[u,p]of Object.entries(d.properties||{})){let m=Xo(p);m&&(l[u]=m)}return{id:d.id,title:Dr(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:n,count:c.length,hasMore:!!o.has_more,rows:c})}case"notion_create_page":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let n=e?.databaseId?ne(e.databaseId):null,i=e?.parentPageId?ne(e.parentPageId):ne(e?.parent||e?.pageId);if(!n&&!i)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let s=n?{database_id:n}:{page_id:i},o={title:{title:Be(t)}},a=qr(e)||[],c=a.slice(0,nt),d=await Y("/pages",{method:"POST",body:{parent:s,properties:o,...c.length?{children:c}:{}}}),l=d?.id;if(!l)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let u=a.slice(nt);return u.length&&await Jr(l,u),JSON.stringify({ok:!0,pageId:l,url:d?.url||Lt(l)})}case"notion_append_blocks":{let t=ne(e?.pageId||e?.blockId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=qr(e);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await Jr(t,n),JSON.stringify({ok:!0,pageId:t,url:Lt(t)}))}case"notion_insert_image":{let t=ne(e?.pageId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=typeof e?.caption=="string"&&e.caption.trim()?Be(e.caption.trim()):null,i,s;if(typeof e?.imagePath=="string"&&e.imagePath.trim())s=await ra(e.imagePath),i={type:"file_upload",file_upload:{id:s}};else if(typeof e?.imageUrl=="string"&&e.imageUrl.trim())i={type:"external",external:{url:e.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return n&&(i.caption=n),await Y(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:i}]}}),JSON.stringify({ok:!0,pageId:t,url:Lt(t),...s?{fileUploadId:s}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,n=ne(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let i=new URLSearchParams({block_id:n,page_size:"100"}),s=await Y(`/comments?${i.toString()}`),a=(Array.isArray(s.results)?s.results:[]).map(Qo);return JSON.stringify({ok:!0,id:n,count:a.length,comments:a})}case"notion_add_comment":{let t=typeof e?.text=="string"?e.text:typeof e?.body=="string"?e.body:"";if(!t||!t.trim())return JSON.stringify({ok:!1,error:"text is required"});let n=e?.discussionId||e?.discussion_id||null,i;if(n)i={discussion_id:String(n),rich_text:Be(t)};else{let o=e?.pageId||e?.page||e?.url||e?.id,a=ne(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:Be(t)}}let s=await Y("/comments",{method:"POST",body:i});return JSON.stringify({ok:!0,id:s?.id||"",discussionId:s?.discussion_id||n||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}},{name:"notion_create_page",description:"Create a new Notion page under a parent page (parentPageId) OR in a database (databaseId) \u2014 exactly one parent is required. Body from markdown (#/##/### headings, - bullets, 1. ordered lists; inline marks kept as literal text) or raw Notion block objects. Long bodies are chunked automatically (Notion caps 100 blocks/request). Returns { ok, pageId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{parentPageId:{type:"string",description:"Parent PAGE id/URL to create the page under (used when databaseId is absent)."},databaseId:{type:"string",description:"Parent DATABASE id/URL to create the page in (title goes into the title property)."},title:{type:"string",description:"Page title."},markdown:{type:"string",description:"Page body as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["title"]}},{name:"notion_append_blocks",description:"Append markdown (or raw Notion blocks) to the END of an existing Notion page. Accepts a page id or full Notion URL. Chunks automatically at Notion's 100-blocks-per-request cap. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["pageId"]}},{name:"notion_insert_image",description:"Append an image block to a Notion page. Pass imagePath for a LOCAL .png/.jpg file (max 20MB \u2014 uploaded via Notion's File Upload API, stored by Notion) or imageUrl for an external publicly-reachable image URL. Optional caption. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 20MB). Preferred for locally rendered charts."},imageUrl:{type:"string",description:"External image URL (must be publicly reachable; used when imagePath is absent)."},caption:{type:"string",description:"Optional image caption."}},required:["pageId"]}},{name:"notion_list_comments",description:"List the open comment discussions on a Notion page/block. Accepts a page/block id OR a full Notion URL. Returns { ok, comments:[{ id, discussionId, text, author }] }. Use to read the comment thread you are replying to.",input_schema:{type:"object",properties:{blockId:{type:"string",description:"Notion page or block id (dashed UUID or 32-char) OR a full Notion URL."}},required:["blockId"]}},{name:"notion_add_comment",description:"Post a comment on Notion. To REPLY within an existing discussion, pass { discussionId, text }. To start a NEW top-level comment on a page, pass { pageId, text }. Returns { ok, id, discussionId }. Use this to answer a user who @mentioned Zibby in a Notion comment (reply in the same discussionId).",input_schema:{type:"object",properties:{discussionId:{type:"string",description:"The discussion_id to reply into (from notion_list_comments). Preferred for replies."},pageId:{type:"string",description:"Page id/URL to start a NEW top-level comment on (used when discussionId is absent)."},text:{type:"string",description:"The comment body (plain text)."}},required:["text"]}}]};import{existsSync as na,readFileSync as ia}from"fs";import{fileURLToPath as sa}from"url";import{dirname as oa,resolve as aa}from"path";import{resolveIntegrationToken as jt,clearTokenCache as ca}from"@zibby/core/backend-client.js";function la(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=oa(sa(import.meta.url)),e=aa(r,"..","bin","mcp-skill.mjs");return na(e)?e:null}function da(){let r=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!r)return null;let e=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:r,memberId:e}}function ua(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function pa(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var ma="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 Pt(){let r=da();if(r)return r;if(ua()||pa())throw new Error(ma);return null}var fa="202506",ha="https://api.linkedin.com";function Gr(r){if(r==null)return null;let e=String(r).trim();if(!e)return null;let t=e.match(/urn:li:organization:(\d+)/i);return t?t[1]:/^\d+$/.test(e)?e:null}function Kr(r){if(!r)return"";if(r.localizedName)return String(r.localizedName);let e=r.name&&r.name.localized;if(e&&typeof e=="object"){let t=Object.values(e)[0];if(t)return String(t)}return""}function it(r,e){return r?typeof r.get=="function"?r.get(e):r[e]||r[e.toLowerCase()]||null:null}async function fe(r,e={},t="linkedin_business"){let n=async()=>{let i;if(t==="linkedin_personal"){let d=Pt();d&&(i=d.token)}if(i||({token:i}=await jt(t)),typeof i!="string"||!i)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let s=r.startsWith("https://")?r:`${ha}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,"LinkedIn-Version":fa,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${d.slice(0,300)}`)}let a=await o.text().catch(()=>""),c={};if(a&&a.trim())try{c=JSON.parse(a)}catch{c={raw:a}}return{status:o.status,headers:o.headers,body:c}};try{return await n()}catch(i){let s=String(i?.message||i||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw i;return ca(t),n()}}async function ga(r){let e;if(r==="linkedin_personal"){let t=Pt();t&&(e=t.token)}if(e||({token:e}=await jt(r)),typeof e!="string"||!e)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return e}function ya(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 Hr(r,e,t,n){if(typeof t!="string"||!t.trim())throw new Error("imagePath (a local image file path) is required to upload an image");let{body:i}=await fe("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:e}}},r),s=i?.value?.uploadUrl,o=i?.value?.image;if(!s||!o)throw new Error(`LinkedIn image initializeUpload returned no uploadUrl/image (got: ${JSON.stringify(i).slice(0,200)})`);let a=ia(t),c=await ga(r),d=await fetch(s,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":n||ya(t)},body:a});if(!d.ok){let l=await d.text().catch(()=>"");throw new Error(`LinkedIn image upload ${d.status}: ${l.slice(0,300)}`)}return o}var zr={id:"linkedin",serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn (connected)
339
339
  You can post to LinkedIn two ways \u2014 an ORG company Page (business) and your own member PROFILE (personal). Each path needs its own LinkedIn integration connected.
340
340
 
341
341
  Business (company Page) \u2014 DRAFT only:
@@ -351,10 +351,10 @@ Attaching an image (optional, both tools):
351
351
  Notes:
352
352
  - Org-page posts are ALWAYS created as a DRAFT; personal-profile posts are ALWAYS published live \u2014 choose the tool accordingly.
353
353
  - PUBLISHING IS OUTWARD-FACING AND IRREVERSIBLE. linkedin_publish_post posts live to a real audience the instant you call it \u2014 there is no undo and no draft state for member profiles. Only call it after the human has EXPLICITLY approved publishing THIS specific text in THIS conversation. If you wrote or edited the text, show it and get an explicit "yes, publish" first; if you are unsure, HOLD/draft rather than publish. The org draft tool (linkedin_create_draft_post) is the safe default when a human still needs to review.
354
- - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=la();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/linkedin.js","linkedinSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"linkedin_list_organizations":{let{body:t}=await fe("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(t.elements)?t.elements:[],i=[];for(let s of n){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=Gr(o);if(!a)continue;let c="",d="";try{let l=(await fe(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=Kr(l),d=l.vanityName||""}catch{}i.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:i.length,organizations:i})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,n=Gr(t);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let p="";try{let m=(await fe(`/rest/organizations/${n}`,{},"linkedin_business")).body;p=Kr(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:p,id:n,urn:o},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(p){return JSON.stringify({dryRun:!0,ok:!1,error:p.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let p=await Hr("linkedin_business",o,a);d.content={media:{id:p,altText:c||""}}}let l=await fe("/rest/posts",{method:"POST",body:d},"linkedin_business"),u=st(l.headers,"x-restli-id")||st(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:u,author:o,lifecycleState:"DRAFT",visibility:s,status:l.status})}case"linkedin_publish_post":{let t=Ct(),n=t?t.memberId:(await Pt("linkedin_personal")).memberId;if(!n)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let p=(await fe("/v2/userinfo",{},"linkedin_personal")).body,m=p?.name||[p?.given_name,p?.family_name].filter(Boolean).join(" ")||"",f=p?.sub?String(p.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(p){return JSON.stringify({dryRun:!0,ok:!1,error:p.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let p=await Hr("linkedin_personal",o,a);d.content={media:{id:p,altText:c||""}}}let l=await fe("/rest/posts",{method:"POST",body:d},"linkedin_personal"),u=st(l.headers,"x-restli-id")||st(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:u,author:o,lifecycleState:"PUBLISHED",visibility:s,status:l.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}}]};import{existsSync as Vr,statSync as _a,readFileSync as ba}from"fs";import{fileURLToPath as ka}from"url";import{basename as wa,dirname as Sa,resolve as Ia}from"path";import{resolveIntegrationToken as va,clearTokenCache as Na}from"@zibby/core/backend-client.js";function Oa(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Sa(ka(import.meta.url)),e=Ia(r,"..","bin","mcp-skill.mjs");return Vr(e)?e:null}var he="https://docs.googleapis.com/v1",Wr="https://www.googleapis.com/drive/v3",Ra="https://www.googleapis.com/upload/drive/v3",Ta=5*1024*1024;function Aa(){let r=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!r)return null;let e=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:r,email:e}}function xa(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Ea(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var $a="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.",Dt=2e4,La=25;function Ut(r){if(!r||typeof r!="string")return null;let e=r.trim(),t=e.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return t?t[1]:/^[a-zA-Z0-9_-]{20,}$/.test(e)?e:null}async function ja(){let r,e=Aa();if(e)r=e.token;else{if(Ea()||xa())throw new Error($a);({token:r}=await va("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function Z(r,e={}){let t=async()=>{let n=await ja(),i=await fetch(r,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Google API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Na("google"),t()}}function Pa(r){let e=[],t="",n=0;for(;n<r.length;){let i=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(i){e.push({start:t.length,end:t.length+i[1].length,link:i[2]}),t+=i[1],n+=i[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(s){e.push({start:t.length,end:t.length+s[1].length,bold:!0}),t+=s[1],n+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(n));if(o){e.push({start:t.length,end:t.length+o[1].length,code:!0}),t+=o[1],n+=o[0].length;continue}t+=r[n],n+=1}return{text:t,styles:e}}function Yr(r,e){let t=String(r??"").replace(/\r\n/g,`
354
+ - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=la();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/linkedin.js","linkedinSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"linkedin_list_organizations":{let{body:t}=await fe("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(t.elements)?t.elements:[],i=[];for(let s of n){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=Gr(o);if(!a)continue;let c="",d="";try{let l=(await fe(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=Kr(l),d=l.vanityName||""}catch{}i.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:i.length,organizations:i})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,n=Gr(t);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let p="";try{let m=(await fe(`/rest/organizations/${n}`,{},"linkedin_business")).body;p=Kr(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:p,id:n,urn:o},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(p){return JSON.stringify({dryRun:!0,ok:!1,error:p.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let p=await Hr("linkedin_business",o,a);d.content={media:{id:p,altText:c||""}}}let l=await fe("/rest/posts",{method:"POST",body:d},"linkedin_business"),u=it(l.headers,"x-restli-id")||it(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:u,author:o,lifecycleState:"DRAFT",visibility:s,status:l.status})}case"linkedin_publish_post":{let t=Pt(),n=t?t.memberId:(await jt("linkedin_personal")).memberId;if(!n)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let p=(await fe("/v2/userinfo",{},"linkedin_personal")).body,m=p?.name||[p?.given_name,p?.family_name].filter(Boolean).join(" ")||"",f=p?.sub?String(p.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(p){return JSON.stringify({dryRun:!0,ok:!1,error:p.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let p=await Hr("linkedin_personal",o,a);d.content={media:{id:p,altText:c||""}}}let l=await fe("/rest/posts",{method:"POST",body:d},"linkedin_personal"),u=it(l.headers,"x-restli-id")||it(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:u,author:o,lifecycleState:"PUBLISHED",visibility:s,status:l.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}}]};import{existsSync as Vr,statSync as _a,readFileSync as ba}from"fs";import{fileURLToPath as ka}from"url";import{basename as wa,dirname as Sa,resolve as Ia}from"path";import{resolveIntegrationToken as va,clearTokenCache as Na}from"@zibby/core/backend-client.js";function Oa(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Sa(ka(import.meta.url)),e=Ia(r,"..","bin","mcp-skill.mjs");return Vr(e)?e:null}var he="https://docs.googleapis.com/v1",Wr="https://www.googleapis.com/drive/v3",Ra="https://www.googleapis.com/upload/drive/v3",Ta=5*1024*1024;function Aa(){let r=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!r)return null;let e=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:r,email:e}}function xa(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Ea(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var $a="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.",Ut=2e4,La=25;function Ct(r){if(!r||typeof r!="string")return null;let e=r.trim(),t=e.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return t?t[1]:/^[a-zA-Z0-9_-]{20,}$/.test(e)?e:null}async function ja(){let r,e=Aa();if(e)r=e.token;else{if(Ea()||xa())throw new Error($a);({token:r}=await va("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function Z(r,e={}){let t=async()=>{let n=await ja(),i=await fetch(r,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Google API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Na("google"),t()}}function Pa(r){let e=[],t="",n=0;for(;n<r.length;){let i=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(i){e.push({start:t.length,end:t.length+i[1].length,link:i[2]}),t+=i[1],n+=i[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(s){e.push({start:t.length,end:t.length+s[1].length,bold:!0}),t+=s[1],n+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(n));if(o){e.push({start:t.length,end:t.length+o[1].length,code:!0}),t+=o[1],n+=o[0].length;continue}t+=r[n],n+=1}return{text:t,styles:e}}function Yr(r,e){let t=String(r??"").replace(/\r\n/g,`
355
355
  `);if(!t.trim())return{requests:[],endIndex:e};let n=t.split(`
356
356
  `),i="",s=[],o=[];for(let l of n){let u=l,p=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(u),h=/^\s*[-*]\s+(.*)$/.exec(u),y=/^\s*\d+[.)]\s+(.*)$/.exec(u);f?(p=`HEADING_${f[1].length}`,u=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",u=h[1]):y&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",u=y[1]);let{text:_,styles:b}=Pa(u),g=e+i.length;for(let w of b)o.push({...w,start:g+w.start,end:g+w.end});i+=`${_}
357
- `,s.push({start:g,end:e+i.length,named:p,bullet:m})}if(!i)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:i}}];for(let l of s)l.named&&a.push({updateParagraphStyle:{range:{startIndex:l.start,endIndex:l.end},paragraphStyle:{namedStyleType:l.named},fields:"namedStyleType"}});let c=null,d=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let l of s)l.bullet?c&&c.preset===l.bullet?c.end=l.end:(d(),c={start:l.start,end:l.end,preset:l.bullet}):d();d();for(let l of o)l.end<=l.start||(l.bold?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{bold:!0},fields:"bold"}}):l.link?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{link:{url:l.link}},fields:"link"}}):l.code&&a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:e+i.length}}function Ca(r){let e="",t=n=>{for(let i of Array.isArray(n)?n:[]){if(e.length>=Dt)return;if(i.paragraph)for(let s of i.paragraph.elements||[])e+=s?.textRun?.content||"";else if(i.table)for(let s of i.table.tableRows||[])for(let o of s.tableCells||[])t(o.content);else i.tableOfContents&&t(i.tableOfContents.content)}};return t(r?.content),e.slice(0,Dt)}var Me=r=>`https://docs.google.com/document/d/${r}/edit`;function Ua(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Vr(e)||!_a(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=ba(e);if(t.length>Ta)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:wa(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Da(r,e,t){let n=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${n}\r
357
+ `,s.push({start:g,end:e+i.length,named:p,bullet:m})}if(!i)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:i}}];for(let l of s)l.named&&a.push({updateParagraphStyle:{range:{startIndex:l.start,endIndex:l.end},paragraphStyle:{namedStyleType:l.named},fields:"namedStyleType"}});let c=null,d=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let l of s)l.bullet?c&&c.preset===l.bullet?c.end=l.end:(d(),c={start:l.start,end:l.end,preset:l.bullet}):d();d();for(let l of o)l.end<=l.start||(l.bold?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{bold:!0},fields:"bold"}}):l.link?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{link:{url:l.link}},fields:"link"}}):l.code&&a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:e+i.length}}function Ca(r){let e="",t=n=>{for(let i of Array.isArray(n)?n:[]){if(e.length>=Ut)return;if(i.paragraph)for(let s of i.paragraph.elements||[])e+=s?.textRun?.content||"";else if(i.table)for(let s of i.table.tableRows||[])for(let o of s.tableCells||[])t(o.content);else i.tableOfContents&&t(i.tableOfContents.content)}};return t(r?.content),e.slice(0,Ut)}var Me=r=>`https://docs.google.com/document/d/${r}/edit`;function Ua(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Vr(e)||!_a(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=ba(e);if(t.length>Ta)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:wa(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Da(r,e,t){let n=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${n}\r
358
358
  Content-Type: application/json; charset=UTF-8\r
359
359
  \r
360
360
  ${JSON.stringify(r)}\r
@@ -371,10 +371,10 @@ Docs access is PER-USER: each teammate connects their OWN Google account (Integr
371
371
  - gdocs_insert_image: append a LOCAL image file (png/jpg, \u22645MB) to the end of a doc \u2014 pass { documentId, imagePath, width?, height? } (width/height in PT, optional). The image is uploaded to the user's Drive and made link-readable (anyone with the link) so Docs can render it. Returns { ok, documentId, fileId, url }.
372
372
  - gdocs_get: read a doc back as plain text (works for app-created/user-picked docs; arbitrary docs need the extended documents.readonly connection).
373
373
  - gdocs_list_created: list the Google Docs visible to this app (drive.file \u2192 only docs it created or the user picked).
374
- These tools return { ok:false, error } on failure \u2014 treat an unavailable Google connection as "cannot deliver to Docs" and report it rather than blocking the task.`,resolve(){let r=Oa();if(!r)return null;let e={};for(let t of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gdocs_create_doc":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let i=(await Z(`${he}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!i)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=Zr(e);if(s&&s.trim()){let{requests:o}=Yr(s,1);o.length&&await Z(`${he}/documents/${i}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:i,title:t,url:Me(i)})}case"gdocs_append":{let t=Ut(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=Zr(e);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await Z(`${he}/documents/${t}`))?.body,o=Array.isArray(s?.content)?s.content:[],a=o.length&&o[o.length-1].endIndex||2,c=Math.max(1,a-1),d=[],l=c;c>1&&(d.push({insertText:{location:{index:c},text:`
375
- `}}),l=c+1);let u=Yr(n,l);return d.push(...u.requests),await Z(`${he}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:Me(t)})}case"gdocs_insert_image":{let t=Ut(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:n,fileName:i,mimeType:s}=Ua(e.imagePath),{rawBody:o,contentType:a}=Da({name:i,mimeType:s},n,s),d=(await Z(`${Ra}/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 Z(`${Wr}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await Z(`${he}/documents/${t}`),u=Array.isArray(l?.body?.content)?l.body.content:[],p=u.length&&u[u.length-1].endIndex||2,f={location:{index:Math.max(1,p-1)},uri:`https://drive.google.com/uc?export=download&id=${d}`},h=Number(e?.width),y=Number(e?.height);return(Number.isFinite(h)&&h>0||Number.isFinite(y)&&y>0)&&(f.objectSize={...Number.isFinite(h)&&h>0?{width:{magnitude:h,unit:"PT"}}:{},...Number.isFinite(y)&&y>0?{height:{magnitude:y,unit:"PT"}}:{}}),await Z(`${he}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:Me(t)})}case"gdocs_get":{let t=Ut(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=await Z(`${he}/documents/${t}`),i=Ca(n?.body);return JSON.stringify({ok:!0,documentId:t,title:n?.title||"",url:Me(t),text:i,...i.length>=Dt?{truncated:!0}:{}})}case"gdocs_list_created":{let t=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(La),orderBy:"modifiedTime desc"}),n=await Z(`${Wr}/files?${t.toString()}`),i=(Array.isArray(n?.files)?n.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||Me(s.id)}));return JSON.stringify({ok:!0,count:i.length,files:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). Under the default drive.file scope this works ONLY for docs this app created or the user explicitly picked; reading arbitrary docs requires the extended documents.readonly connection. Returns { ok, documentId, title, url, text }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."}},required:["documentId"]}},{name:"gdocs_list_created",description:"List the Google Docs visible to this integration, newest first (max 25). NOTE: under the drive.file scope this lists ONLY docs the app created or the user explicitly picked \u2014 it is NOT a full Drive search. Returns { ok, count, files:[{ documentId, title, modifiedTime, url }] }.",input_schema:{type:"object",properties:{}}}]};import{existsSync as sn,statSync as qa,readFileSync as Ja}from"fs";import{fileURLToPath as Ba}from"url";import{basename as Ma,dirname as Fa,resolve as Ga}from"path";import{resolveIntegrationToken as Ka}from"@zibby/core/backend-client.js";function Ha(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Fa(Ba(import.meta.url)),e=Ga(r,"..","bin","mcp-skill.mjs");return sn(e)?e:null}var Xr=2e4,en=50,za=10*1024*1024,Wa=6e3*1e3,Fe=null;async function on(){let{appId:r,appSecret:e,host:t}=await Ka("lark");if(Fe&&Fe.appId===r&&Fe.expiresAt>Date.now())return{token:Fe.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return Fe={token:i.tenant_access_token,expiresAt:Date.now()+Wa,appId:r},{token:i.tenant_access_token,host:t}}async function V(r,e,t){let{token:n,host:i}=await on(),s={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(s.body=JSON.stringify(t));let a=await(await fetch(`${i}${e}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:i}}function ot(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function ge(r){if(!r||typeof r!="string")return null;let e=r.trim();if(!e)return null;let t=e.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return t?{type:t[1],token:t[2]}:/^[A-Za-z0-9]{10,}$/.test(e)?{type:"docx",token:e}:null}async function Ae(r){let e=typeof r=="string"?ge(r):r;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:t}=await V("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),n=t?.node||{};if(n.obj_type!=="docx"||!n.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${n.obj_type||"unknown"})`);return n.obj_token}function tn(r){let e=String(r??"").replace(/\r\n/g,`
374
+ These tools return { ok:false, error } on failure \u2014 treat an unavailable Google connection as "cannot deliver to Docs" and report it rather than blocking the task.`,resolve(){let r=Oa();if(!r)return null;let e={};for(let t of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gdocs_create_doc":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let i=(await Z(`${he}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!i)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=Zr(e);if(s&&s.trim()){let{requests:o}=Yr(s,1);o.length&&await Z(`${he}/documents/${i}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:i,title:t,url:Me(i)})}case"gdocs_append":{let t=Ct(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=Zr(e);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await Z(`${he}/documents/${t}`))?.body,o=Array.isArray(s?.content)?s.content:[],a=o.length&&o[o.length-1].endIndex||2,c=Math.max(1,a-1),d=[],l=c;c>1&&(d.push({insertText:{location:{index:c},text:`
375
+ `}}),l=c+1);let u=Yr(n,l);return d.push(...u.requests),await Z(`${he}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:Me(t)})}case"gdocs_insert_image":{let t=Ct(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:n,fileName:i,mimeType:s}=Ua(e.imagePath),{rawBody:o,contentType:a}=Da({name:i,mimeType:s},n,s),d=(await Z(`${Ra}/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 Z(`${Wr}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await Z(`${he}/documents/${t}`),u=Array.isArray(l?.body?.content)?l.body.content:[],p=u.length&&u[u.length-1].endIndex||2,f={location:{index:Math.max(1,p-1)},uri:`https://drive.google.com/uc?export=download&id=${d}`},h=Number(e?.width),y=Number(e?.height);return(Number.isFinite(h)&&h>0||Number.isFinite(y)&&y>0)&&(f.objectSize={...Number.isFinite(h)&&h>0?{width:{magnitude:h,unit:"PT"}}:{},...Number.isFinite(y)&&y>0?{height:{magnitude:y,unit:"PT"}}:{}}),await Z(`${he}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:Me(t)})}case"gdocs_get":{let t=Ct(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=await Z(`${he}/documents/${t}`),i=Ca(n?.body);return JSON.stringify({ok:!0,documentId:t,title:n?.title||"",url:Me(t),text:i,...i.length>=Ut?{truncated:!0}:{}})}case"gdocs_list_created":{let t=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(La),orderBy:"modifiedTime desc"}),n=await Z(`${Wr}/files?${t.toString()}`),i=(Array.isArray(n?.files)?n.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||Me(s.id)}));return JSON.stringify({ok:!0,count:i.length,files:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). Under the default drive.file scope this works ONLY for docs this app created or the user explicitly picked; reading arbitrary docs requires the extended documents.readonly connection. Returns { ok, documentId, title, url, text }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."}},required:["documentId"]}},{name:"gdocs_list_created",description:"List the Google Docs visible to this integration, newest first (max 25). NOTE: under the drive.file scope this lists ONLY docs the app created or the user explicitly picked \u2014 it is NOT a full Drive search. Returns { ok, count, files:[{ documentId, title, modifiedTime, url }] }.",input_schema:{type:"object",properties:{}}}]};import{existsSync as sn,statSync as qa,readFileSync as Ja}from"fs";import{fileURLToPath as Ba}from"url";import{basename as Ma,dirname as Fa,resolve as Ga}from"path";import{resolveIntegrationToken as Ka}from"@zibby/core/backend-client.js";function Ha(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Fa(Ba(import.meta.url)),e=Ga(r,"..","bin","mcp-skill.mjs");return sn(e)?e:null}var Xr=2e4,en=50,za=10*1024*1024,Wa=6e3*1e3,Fe=null;async function on(){let{appId:r,appSecret:e,host:t}=await Ka("lark");if(Fe&&Fe.appId===r&&Fe.expiresAt>Date.now())return{token:Fe.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return Fe={token:i.tenant_access_token,expiresAt:Date.now()+Wa,appId:r},{token:i.tenant_access_token,host:t}}async function V(r,e,t){let{token:n,host:i}=await on(),s={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(s.body=JSON.stringify(t));let a=await(await fetch(`${i}${e}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:i}}function st(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function ge(r){if(!r||typeof r!="string")return null;let e=r.trim();if(!e)return null;let t=e.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return t?{type:t[1],token:t[2]}:/^[A-Za-z0-9]{10,}$/.test(e)?{type:"docx",token:e}:null}async function Ae(r){let e=typeof r=="string"?ge(r):r;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:t}=await V("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),n=t?.node||{};if(n.obj_type!=="docx"||!n.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${n.obj_type||"unknown"})`);return n.obj_token}function tn(r){let e=String(r??"").replace(/\r\n/g,`
376
376
  `),t=[];for(let n of e.split(`
377
- `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d,l;if(s){let u=s[1].length;c=`heading${u}`,d=2+u,l=s[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=i);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function at(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function rn(r,e){let t;for(let n=0;n<e.length;n+=en){let i=e.slice(n,n+en);t=(await V("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:i})).host}return t}function Ya(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!sn(e)||!qa(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=Ja(e);if(t.length>za)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function Za({fileName:r,parentNode:e,bytes:t}){let{token:n,host:i}=await on(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",e),s.set("size",String(t.length)),s.set("file",new Blob([t]),r);let a=await(await fetch(`${i}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${n}`},body:s})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var Va="docx",Qa=50;function nn(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function Xa(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function ec(r){let e=Array.isArray(r?.reply_list?.replies)?r.reply_list.replies:[];return{commentId:r?.comment_id||"",resolved:!!r?.is_solved,replies:e.map(t=>({replyId:t?.reply_id||"",author:t?.user_id||"",text:Xa(t?.content?.elements),createTime:t?.create_time||""}))}}function qt(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():Va}var an={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:N.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs (connected)
377
+ `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d,l;if(s){let u=s[1].length;c=`heading${u}`,d=2+u,l=s[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=i);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function ot(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function rn(r,e){let t;for(let n=0;n<e.length;n+=en){let i=e.slice(n,n+en);t=(await V("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:i})).host}return t}function Ya(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!sn(e)||!qa(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=Ja(e);if(t.length>za)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function Za({fileName:r,parentNode:e,bytes:t}){let{token:n,host:i}=await on(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",e),s.set("size",String(t.length)),s.set("file",new Blob([t]),r);let a=await(await fetch(`${i}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${n}`},body:s})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var Va="docx",Qa=50;function nn(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function Xa(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function ec(r){let e=Array.isArray(r?.reply_list?.replies)?r.reply_list.replies:[];return{commentId:r?.comment_id||"",resolved:!!r?.is_solved,replies:e.map(t=>({replyId:t?.reply_id||"",author:t?.user_id||"",text:Xa(t?.content?.elements),createTime:t?.create_time||""}))}}function Dt(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():Va}var an={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:N.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs (connected)
378
378
  You can read, create, and append Lark/Feishu documents (docx). This reuses the same connected Lark app as messaging.
379
379
  - larkdoc_get: pass a Lark doc id OR a full doc URL (a /docx/ or /wiki/ link); returns { ok, documentId, title, url, text } where text is the doc as plain text (truncated to ~20k chars). Use it as reference context.
380
380
  - larkdoc_create: create a new doc from a title + markdown/text (#/##/### headings, - bullets, 1. ordered supported); returns { ok, documentId, url }. Share the url.
@@ -383,7 +383,7 @@ You can read, create, and append Lark/Feishu documents (docx). This reuses the s
383
383
  - larkdoc_list_comments: list the comment threads on a doc (pass the documentId or doc URL); returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.
384
384
  - larkdoc_reply_comment: reply INSIDE an existing comment thread \u2014 pass { documentId, commentId, text }. Use this to answer a user who @mentioned Zibby in a doc comment (reply in the SAME commentId).
385
385
  - larkdoc_add_comment: post a NEW top-level comment on a doc \u2014 pass { documentId, text }.
386
- These tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.`,resolve(){let r=Ha();return r?{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ae(n),s="";try{s=(await V("GET",`/open-apis/docx/v1/documents/${i}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await V("GET",`/open-apis/docx/v1/documents/${i}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>Xr&&(c=c.slice(0,Xr),d=!0),JSON.stringify({ok:!0,documentId:i,title:s,url:ot(a,i),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let{data:n,host:i}=await V("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),s=n?.document?.document_id;if(!s)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let o=at(e);if(o&&o.trim()){let a=tn(o);a.length&&await rn(s,a)}return JSON.stringify({ok:!0,documentId:s,title:t,url:ot(i,s)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=at(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Ae(n),o=tn(i);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await rn(s,o);return JSON.stringify({ok:!0,documentId:s,url:ot(a,s)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let i=await Ae(n),s=e.imagePath.trim(),o=Ya(s),a=Ma(s),d=(await V("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 Za({fileName:a,parentNode:d,bytes:o}),u={token:l},p=Number(e?.width),m=Number(e?.height);Number.isFinite(p)&&p>0&&(u.width=Math.round(p)),Number.isFinite(m)&&m>0&&(u.height=Math.round(m));let{host:f}=await V("PATCH",`/open-apis/docx/v1/documents/${i}/blocks/${d}?document_revision_id=-1`,{replace_image:u});return JSON.stringify({ok:!0,documentId:i,blockId:d,fileToken:l,url:ot(f,i)})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ae(n),s=qt(e),o=new URLSearchParams({file_type:s,page_size:String(Qa)}),{data:a}=await V("GET",`/open-apis/drive/v1/files/${i}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(ec);return JSON.stringify({ok:!0,documentId:i,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=at({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Ae(n),o=qt(e),{data:a}=await V("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:nn(i)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=e?.commentId||e?.comment_id;if(!i)return JSON.stringify({ok:!1,error:"commentId is required"});let s=at({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Ae(n),a=qt(e),{data:c}=await V("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(i)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:nn(s)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(i),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root."}},required:["title"]}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};var cn={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||[],...W.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return P.serverName;if(process.env.LARK_RECEIVE_ID)return W.serverName;if(process.env.SLACK_BOT_TOKEN)return P.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?P.allowedTools||[]:process.env.LARK_RECEIVE_ID?W.allowedTools||[]:process.env.SLACK_BOT_TOKEN?P.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
386
+ These tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.`,resolve(){let r=Ha();return r?{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ae(n),s="";try{s=(await V("GET",`/open-apis/docx/v1/documents/${i}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await V("GET",`/open-apis/docx/v1/documents/${i}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>Xr&&(c=c.slice(0,Xr),d=!0),JSON.stringify({ok:!0,documentId:i,title:s,url:st(a,i),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let{data:n,host:i}=await V("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),s=n?.document?.document_id;if(!s)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let o=ot(e);if(o&&o.trim()){let a=tn(o);a.length&&await rn(s,a)}return JSON.stringify({ok:!0,documentId:s,title:t,url:st(i,s)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=ot(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Ae(n),o=tn(i);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await rn(s,o);return JSON.stringify({ok:!0,documentId:s,url:st(a,s)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let i=await Ae(n),s=e.imagePath.trim(),o=Ya(s),a=Ma(s),d=(await V("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 Za({fileName:a,parentNode:d,bytes:o}),u={token:l},p=Number(e?.width),m=Number(e?.height);Number.isFinite(p)&&p>0&&(u.width=Math.round(p)),Number.isFinite(m)&&m>0&&(u.height=Math.round(m));let{host:f}=await V("PATCH",`/open-apis/docx/v1/documents/${i}/blocks/${d}?document_revision_id=-1`,{replace_image:u});return JSON.stringify({ok:!0,documentId:i,blockId:d,fileToken:l,url:st(f,i)})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ae(n),s=Dt(e),o=new URLSearchParams({file_type:s,page_size:String(Qa)}),{data:a}=await V("GET",`/open-apis/drive/v1/files/${i}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(ec);return JSON.stringify({ok:!0,documentId:i,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=ot({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Ae(n),o=Dt(e),{data:a}=await V("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:nn(i)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=e?.commentId||e?.comment_id;if(!i)return JSON.stringify({ok:!1,error:"commentId is required"});let s=ot({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Ae(n),a=Dt(e),{data:c}=await V("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(i)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:nn(s)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(i),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root."}},required:["title"]}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};var cn={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||[],...W.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return P.serverName;if(process.env.LARK_RECEIVE_ID)return W.serverName;if(process.env.SLACK_BOT_TOKEN)return P.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?P.allowedTools||[]:process.env.LARK_RECEIVE_ID?W.allowedTools||[]:process.env.SLACK_BOT_TOKEN?P.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
387
387
  You can post chat messages via:
388
388
  - slack_post_message (channel, text[, blocks]) \u2014 Slack. The \`channel\` is REQUIRED on every call.
389
389
  - lark_send_message (receive_id, text) \u2014 Lark.
@@ -414,17 +414,17 @@ AFTER completing the test, you MUST call memory_save_insight at least once:
414
414
  3. After OAuth completes, ask me to install Slack again`},sentry:{description:"Sentry error tracking \u2014 projects, issues, events",integrationProvider:"sentry",envKeys:[],setupInstructions:`To connect Sentry:
415
415
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
416
416
  2. Click "Connect Sentry" and authorize
417
- 3. After OAuth completes, ask me to install Sentry again`},runner:{description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],setupInstructions:"Ready to use. Runs zibby test workflows as background processes \u2014 each with its own browser and session."},browser:{description:"Playwright browser automation (navigate, click, fill, screenshot)",envKeys:[],setupInstructions:"Ready to use. Starts a Playwright browser for web automation."},memory:{description:"Test memory database (Dolt) \u2014 history, selectors, insights",envKeys:[],setupInstructions:"Ready to use. Requires Dolt (https://docs.dolthub.com/introduction/installation) and a memory DB via `zibby init --mem`."},"chat-memory":{description:"Persistent chat memory \u2014 remembers facts, decisions, and task history across sessions (Dolt-backed)",envKeys:[],setupInstructions:'Ready to use. Requires Dolt installed. Tables auto-create on first use. Install with: "add chat memory" or "install chat-memory".'},git:{description:"Clone and explore git repositories locally for codebase analysis",envKeys:[],setupInstructions:"Ready to use. Clone repos with git_checkout, explore with git_explore. Auto-authenticates with GitHub/GitLab tokens."}};function uc(){let r=["## Available Skills"];for(let[e,t]of Object.entries(ye)){let n=t.integrationProvider?`integration: ${t.integrationProvider}`:"ready";r.push(`- ${e}: ${t.description} [${n}]`)}return r.push(""),r.push("Use the install_skill / uninstall_skill / list_available_skills tools to manage skills."),r.push(`Zibby third party Integration settings page: ${Jt()}`),r.push(""),r.push("## Tool-First Policy (mandatory)"),r.push("CRITICAL RULES \u2014 follow these strictly:"),r.push("1. When user asks to do something and a matching skill is available but not installed, IMMEDIATELY call install_skill. Never ask for credentials or confirmation first."),r.push(`2. If install_skill succeeds, the skill's tools are now available. Use them RIGHT AWAY in the same turn \u2014 don't just say "it's connected", actually call the tools.`),r.push("3. If install_skill reports needsIntegration, tell the user to connect via the integration URL and try again after."),r.push("4. When the relevant skill is already installed, use its tools directly \u2014 don't ask for IDs or keys. Each skill's own instructions explain the workflow."),r.push("5. If a task needs multiple skills (e.g. data from one + execution from another), install all of them, then follow each skill's workflow instructions."),r.join(`
418
- `)}function pc(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=lc(cc(),".zibby","config.json");return oc(r)&&JSON.parse(ac(r,"utf-8")).sessionToken||null}catch{return null}}function mc(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function Jt(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function fc(r){try{let e=process.platform;return dc(e==="darwin"?"open":e==="win32"?"cmd":"xdg-open",e==="win32"?["/c","start","",r]:[r],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}async function hc(){let r=pc();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${mc()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});return e.ok?{checked:!0,statuses:await e.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${e.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function un(r,e){if(!e||!r)return{connected:null};let t=r[e];return!t||typeof t.connected!="boolean"?{connected:null,details:t||null}:{connected:t.connected,details:t}}var pn={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:ye,promptFragment:uc,tools:[{name:"install_skill",description:"Install a skill into the current chat session so its tools become available",input_schema:{type:"object",properties:{skillId:{type:"string",description:'Skill identifier to install (e.g. "jira", "github", "browser", "memory")'}},required:["skillId"]}},{name:"uninstall_skill",description:"Remove a skill from the current chat session",input_schema:{type:"object",properties:{skillId:{type:"string",description:"Skill identifier to remove"}},required:["skillId"]}},{name:"list_available_skills",description:"List all skills that can be installed, with their env-var readiness status",input_schema:{type:"object",properties:{}}}],async handleToolCall(r,e,t){let{activeSkills:n}=t,i=await hc();if(r==="list_available_skills"){let s=Object.entries(ye).map(([o,a])=>{let c=n.includes(o),d=un(i.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:d.connected,setupInstructions:d.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:s})}if(r==="install_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(n.includes(s)){let l=ye[s],{getSkill:u}=await import("@zibby/agent-workflow"),m=(u(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?Jt():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!ye[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(ye).join(", ")}`});let o=ye[s];if(o.integrationProvider){let l=un(i.statuses,o.integrationProvider),u=Jt();if(i.checked&&l.connected===!1){let p=fc(u);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:u,openedBrowser:p,setupInstructions:`Please connect ${o.integrationProvider} first at ${u}. After you finish OAuth, ask me to install ${s} again.`})}}n.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(s)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:d,hint:`${s} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(s==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=n.indexOf(s);return o===-1?JSON.stringify({ok:!1,error:`${s} is not installed`}):(n.splice(o,1),JSON.stringify({ok:!0,uninstalled:s}))}return JSON.stringify({error:`Unknown tool: ${r}`})},resolve(){return null}};import{readFileSync as gc,readdirSync as yc,statSync as fn,writeFileSync as _c,mkdirSync as bc}from"fs";import{join as hn,resolve as kc,relative as wc}from"path";import{execSync as gn}from"child_process";var mn=256*1024,Sc=64*1024,yn={id:"core-tools",description:"File read/write, directory listing, shell commands, open URLs, wait for async operations",envKeys:[],tools:[{name:"read_file",description:"Read the contents of a file. Returns the text content.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"}},required:["path"]}},{name:"write_file",description:"Write content to a file. Creates parent directories if needed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"},content:{type:"string",description:"Content to write"}},required:["path","content"]}},{name:"list_directory",description:"List files and directories in a path. Returns names with type indicators (/ for dirs).",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory path (relative to cwd or absolute). Defaults to cwd."}}}},{name:"run_command",description:"Run a shell command and return its output. Use for grep, git, npm, etc.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},cwd:{type:"string",description:"Working directory (optional, defaults to project root)"}},required:["command"]}},{name:"open_url",description:"Open a URL in the user's default browser. Use for OAuth flows, documentation, integration setup pages.",input_schema:{type:"object",properties:{url:{type:"string",description:"URL to open"}},required:["url"]}},{name:"wait",description:"Wait for N seconds. Use this for async operations (tests, builds, deploys) \u2014 wait, then check status again.",input_schema:{type:"object",properties:{seconds:{type:"number",description:"Seconds to wait (default: 5, max: 300)"},reason:{type:"string",description:"Why waiting (for logging/clarity)"}}}}],async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"read_file":return Ic(e,n);case"write_file":return vc(e,n);case"list_directory":return Nc(e,n);case"run_command":return Oc(e,n);case"open_url":return Rc(e);case"wait":return await Tc(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function ct(r,e){return kc(e,r)}function Ic(r,e){let t=ct(r.path,e),n=fn(t);return n.size>mn?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${mn/1024}KB`}):gc(t,"utf-8")}function vc(r,e){let t=ct(r.path,e),n=hn(t,"..");return bc(n,{recursive:!0}),_c(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:wc(e,t)})}function Nc(r,e){let t=ct(r.path||".",e);return yc(t).map(i=>{try{return fn(hn(t,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
419
- `)}function Oc(r,e){let t=r.cwd?ct(r.cwd,e):e;return gn(r.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:Sc,stdio:["pipe","pipe","pipe"]})||"(no output)"}function Rc(r){let{url:e}=r;if(!e||!e.startsWith("http://")&&!e.startsWith("https://"))return JSON.stringify({error:"Invalid URL \u2014 must start with http:// or https://"});let t=process.platform,n=t==="darwin"?"open":t==="win32"?"start":"xdg-open";try{return gn(`${n} "${e}"`,{stdio:"ignore",timeout:5e3}),JSON.stringify({ok:!0,opened:e})}catch{return JSON.stringify({ok:!1,error:`Could not open browser. Please visit: ${e}`})}}async function Tc(r,e){let t=Math.min(Math.max(r.seconds||5,1),300),n=r.reason||"async operation",i=500,s=Date.now()+t*1e3;for(;Date.now()<s;){if(e?.aborted)return JSON.stringify({ok:!0,waited:Math.round((t*1e3-(s-Date.now()))/1e3),reason:n,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(i,s-Date.now())))}return JSON.stringify({ok:!0,waited:t,reason:n})}import{existsSync as Ac}from"fs";import{fileURLToPath as xc}from"url";import{dirname as Ec,resolve as $c}from"path";import{resolveIntegrationToken as Ge}from"@zibby/core/backend-client.js";function Lc(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=Ec(xc(import.meta.url)),e=$c(r,"..","bin","mcp-sentry.mjs");return Ac(e)?e:null}function Ke(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function _n(r){let e=r||process.env.SENTRY_ORG;if(!e)throw new Error('Sentry organization not resolved \u2014 reconnect Sentry, or set SENTRY_ORG (self-hosted; the default org slug is "sentry").');return e}async function bn(r,e={}){let{token:t,organizationSlug:n,baseUrl:i}=await Ge("sentry"),s=`${Ke(i)}/api/0/organizations/${_n(n)}${r}`,o={method:e.method||"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}};e.body!=null&&(o.body=typeof e.body=="string"?e.body:JSON.stringify(e.body));let a=await fetch(s,o);if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Sentry API ${a.status}: ${c.slice(0,300)}`)}return a.json()}async function jc(){return bn("/projects/?per_page=50")}async function Pc({query:r="is:unresolved",sort:e="date",project:t,limit:n=25}={}){let i=`/issues/?query=${encodeURIComponent(r)}&sort=${e}&per_page=${n}`;return t&&(i+=`&project=${encodeURIComponent(t)}`),bn(i)}async function Bt(r){let e=String(r??"").trim();if(!e)throw new Error("resolveSentryIssueId: issueRef is required");if(/^\d+$/.test(e))return e;let{token:t,organizationSlug:n,baseUrl:i}=await Ge("sentry"),s=await fetch(`${Ke(i)}/api/0/organizations/${_n(n)}/shortids/${encodeURIComponent(e)}/`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status} resolving shortId "${e}": ${c.slice(0,200)}`)}let o=await s.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${e}" did not resolve to a numeric issue id`);return String(a)}async function Cc(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let e=await Bt(r),{token:t,baseUrl:n}=await Ge("sentry"),i=await fetch(`${Ke(n)}/api/0/issues/${e}/`,{headers:{Authorization:`Bearer ${t}`}});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`Sentry API ${i.status}: ${s.slice(0,300)}`)}return i.json()}async function Uc(r,e={}){if(!r)throw new Error("sentryUpdateIssue: issueId is required");let t={};for(let a of["status","statusDetails","assignedTo","isBookmarked","hasSeen"])e[a]!==void 0&&(t[a]=e[a]);if(Object.keys(t).length===0)throw new Error("sentryUpdateIssue: nothing to update (pass status / statusDetails / assignedTo / isBookmarked / hasSeen)");let n=await Bt(r),{token:i,baseUrl:s}=await Ge("sentry"),o=await fetch(`${Ke(s)}/api/0/issues/${n}/`,{method:"PUT",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===403?new Error(`Sentry API 403 updating issue ${r}: ${a.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access to let Zibby resolve/comment on issues.`):new Error(`Sentry API ${o.status} updating issue ${r}: ${a.slice(0,300)}`)}return o.json()}async function Dc(r,e){if(!r)throw new Error("sentryAddComment: issueId is required");if(!e||!String(e).trim())throw new Error("sentryAddComment: text is required");let t=await Bt(r),{token:n,baseUrl:i}=await Ge("sentry"),s=await fetch(`${Ke(i)}/api/0/issues/${t}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(e)})});if(!s.ok){let o=await s.text().catch(()=>"");throw s.status===403?new Error(`Sentry API 403 commenting on issue ${r}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${s.status} commenting on issue ${r}: ${o.slice(0,300)}`)}return s.json()}var lt={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:N.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
417
+ 3. After OAuth completes, ask me to install Sentry again`},runner:{description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],setupInstructions:"Ready to use. Runs zibby test workflows as background processes \u2014 each with its own browser and session."},browser:{description:"Playwright browser automation (navigate, click, fill, screenshot)",envKeys:[],setupInstructions:"Ready to use. Starts a Playwright browser for web automation."},memory:{description:"Test memory database (Dolt) \u2014 history, selectors, insights",envKeys:[],setupInstructions:"Ready to use. Requires Dolt (https://docs.dolthub.com/introduction/installation) and a memory DB via `zibby init --mem`."},"chat-memory":{description:"Persistent chat memory \u2014 remembers facts, decisions, and task history across sessions (Dolt-backed)",envKeys:[],setupInstructions:'Ready to use. Requires Dolt installed. Tables auto-create on first use. Install with: "add chat memory" or "install chat-memory".'},git:{description:"Clone and explore git repositories locally for codebase analysis",envKeys:[],setupInstructions:"Ready to use. Clone repos with git_checkout, explore with git_explore. Auto-authenticates with GitHub/GitLab tokens."}};function uc(){let r=["## Available Skills"];for(let[e,t]of Object.entries(ye)){let n=t.integrationProvider?`integration: ${t.integrationProvider}`:"ready";r.push(`- ${e}: ${t.description} [${n}]`)}return r.push(""),r.push("Use the install_skill / uninstall_skill / list_available_skills tools to manage skills."),r.push(`Zibby third party Integration settings page: ${qt()}`),r.push(""),r.push("## Tool-First Policy (mandatory)"),r.push("CRITICAL RULES \u2014 follow these strictly:"),r.push("1. When user asks to do something and a matching skill is available but not installed, IMMEDIATELY call install_skill. Never ask for credentials or confirmation first."),r.push(`2. If install_skill succeeds, the skill's tools are now available. Use them RIGHT AWAY in the same turn \u2014 don't just say "it's connected", actually call the tools.`),r.push("3. If install_skill reports needsIntegration, tell the user to connect via the integration URL and try again after."),r.push("4. When the relevant skill is already installed, use its tools directly \u2014 don't ask for IDs or keys. Each skill's own instructions explain the workflow."),r.push("5. If a task needs multiple skills (e.g. data from one + execution from another), install all of them, then follow each skill's workflow instructions."),r.join(`
418
+ `)}function pc(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=lc(cc(),".zibby","config.json");return oc(r)&&JSON.parse(ac(r,"utf-8")).sessionToken||null}catch{return null}}function mc(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function qt(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function fc(r){try{let e=process.platform;return dc(e==="darwin"?"open":e==="win32"?"cmd":"xdg-open",e==="win32"?["/c","start","",r]:[r],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}async function hc(){let r=pc();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${mc()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});return e.ok?{checked:!0,statuses:await e.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${e.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function un(r,e){if(!e||!r)return{connected:null};let t=r[e];return!t||typeof t.connected!="boolean"?{connected:null,details:t||null}:{connected:t.connected,details:t}}var pn={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:ye,promptFragment:uc,tools:[{name:"install_skill",description:"Install a skill into the current chat session so its tools become available",input_schema:{type:"object",properties:{skillId:{type:"string",description:'Skill identifier to install (e.g. "jira", "github", "browser", "memory")'}},required:["skillId"]}},{name:"uninstall_skill",description:"Remove a skill from the current chat session",input_schema:{type:"object",properties:{skillId:{type:"string",description:"Skill identifier to remove"}},required:["skillId"]}},{name:"list_available_skills",description:"List all skills that can be installed, with their env-var readiness status",input_schema:{type:"object",properties:{}}}],async handleToolCall(r,e,t){let{activeSkills:n}=t,i=await hc();if(r==="list_available_skills"){let s=Object.entries(ye).map(([o,a])=>{let c=n.includes(o),d=un(i.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:d.connected,setupInstructions:d.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:s})}if(r==="install_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(n.includes(s)){let l=ye[s],{getSkill:u}=await import("@zibby/agent-workflow"),m=(u(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?qt():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!ye[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(ye).join(", ")}`});let o=ye[s];if(o.integrationProvider){let l=un(i.statuses,o.integrationProvider),u=qt();if(i.checked&&l.connected===!1){let p=fc(u);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:u,openedBrowser:p,setupInstructions:`Please connect ${o.integrationProvider} first at ${u}. After you finish OAuth, ask me to install ${s} again.`})}}n.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(s)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:d,hint:`${s} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(s==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=n.indexOf(s);return o===-1?JSON.stringify({ok:!1,error:`${s} is not installed`}):(n.splice(o,1),JSON.stringify({ok:!0,uninstalled:s}))}return JSON.stringify({error:`Unknown tool: ${r}`})},resolve(){return null}};import{readFileSync as gc,readdirSync as yc,statSync as fn,writeFileSync as _c,mkdirSync as bc}from"fs";import{join as hn,resolve as kc,relative as wc}from"path";import{execSync as gn}from"child_process";var mn=256*1024,Sc=64*1024,yn={id:"core-tools",description:"File read/write, directory listing, shell commands, open URLs, wait for async operations",envKeys:[],tools:[{name:"read_file",description:"Read the contents of a file. Returns the text content.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"}},required:["path"]}},{name:"write_file",description:"Write content to a file. Creates parent directories if needed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"},content:{type:"string",description:"Content to write"}},required:["path","content"]}},{name:"list_directory",description:"List files and directories in a path. Returns names with type indicators (/ for dirs).",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory path (relative to cwd or absolute). Defaults to cwd."}}}},{name:"run_command",description:"Run a shell command and return its output. Use for grep, git, npm, etc.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},cwd:{type:"string",description:"Working directory (optional, defaults to project root)"}},required:["command"]}},{name:"open_url",description:"Open a URL in the user's default browser. Use for OAuth flows, documentation, integration setup pages.",input_schema:{type:"object",properties:{url:{type:"string",description:"URL to open"}},required:["url"]}},{name:"wait",description:"Wait for N seconds. Use this for async operations (tests, builds, deploys) \u2014 wait, then check status again.",input_schema:{type:"object",properties:{seconds:{type:"number",description:"Seconds to wait (default: 5, max: 300)"},reason:{type:"string",description:"Why waiting (for logging/clarity)"}}}}],async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"read_file":return Ic(e,n);case"write_file":return vc(e,n);case"list_directory":return Nc(e,n);case"run_command":return Oc(e,n);case"open_url":return Rc(e);case"wait":return await Tc(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function at(r,e){return kc(e,r)}function Ic(r,e){let t=at(r.path,e),n=fn(t);return n.size>mn?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${mn/1024}KB`}):gc(t,"utf-8")}function vc(r,e){let t=at(r.path,e),n=hn(t,"..");return bc(n,{recursive:!0}),_c(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:wc(e,t)})}function Nc(r,e){let t=at(r.path||".",e);return yc(t).map(i=>{try{return fn(hn(t,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
419
+ `)}function Oc(r,e){let t=r.cwd?at(r.cwd,e):e;return gn(r.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:Sc,stdio:["pipe","pipe","pipe"]})||"(no output)"}function Rc(r){let{url:e}=r;if(!e||!e.startsWith("http://")&&!e.startsWith("https://"))return JSON.stringify({error:"Invalid URL \u2014 must start with http:// or https://"});let t=process.platform,n=t==="darwin"?"open":t==="win32"?"start":"xdg-open";try{return gn(`${n} "${e}"`,{stdio:"ignore",timeout:5e3}),JSON.stringify({ok:!0,opened:e})}catch{return JSON.stringify({ok:!1,error:`Could not open browser. Please visit: ${e}`})}}async function Tc(r,e){let t=Math.min(Math.max(r.seconds||5,1),300),n=r.reason||"async operation",i=500,s=Date.now()+t*1e3;for(;Date.now()<s;){if(e?.aborted)return JSON.stringify({ok:!0,waited:Math.round((t*1e3-(s-Date.now()))/1e3),reason:n,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(i,s-Date.now())))}return JSON.stringify({ok:!0,waited:t,reason:n})}import{existsSync as Ac}from"fs";import{fileURLToPath as xc}from"url";import{dirname as Ec,resolve as $c}from"path";import{resolveIntegrationToken as Ge}from"@zibby/core/backend-client.js";function Lc(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=Ec(xc(import.meta.url)),e=$c(r,"..","bin","mcp-sentry.mjs");return Ac(e)?e:null}function Ke(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function _n(r){let e=r||process.env.SENTRY_ORG;if(!e)throw new Error('Sentry organization not resolved \u2014 reconnect Sentry, or set SENTRY_ORG (self-hosted; the default org slug is "sentry").');return e}async function bn(r,e={}){let{token:t,organizationSlug:n,baseUrl:i}=await Ge("sentry"),s=`${Ke(i)}/api/0/organizations/${_n(n)}${r}`,o={method:e.method||"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}};e.body!=null&&(o.body=typeof e.body=="string"?e.body:JSON.stringify(e.body));let a=await fetch(s,o);if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Sentry API ${a.status}: ${c.slice(0,300)}`)}return a.json()}async function jc(){return bn("/projects/?per_page=50")}async function Pc({query:r="is:unresolved",sort:e="date",project:t,limit:n=25}={}){let i=`/issues/?query=${encodeURIComponent(r)}&sort=${e}&per_page=${n}`;return t&&(i+=`&project=${encodeURIComponent(t)}`),bn(i)}async function Jt(r){let e=String(r??"").trim();if(!e)throw new Error("resolveSentryIssueId: issueRef is required");if(/^\d+$/.test(e))return e;let{token:t,organizationSlug:n,baseUrl:i}=await Ge("sentry"),s=await fetch(`${Ke(i)}/api/0/organizations/${_n(n)}/shortids/${encodeURIComponent(e)}/`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status} resolving shortId "${e}": ${c.slice(0,200)}`)}let o=await s.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${e}" did not resolve to a numeric issue id`);return String(a)}async function Cc(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let e=await Jt(r),{token:t,baseUrl:n}=await Ge("sentry"),i=await fetch(`${Ke(n)}/api/0/issues/${e}/`,{headers:{Authorization:`Bearer ${t}`}});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`Sentry API ${i.status}: ${s.slice(0,300)}`)}return i.json()}async function Uc(r,e={}){if(!r)throw new Error("sentryUpdateIssue: issueId is required");let t={};for(let a of["status","statusDetails","assignedTo","isBookmarked","hasSeen"])e[a]!==void 0&&(t[a]=e[a]);if(Object.keys(t).length===0)throw new Error("sentryUpdateIssue: nothing to update (pass status / statusDetails / assignedTo / isBookmarked / hasSeen)");let n=await Jt(r),{token:i,baseUrl:s}=await Ge("sentry"),o=await fetch(`${Ke(s)}/api/0/issues/${n}/`,{method:"PUT",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===403?new Error(`Sentry API 403 updating issue ${r}: ${a.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access to let Zibby resolve/comment on issues.`):new Error(`Sentry API ${o.status} updating issue ${r}: ${a.slice(0,300)}`)}return o.json()}async function Dc(r,e){if(!r)throw new Error("sentryAddComment: issueId is required");if(!e||!String(e).trim())throw new Error("sentryAddComment: text is required");let t=await Jt(r),{token:n,baseUrl:i}=await Ge("sentry"),s=await fetch(`${Ke(i)}/api/0/issues/${t}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(e)})});if(!s.ok){let o=await s.text().catch(()=>"");throw s.status===403?new Error(`Sentry API 403 commenting on issue ${r}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${s.status} commenting on issue ${r}: ${o.slice(0,300)}`)}return s.json()}var ct={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:N.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
420
420
  You have access to the user's Sentry. Use these tools:
421
421
  - sentry_list_projects: List projects in the organization
422
422
  - sentry_list_issues: List errors/issues (supports Sentry search query, project filter, sort)
423
423
  - sentry_get_issue: Get detailed info about a specific issue (requires issueId)
424
424
  - sentry_update_issue: Change an issue's status (resolved / resolvedInNextRelease / ignored / unresolved / muted), assignment, or bookmark (requires issueId; needs write scope)
425
- - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=Lc();if(!r)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE","ZIBBY_SELF_HOST","SENTRY_URL","SENTRY_ORG","SENTRY_AUTH_TOKEN"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},async handleToolCall(r,e={}){try{switch(r){case"sentry_list_projects":{let t=await jc();return JSON.stringify({projects:t.map(n=>({slug:n.slug,name:n.name,platform:n.platform}))})}case"sentry_list_issues":{let t=await Pc({query:e.query,sort:e.sort,project:e.project,limit:e.limit});return JSON.stringify({issues:t.map(n=>({id:n.id,title:n.title,culprit:n.culprit,count:n.count,firstSeen:n.firstSeen,lastSeen:n.lastSeen,level:n.level,status:n.status}))})}case"sentry_get_issue":{let t=await Cc(e.issueId);return JSON.stringify({id:t.id,title:t.title,culprit:t.culprit,metadata:t.metadata,count:t.count,userCount:t.userCount,firstSeen:t.firstSeen,lastSeen:t.lastSeen,level:t.level,status:t.status,project:{slug:t.project?.slug,name:t.project?.name}})}case"sentry_update_issue":{let t=await Uc(e.issueId,{status:e.status,statusDetails:e.statusDetails,assignedTo:e.assignedTo,isBookmarked:e.isBookmarked,hasSeen:e.hasSeen});return JSON.stringify({ok:!0,id:t.id??e.issueId,status:t.status,assignedTo:t.assignedTo,isBookmarked:t.isBookmarked})}case"sentry_add_comment":{let t=await Dc(e.issueId,e.text);return JSON.stringify({ok:!0,id:t.id,issueId:e.issueId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},toolsForAssistant:[{name:"sentry_list_projects",description:"List Sentry projects",input_schema:{type:"object",properties:{}}},{name:"sentry_list_issues",description:"List Sentry issues (errors)",input_schema:{type:"object",properties:{project:{type:"string",description:"Project slug (optional)"},query:{type:"string",description:"Sentry search query (default: is:unresolved)"},sort:{type:"string",description:"Sort order: date, new, priority, freq, user (default: date)"},limit:{type:"number",description:"Max issues to return (default 25)"}}}},{name:"sentry_get_issue",description:"Get details of a specific Sentry issue",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"}},required:["issueId"]}},{name:"sentry_update_issue",description:"Update a Sentry issue's status, assignment, or bookmark (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},status:{type:"string",description:"resolved | resolvedInNextRelease | unresolved | ignored | muted"},statusDetails:{type:"object",description:'Optional status details, e.g. { "inRelease": "latest" }'},assignedTo:{type:"string",description:'Assignee actor id, e.g. "user:123" or "team:456" (optional)'},isBookmarked:{type:"boolean",description:"Bookmark/unbookmark the issue (optional)"},hasSeen:{type:"boolean",description:"Mark the issue seen/unseen (optional)"}},required:["issueId"]}},{name:"sentry_add_comment",description:"Post a comment/note on a Sentry issue (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},text:{type:"string",description:"Comment body (markdown)"}},required:["issueId","text"]}}]};lt.tools=lt.toolsForAssistant;import{spawn as An}from"child_process";import{writeFileSync as qc,mkdirSync as kn,existsSync as Q,readdirSync as mt,readFileSync as pt,unlinkSync as Jc,createWriteStream as Bc,statSync as Mc}from"fs";import{resolve as _e,join as H}from"path";import{resolveMaxParallelRuns as xn}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Fc}from"@zibby/core/constants/zibby-scratch.js";var Gt="sessions",Kt=".zibby/output",dt=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",Gc=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",En=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",q=new Map,le=[],Kc=0,Mt=0,wn=3e3;function $n(){return`run_${++Kc}_${Date.now().toString(36)}`}function Sn(r){let e=Math.floor(r/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Ln(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function U(r,e,t){if(!Gc)return;let n=`
425
+ - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=Lc();if(!r)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE","ZIBBY_SELF_HOST","SENTRY_URL","SENTRY_ORG","SENTRY_AUTH_TOKEN"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},async handleToolCall(r,e={}){try{switch(r){case"sentry_list_projects":{let t=await jc();return JSON.stringify({projects:t.map(n=>({slug:n.slug,name:n.name,platform:n.platform}))})}case"sentry_list_issues":{let t=await Pc({query:e.query,sort:e.sort,project:e.project,limit:e.limit});return JSON.stringify({issues:t.map(n=>({id:n.id,title:n.title,culprit:n.culprit,count:n.count,firstSeen:n.firstSeen,lastSeen:n.lastSeen,level:n.level,status:n.status}))})}case"sentry_get_issue":{let t=await Cc(e.issueId);return JSON.stringify({id:t.id,title:t.title,culprit:t.culprit,metadata:t.metadata,count:t.count,userCount:t.userCount,firstSeen:t.firstSeen,lastSeen:t.lastSeen,level:t.level,status:t.status,project:{slug:t.project?.slug,name:t.project?.name}})}case"sentry_update_issue":{let t=await Uc(e.issueId,{status:e.status,statusDetails:e.statusDetails,assignedTo:e.assignedTo,isBookmarked:e.isBookmarked,hasSeen:e.hasSeen});return JSON.stringify({ok:!0,id:t.id??e.issueId,status:t.status,assignedTo:t.assignedTo,isBookmarked:t.isBookmarked})}case"sentry_add_comment":{let t=await Dc(e.issueId,e.text);return JSON.stringify({ok:!0,id:t.id,issueId:e.issueId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},toolsForAssistant:[{name:"sentry_list_projects",description:"List Sentry projects",input_schema:{type:"object",properties:{}}},{name:"sentry_list_issues",description:"List Sentry issues (errors)",input_schema:{type:"object",properties:{project:{type:"string",description:"Project slug (optional)"},query:{type:"string",description:"Sentry search query (default: is:unresolved)"},sort:{type:"string",description:"Sort order: date, new, priority, freq, user (default: date)"},limit:{type:"number",description:"Max issues to return (default 25)"}}}},{name:"sentry_get_issue",description:"Get details of a specific Sentry issue",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"}},required:["issueId"]}},{name:"sentry_update_issue",description:"Update a Sentry issue's status, assignment, or bookmark (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},status:{type:"string",description:"resolved | resolvedInNextRelease | unresolved | ignored | muted"},statusDetails:{type:"object",description:'Optional status details, e.g. { "inRelease": "latest" }'},assignedTo:{type:"string",description:'Assignee actor id, e.g. "user:123" or "team:456" (optional)'},isBookmarked:{type:"boolean",description:"Bookmark/unbookmark the issue (optional)"},hasSeen:{type:"boolean",description:"Mark the issue seen/unseen (optional)"}},required:["issueId"]}},{name:"sentry_add_comment",description:"Post a comment/note on a Sentry issue (needs event:write scope)",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"},text:{type:"string",description:"Comment body (markdown)"}},required:["issueId","text"]}}]};ct.tools=ct.toolsForAssistant;import{spawn as An}from"child_process";import{writeFileSync as qc,mkdirSync as kn,existsSync as Q,readdirSync as pt,readFileSync as ut,unlinkSync as Jc,createWriteStream as Bc,statSync as Mc}from"fs";import{resolve as _e,join as H}from"path";import{resolveMaxParallelRuns as xn}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Fc}from"@zibby/core/constants/zibby-scratch.js";var Ft="sessions",Gt=".zibby/output",lt=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",Gc=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",En=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",q=new Map,le=[],Kc=0,Bt=0,wn=3e3;function $n(){return`run_${++Kc}_${Date.now().toString(36)}`}function Sn(r){let e=Math.floor(r/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Ln(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function U(r,e,t){if(!Gc)return;let n=`
426
426
  ${e} [${r}] ${t}
427
- `;try{process.stderr.write(n)}catch{}}function Ht(){le.length=0;for(let[,r]of q)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",Ht);process.on("SIGINT",()=>{Ht(),process.exit(0)});process.on("SIGTERM",()=>{Ht(),process.exit(0)});var jn={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
427
+ `;try{process.stderr.write(n)}catch{}}function Kt(){le.length=0;for(let[,r]of q)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",Kt);process.on("SIGINT",()=>{Kt(),process.exit(0)});process.on("SIGTERM",()=>{Kt(),process.exit(0)});var jn={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
428
428
  You can run zibby test workflows directly from chat:
429
429
 
430
430
  **CRITICAL: When user asks to test a ticket:**
@@ -561,14 +561,14 @@ Each run generates:
561
561
  - events.json: All browser events
562
562
  - raw_stream_output.txt: Agent log
563
563
 
564
- Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"run_generate":return await Hc(e,n);case"run_test":return await Qc(e,n,t);case"run_status":return Xc(e);case"run_cancel":return el(e);case"run_artifacts":return nl(e,n);case"run_diagnose":return il(e,n);case"list_specs":return sl(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"run_generate",description:"Generate specs from codebase. CRITICAL: DO NOT USE if ticket has test steps in comments. Only use when: (1) NO steps in ticket AND (2) local codebase exists (not external URLs). For tickets with steps, use run_test with inline format.",input_schema:{type:"object",properties:{ticket:{type:"string",description:"Jira ticket key (e.g. SCRUM-123). Auto-fetches ticket details."},description:{type:"string",description:"Ticket description text (use if no Jira key available)"},input:{type:"string",description:"Path to a file containing ticket/requirements text"},repo:{type:"string",description:"Path to the codebase (default: current directory)"},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},output:{type:"string",description:"Output directory for spec files (default: test-specs)"}}}},{name:"run_test",description:"Start a test (async, returns runId). spec = file path, or inline:+steps, or a Jira-shaped issue key (e.g. PROJ-123): when Jira is connected, the runner loads that issue's description+comments into an inline spec. After starting, tell the user and let them ask for progress via run_status.",input_schema:{type:"object",properties:{spec:{type:"string",description:"Workspace file path; or inline:+steps; or Jira issue key (KEY-123) to auto-fetch from Jira when the jira skill is active."},ticketKey:{type:"string",description:"Optional label (e.g. SCRUM-123). If spec is an issue key, this defaults to that key."},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},headless:{type:"boolean",description:"Run browser headless (default false)"},workflow:{type:"string",description:"Workflow override (e.g. quick-smoke)"}},required:["spec"]}},{name:"run_status",description:'Instant progress check \u2014 returns immediately. Use this whenever user asks about test progress. ALWAYS use runId="all".',input_schema:{type:"object",properties:{runId:{type:"string",description:'Use "all" to see all runs in this session (recommended). Or a specific run ID if known.'}},required:["runId"]}},{name:"run_cancel",description:'Cancel/kill a running test. ONLY use when the USER explicitly asks to cancel or stop a run. NEVER auto-cancel \u2014 tests take 1-5 minutes and "running" is normal. Use runId="all" to cancel all active runs.',input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID to cancel, or "all" to cancel all active runs'}},required:["runId"]}},{name:"run_artifacts",description:"Read artifacts from a test run session. Can list files, read results/events/logs, or search across all sessions.",input_schema:{type:"object",properties:{runId:{type:"string",description:"Run ID from run_test. Omit to search across all sessions."},type:{type:"string",enum:["list","result","events","log","search"],description:'What to retrieve: "list" = all files in session, "result" = result.json, "events" = events.json, "log" = raw output tail, "search" = search text across sessions'},node:{type:"string",description:'Node name to read from (e.g. "execute_live", "generate_script"). Default: "execute_live"'},query:{type:"string",description:'Search text (only for type="search"). Searches across all session logs/events.'},tail:{type:"number",description:"Number of characters from end of log to return (default: 3000)"}},required:["type"]}},{name:"run_diagnose",description:"Diagnose one or all runs, especially failed ones. Uses run logs + known error patterns and returns likely root cause with suggested next action.",input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID from run_test, or "all" (default) to diagnose all known runs'},tail:{type:"number",description:"Characters of run log tail to inspect (default: 2000)"}}}},{name:"list_specs",description:"List available test spec files in the project",input_schema:{type:"object",properties:{directory:{type:"string",description:'Directory to scan (default: "test-specs")'}}}}]};function Ft(){let r=0;for(let[,e]of q)e.status==="running"&&r++;return r}function In(){for(;le.length>0;){let r=xn(le[0]?.context?.options?.config);if(Ft()>=r)break;let{args:e,cwd:t,context:n}=le.shift();Pn(e,t,n)}}async function Hc(r,e){let{ticket:t,description:n,input:i,repo:s,agent:o,output:a}=r,c=["generate"];t&&c.push("--ticket",t),n&&c.push("--description",n),i&&c.push("--input",i),s&&c.push("--repo",s),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,u=l&&d.includes(l)?l:null;u&&c.push("--agent",u);let p=t||"generate";return U(p,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{En&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(_=>/\s/.test(_)?JSON.stringify(_):_).join(" ")} cwd=${e}`);let f=An("zibby",c,{cwd:e,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",y="";f.stdout.on("data",_=>{let b=_.toString();h+=b;for(let g of b.split(`
565
- `)){let w=Ln(g).trim();w.startsWith("\u2705")?U(p,"\u2705",w.slice(2).trim()):w.startsWith("\u2713")&&U(p,"\u2714",w.slice(2).trim())}}),f.stderr.on("data",_=>{y+=_.toString()}),f.on("close",_=>{if(_!==0){U(p,"\u274C",`Generation failed (exit ${_})`),m(JSON.stringify({error:`zibby generate failed with exit code ${_}`,stderr:y.slice(-1e3)}));return}let b=_e(e,a||"test-specs"),g=[];try{let w=t?t.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";g=mt(b).filter(T=>T.endsWith(".txt")&&(!w||T.startsWith(w))).map(T=>H(b,T))}catch{}U(p,"\u2705",`Generated ${g.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:t||null,specFiles:g.map(w=>w.replace(`${e}/`,"")),total:g.length,message:`Generated ${g.length} specs. Now call run_test for each file.`}))}),f.on("error",_=>{U(p,"\u274C",`Spawn error: ${_.message}`),m(JSON.stringify({error:_.message}))})})}var vn=1e5,Nn=/^[A-Z][A-Z0-9]+-\d+$/,zc=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Wc(r,e){if(!e||!e.length)return r;let t=r;for(let n of e)n.type==="strong"?t=`**${t}**`:n.type==="em"?t=`_${t}_`:n.type==="code"?t=`\`${t}\``:n.type==="strike"?t=`~~${t}~~`:n.type==="link"&&n.attrs?.href&&(t=`[${t}](${n.attrs.href})`);return t}function ut(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(Wc(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
564
+ Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"run_generate":return await Hc(e,n);case"run_test":return await Qc(e,n,t);case"run_status":return Xc(e);case"run_cancel":return el(e);case"run_artifacts":return nl(e,n);case"run_diagnose":return il(e,n);case"list_specs":return sl(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"run_generate",description:"Generate specs from codebase. CRITICAL: DO NOT USE if ticket has test steps in comments. Only use when: (1) NO steps in ticket AND (2) local codebase exists (not external URLs). For tickets with steps, use run_test with inline format.",input_schema:{type:"object",properties:{ticket:{type:"string",description:"Jira ticket key (e.g. SCRUM-123). Auto-fetches ticket details."},description:{type:"string",description:"Ticket description text (use if no Jira key available)"},input:{type:"string",description:"Path to a file containing ticket/requirements text"},repo:{type:"string",description:"Path to the codebase (default: current directory)"},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},output:{type:"string",description:"Output directory for spec files (default: test-specs)"}}}},{name:"run_test",description:"Start a test (async, returns runId). spec = file path, or inline:+steps, or a Jira-shaped issue key (e.g. PROJ-123): when Jira is connected, the runner loads that issue's description+comments into an inline spec. After starting, tell the user and let them ask for progress via run_status.",input_schema:{type:"object",properties:{spec:{type:"string",description:"Workspace file path; or inline:+steps; or Jira issue key (KEY-123) to auto-fetch from Jira when the jira skill is active."},ticketKey:{type:"string",description:"Optional label (e.g. SCRUM-123). If spec is an issue key, this defaults to that key."},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},headless:{type:"boolean",description:"Run browser headless (default false)"},workflow:{type:"string",description:"Workflow override (e.g. quick-smoke)"}},required:["spec"]}},{name:"run_status",description:'Instant progress check \u2014 returns immediately. Use this whenever user asks about test progress. ALWAYS use runId="all".',input_schema:{type:"object",properties:{runId:{type:"string",description:'Use "all" to see all runs in this session (recommended). Or a specific run ID if known.'}},required:["runId"]}},{name:"run_cancel",description:'Cancel/kill a running test. ONLY use when the USER explicitly asks to cancel or stop a run. NEVER auto-cancel \u2014 tests take 1-5 minutes and "running" is normal. Use runId="all" to cancel all active runs.',input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID to cancel, or "all" to cancel all active runs'}},required:["runId"]}},{name:"run_artifacts",description:"Read artifacts from a test run session. Can list files, read results/events/logs, or search across all sessions.",input_schema:{type:"object",properties:{runId:{type:"string",description:"Run ID from run_test. Omit to search across all sessions."},type:{type:"string",enum:["list","result","events","log","search"],description:'What to retrieve: "list" = all files in session, "result" = result.json, "events" = events.json, "log" = raw output tail, "search" = search text across sessions'},node:{type:"string",description:'Node name to read from (e.g. "execute_live", "generate_script"). Default: "execute_live"'},query:{type:"string",description:'Search text (only for type="search"). Searches across all session logs/events.'},tail:{type:"number",description:"Number of characters from end of log to return (default: 3000)"}},required:["type"]}},{name:"run_diagnose",description:"Diagnose one or all runs, especially failed ones. Uses run logs + known error patterns and returns likely root cause with suggested next action.",input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID from run_test, or "all" (default) to diagnose all known runs'},tail:{type:"number",description:"Characters of run log tail to inspect (default: 2000)"}}}},{name:"list_specs",description:"List available test spec files in the project",input_schema:{type:"object",properties:{directory:{type:"string",description:'Directory to scan (default: "test-specs")'}}}}]};function Mt(){let r=0;for(let[,e]of q)e.status==="running"&&r++;return r}function In(){for(;le.length>0;){let r=xn(le[0]?.context?.options?.config);if(Mt()>=r)break;let{args:e,cwd:t,context:n}=le.shift();Pn(e,t,n)}}async function Hc(r,e){let{ticket:t,description:n,input:i,repo:s,agent:o,output:a}=r,c=["generate"];t&&c.push("--ticket",t),n&&c.push("--description",n),i&&c.push("--input",i),s&&c.push("--repo",s),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,u=l&&d.includes(l)?l:null;u&&c.push("--agent",u);let p=t||"generate";return U(p,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{En&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(_=>/\s/.test(_)?JSON.stringify(_):_).join(" ")} cwd=${e}`);let f=An("zibby",c,{cwd:e,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",y="";f.stdout.on("data",_=>{let b=_.toString();h+=b;for(let g of b.split(`
565
+ `)){let w=Ln(g).trim();w.startsWith("\u2705")?U(p,"\u2705",w.slice(2).trim()):w.startsWith("\u2713")&&U(p,"\u2714",w.slice(2).trim())}}),f.stderr.on("data",_=>{y+=_.toString()}),f.on("close",_=>{if(_!==0){U(p,"\u274C",`Generation failed (exit ${_})`),m(JSON.stringify({error:`zibby generate failed with exit code ${_}`,stderr:y.slice(-1e3)}));return}let b=_e(e,a||"test-specs"),g=[];try{let w=t?t.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";g=pt(b).filter(T=>T.endsWith(".txt")&&(!w||T.startsWith(w))).map(T=>H(b,T))}catch{}U(p,"\u2705",`Generated ${g.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:t||null,specFiles:g.map(w=>w.replace(`${e}/`,"")),total:g.length,message:`Generated ${g.length} specs. Now call run_test for each file.`}))}),f.on("error",_=>{U(p,"\u274C",`Spawn error: ${_.message}`),m(JSON.stringify({error:_.message}))})})}var vn=1e5,Nn=/^[A-Z][A-Z0-9]+-\d+$/,zc=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Wc(r,e){if(!e||!e.length)return r;let t=r;for(let n of e)n.type==="strong"?t=`**${t}**`:n.type==="em"?t=`_${t}_`:n.type==="code"?t=`\`${t}\``:n.type==="strike"?t=`~~${t}~~`:n.type==="link"&&n.attrs?.href&&(t=`[${t}](${n.attrs.href})`);return t}function dt(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(Wc(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
566
566
  `);continue}if(n.type==="rule"){t.push(`
567
567
  ---
568
- `);continue}let i=n.content?ut(n.content,e+1):"";if(n.type==="listItem")t.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${ut(o.content||[],e+1).trim()}`);t.push(`
568
+ `);continue}let i=n.content?dt(n.content,e+1):"";if(n.type==="listItem")t.push(i);else if(n.type==="bulletList"){let s=(n.content||[]).map(o=>`- ${dt(o.content||[],e+1).trim()}`);t.push(`
569
569
  ${s.join(`
570
570
  `)}
571
- `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${ut(o.content||[],e+1).trim()}`);t.push(`
571
+ `)}else if(n.type==="orderedList"){let s=(n.content||[]).map((o,a)=>`${a+1}. ${dt(o.content||[],e+1).trim()}`);t.push(`
572
572
  ${s.join(`
573
573
  `)}
574
574
  `)}else if(n.type==="heading"){let s=n.attrs?.level||2;t.push(`
@@ -580,16 +580,16 @@ ${"#".repeat(s)} ${i.trim()}
580
580
  ${i}
581
581
  `):t.push(i)}return t.join("").replace(/\n{3,}/g,`
582
582
 
583
- `)}function Yc(r){return r==null||r===""?"":typeof r=="string"?r.trim():typeof r=="object"&&Array.isArray(r.content)?ut(r.content).trim():""}async function Zc(r){let{getSkill:e}=await import("@zibby/agent-workflow"),t=e("jira");if(!t||typeof t.handleToolCall!="function")return null;try{let n=await t.handleToolCall("jira_get_issue",{issueKey:r}),i=JSON.parse(n);if(i?.error)return null;let s=await t.handleToolCall("jira_get_comments",{issueKey:r,maxResults:50}),o=JSON.parse(s);if(o?.error)return null;let a=Yc(i.description),c=[];a&&c.push(a);let d=Array.isArray(o.comments)?o.comments:[];if(d.length>0){let u=d.map(p=>String(p.body||"").trim()).filter(Boolean).join(`
583
+ `)}function Yc(r){return r==null||r===""?"":typeof r=="string"?r.trim():typeof r=="object"&&Array.isArray(r.content)?dt(r.content).trim():""}async function Zc(r){let{getSkill:e}=await import("@zibby/agent-workflow"),t=e("jira");if(!t||typeof t.handleToolCall!="function")return null;try{let n=await t.handleToolCall("jira_get_issue",{issueKey:r}),i=JSON.parse(n);if(i?.error)return null;let s=await t.handleToolCall("jira_get_comments",{issueKey:r,maxResults:50}),o=JSON.parse(s);if(o?.error)return null;let a=Yc(i.description),c=[];a&&c.push(a);let d=Array.isArray(o.comments)?o.comments:[];if(d.length>0){let u=d.map(p=>String(p.body||"").trim()).filter(Boolean).join(`
584
584
 
585
585
  `);u&&c.push(u)}let l=c.join(`
586
586
 
587
587
  `).trim();return l?(l.length>vn&&(l=`${l.slice(0,vn)}
588
588
 
589
- ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function Vc(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function Qc(r,e,t){let n={...r},i=String(n.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let s=null;if(Nn.test(i)&&!i.startsWith("inline:")){let l=await Zc(i);l&&(i=l.inlineSpec,n.spec=i,String(n.ticketKey||"").trim()||(n.ticketKey=l.issueKey),s=l.issueKey)}let o=String(n.ticketKey||"").trim();if(o){for(let[l,u]of q.entries())if(u?.ticketKey===o&&!(u?.status!=="running"&&u?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:u.status,reused:!0,message:`A run for ${o} is already ${u.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let l=_e(e,i);if(!Q(l))return Nn.test(i)?JSON.stringify({error:`Invalid run_test spec: "${i}" is an issue id, not a spec.`,reason:"Jira auto-load was attempted but did not return usable text, or Jira is not configured.",doNext:["Confirm the jira skill is active and authenticated.",'Or call tracker tools yourself, then run_test with spec: "inline:" + steps.'],validExample:{spec:"inline:1. Open https://example.com \u2026 2. Verify \u2026",ticketKey:i},invalidExample:{spec:i,ticketKey:i}}):JSON.stringify({error:`Test spec not found: ${i}`,hint:'If this should be issue steps, load the issue with your tracker tools first, then run_test with spec: "inline:" + steps. Otherwise use a real file path.'})}let a=xn(t?.options?.config);if(Ft()>=a){let l=$n(),u=n.ticketKey||l,p={runId:l,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};q.set(l,p),le.push({args:{...n,_queuedRunId:l},cwd:e,context:t}),U(u,"\u23F3",`Queued (${Ft()}/${a} running, ${le.length} queued)`);let m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return s&&(m.resolvedFromJiraIssue=s,m.message+=` (spec built from Jira ${s})`),JSON.stringify(m)}let c=Date.now()-Mt;c<wn&&Mt>0&&await new Promise(l=>setTimeout(l,wn-c)),Mt=Date.now();let d=Pn(n,e,t);return s?Vc(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function Pn(r,e,t){let{spec:n,ticketKey:i,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||$n(),l=n,u=!1;if(n.startsWith("inline:")){u=!0;let R=Fc(e);kn(R,{recursive:!0}),l=H(R,`${d}.txt`),qc(l,n.slice(7).trim(),"utf-8")}let p=_e(e,".zibby","output","runs");kn(p,{recursive:!0});let m=H(p,`${d}.log`),f=Bc(m,{flags:"a"}),y=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,_=["test",l];y&&_.push("--agent",y),o&&_.push("--headless"),a&&_.push("--workflow",a),En&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${_.map(R=>/\s/.test(R)?JSON.stringify(R):R).join(" ")} cwd=${e}`);let b=An("zibby",_,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),g={runId:d,spec:i?`${i}: ${n}`:n,ticketKey:i||null,specPath:l,logPath:m,isInline:u,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},w=i||d,T="";function F(R){let O=Ln(R).trim();if(!O)return;if(O.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let x=JSON.parse(O.slice(22));x.phase==="node_begin"?g.currentNode=x.node:x.phase==="node_end"&&(x.node&&!g.completedNodes.includes(x.node)&&g.completedNodes.push(x.node),g.currentNode===x.node&&(g.currentNode=null))}catch{}return}let D=O.match(/Session\s+(\S+)/);if(D&&!g.sessionId&&(g.sessionId=D[1],g.sessionPath=_e(e,Kt,Gt,g.sessionId)),O.startsWith("\u250C ")||O.startsWith("\u250C ")){let x=O.slice(2).trim();g.currentNode=x,dt&&U(w,"\u25B6",`${x}`)}else if(O.startsWith("\u2514 ")||O.startsWith("\u2514 ")){let x=O.slice(2).trim();x.startsWith("done")?(g.currentNode&&!g.completedNodes.includes(g.currentNode)&&g.completedNodes.push(g.currentNode),dt&&U(w,"\u2714",`${g.currentNode||"node"} done ${x.replace("done","").trim()}`),g.currentNode=null):x.startsWith("failed")&&(dt&&U(w,"\u2718",`${g.currentNode||"node"} failed ${x.replace("failed","").trim()}`),g.currentNode=null)}else O.includes("Workflow completed")&&(g.currentNode=null,dt&&U(w,"\u2714",`Workflow completed (${Sn(Date.now()-g.startTime)})`))}function Ie(R){let O=R.toString();g.output+=O,f.write(O),g.output.length>5e4&&(g.output=g.output.slice(-3e4)),T+=O;let D=T.split(`
589
+ ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function Vc(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function Qc(r,e,t){let n={...r},i=String(n.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let s=null;if(Nn.test(i)&&!i.startsWith("inline:")){let l=await Zc(i);l&&(i=l.inlineSpec,n.spec=i,String(n.ticketKey||"").trim()||(n.ticketKey=l.issueKey),s=l.issueKey)}let o=String(n.ticketKey||"").trim();if(o){for(let[l,u]of q.entries())if(u?.ticketKey===o&&!(u?.status!=="running"&&u?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:u.status,reused:!0,message:`A run for ${o} is already ${u.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let l=_e(e,i);if(!Q(l))return Nn.test(i)?JSON.stringify({error:`Invalid run_test spec: "${i}" is an issue id, not a spec.`,reason:"Jira auto-load was attempted but did not return usable text, or Jira is not configured.",doNext:["Confirm the jira skill is active and authenticated.",'Or call tracker tools yourself, then run_test with spec: "inline:" + steps.'],validExample:{spec:"inline:1. Open https://example.com \u2026 2. Verify \u2026",ticketKey:i},invalidExample:{spec:i,ticketKey:i}}):JSON.stringify({error:`Test spec not found: ${i}`,hint:'If this should be issue steps, load the issue with your tracker tools first, then run_test with spec: "inline:" + steps. Otherwise use a real file path.'})}let a=xn(t?.options?.config);if(Mt()>=a){let l=$n(),u=n.ticketKey||l,p={runId:l,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};q.set(l,p),le.push({args:{...n,_queuedRunId:l},cwd:e,context:t}),U(u,"\u23F3",`Queued (${Mt()}/${a} running, ${le.length} queued)`);let m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return s&&(m.resolvedFromJiraIssue=s,m.message+=` (spec built from Jira ${s})`),JSON.stringify(m)}let c=Date.now()-Bt;c<wn&&Bt>0&&await new Promise(l=>setTimeout(l,wn-c)),Bt=Date.now();let d=Pn(n,e,t);return s?Vc(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function Pn(r,e,t){let{spec:n,ticketKey:i,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||$n(),l=n,u=!1;if(n.startsWith("inline:")){u=!0;let R=Fc(e);kn(R,{recursive:!0}),l=H(R,`${d}.txt`),qc(l,n.slice(7).trim(),"utf-8")}let p=_e(e,".zibby","output","runs");kn(p,{recursive:!0});let m=H(p,`${d}.log`),f=Bc(m,{flags:"a"}),y=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,_=["test",l];y&&_.push("--agent",y),o&&_.push("--headless"),a&&_.push("--workflow",a),En&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${_.map(R=>/\s/.test(R)?JSON.stringify(R):R).join(" ")} cwd=${e}`);let b=An("zibby",_,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),g={runId:d,spec:i?`${i}: ${n}`:n,ticketKey:i||null,specPath:l,logPath:m,isInline:u,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},w=i||d,T="";function F(R){let O=Ln(R).trim();if(!O)return;if(O.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let x=JSON.parse(O.slice(22));x.phase==="node_begin"?g.currentNode=x.node:x.phase==="node_end"&&(x.node&&!g.completedNodes.includes(x.node)&&g.completedNodes.push(x.node),g.currentNode===x.node&&(g.currentNode=null))}catch{}return}let D=O.match(/Session\s+(\S+)/);if(D&&!g.sessionId&&(g.sessionId=D[1],g.sessionPath=_e(e,Gt,Ft,g.sessionId)),O.startsWith("\u250C ")||O.startsWith("\u250C ")){let x=O.slice(2).trim();g.currentNode=x,lt&&U(w,"\u25B6",`${x}`)}else if(O.startsWith("\u2514 ")||O.startsWith("\u2514 ")){let x=O.slice(2).trim();x.startsWith("done")?(g.currentNode&&!g.completedNodes.includes(g.currentNode)&&g.completedNodes.push(g.currentNode),lt&&U(w,"\u2714",`${g.currentNode||"node"} done ${x.replace("done","").trim()}`),g.currentNode=null):x.startsWith("failed")&&(lt&&U(w,"\u2718",`${g.currentNode||"node"} failed ${x.replace("failed","").trim()}`),g.currentNode=null)}else O.includes("Workflow completed")&&(g.currentNode=null,lt&&U(w,"\u2714",`Workflow completed (${Sn(Date.now()-g.startTime)})`))}function Ie(R){let O=R.toString();g.output+=O,f.write(O),g.output.length>5e4&&(g.output=g.output.slice(-3e4)),T+=O;let D=T.split(`
590
590
  `);T=D.pop();for(let x of D)F(x)}return b.stdout.on("data",Ie),b.stderr.on("data",R=>{let O=R.toString();g.error+=O,f.write(O),g.error.length>2e4&&(g.error=g.error.slice(-1e4))}),b.on("close",R=>{g.status=R===0?"passed":"failed",g.exitCode=R,g.endTime=Date.now(),T&&F(T),f.end();let O=Sn(Date.now()-g.startTime);if(R===0?U(w,"\u2705",`Passed (${O})`):U(w,"\u274C",`Failed (${O})`),g.isInline)try{Jc(g.specPath)}catch{}In()}),b.on("error",R=>{g.status="error",g.error+=`
591
- Spawn error: ${R.message}`,U(w,"\u274C",`Spawn error: ${R.message}`),f.end(),In()}),g._child=b,q.set(d,g),JSON.stringify({runId:d,spec:g.spec,ticketKey:g.ticketKey,status:"running",pid:b.pid,logFile:m})}function On(r){let e=Math.round(((r.endTime||Date.now())-r.startTime)/1e3),t=r.completedNodes||[],n=r.currentNode||null;if(r.status!=="running")return{elapsed:e,stage:r.status,completedNodes:t,currentNode:null};let i;return n?(i=`Actively executing node "${n}"`,t.length&&(i+=` (completed: ${t.join(", ")})`)):t.length?i=`Between nodes (completed: ${t.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${e}s. This is normal progress \u2014 do not cancel.`,{elapsed:e,stage:"running",currentNode:n,completedNodes:t,progress:i}}function Xc(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let s=[...q.entries()].map(([l,u])=>{let p=On(u),m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:u.status,elapsed:p.elapsed,exitCode:u.exitCode,sessionId:u.sessionId||null};return u.status==="running"?(m.currentNode=p.currentNode,m.completedNodes=p.completedNodes,m.progress=p.progress):m.outputTail=u.output.slice(-500),m}),o=s.filter(l=>l.status==="running").length,a=s.filter(l=>l.status==="passed").length,c=s.filter(l=>l.status==="failed").length,d={total:s.length,running:o,passed:a,failed:c,runs:s};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let t=q.get(e);if(!t)return JSON.stringify({error:`Run not found: ${e}`});let n=On(t),i={runId:e,spec:t.spec,ticketKey:t.ticketKey,status:t.status,elapsed:n.elapsed,exitCode:t.exitCode,sessionId:t.sessionId||null};return t.status==="running"?(i.currentNode=n.currentNode,i.completedNodes=n.completedNodes,i.progress=n.progress):(i.outputTail=t.output.slice(-1e3),i.errorTail=t.error.slice(-500)),t.status==="running"&&(i._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(i)}function Rn(r,e){if(e.status==="queued"){let t=le.findIndex(n=>n.args._queuedRunId===r);return t>=0&&le.splice(t,1),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}if(e.status!=="running")return{ok:!1,runId:r,error:`Run is not active (status: ${e.status})`};try{return e._child.kill("SIGTERM"),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}catch(t){return{ok:!1,runId:r,error:`Failed to cancel: ${t.message}`}}}function el(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let n=[];for(let[i,s]of q.entries())(s.status==="running"||s.status==="queued")&&n.push(Rn(i,s));return n.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:n.length,results:n})}let t=q.get(e);return JSON.stringify(t?Rn(e,t):{error:`Run not found: ${e}`})}function tl(r,e){let t=q.get(r);if(t?.sessionPath&&Q(t.sessionPath))return t.sessionPath;if(t?.sessionId){let n=_e(e,Kt,Gt,t.sessionId);if(Q(n))return n}return null}function Cn(r,e=""){let t=[];if(!Q(r))return t;for(let n of mt(r,{withFileTypes:!0})){let i=e?`${e}/${n.name}`:n.name;if(n.isDirectory())t.push(...Cn(H(r,n.name),i));else{let s=Mc(H(r,n.name));t.push({path:i,size:s.size})}}return t}function Tn(r){if(!Q(r))return null;try{return JSON.parse(pt(r,"utf-8"))}catch{return null}}function Un(r,e=2e3){if(!r||!Q(r))return"";try{return pt(r,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function rl({run:r,logTail:e,errorTail:t}){let i=`${e||""}
592
- ${t||""}`.toLowerCase(),s={runId:r?.runId||null,status:r?.status||null,exitCode:r?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return r?.status==="running"||r?.status==="queued"?{...s,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:i.includes("test spec not found")?{...s,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:i.includes("unknown command")&&i.includes("'run'")?{...s,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:i.includes("missing openai_api_key")||i.includes("didn't provide an api key")||i.includes("401")?{...s,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:i.includes("spawn error")||i.includes("enoent")?{...s,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:i.includes("security command failed")||i.includes("security process exited with code: 45")||i.includes("password not found for account")?{...s,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:s}function nl(r,e){let{runId:t,type:n,node:i="execute_live",query:s,tail:o=3e3}=r;if(n==="search"){if(!s)return JSON.stringify({error:'query is required for type="search"'});let c=_e(e,Kt,Gt);if(!Q(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=s.toLowerCase();for(let u of mt(c,{withFileTypes:!0})){if(!u.isDirectory())continue;let p=H(c,u.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let y=H(p,f);if(Q(y))try{let _=pt(y,"utf-8");if(_.toLowerCase().includes(l)){let b=_.toLowerCase().indexOf(l),g=Math.max(0,b-100),w=Math.min(_.length,b+s.length+100);d.push({sessionId:u.name,artifact:h,snippet:_.slice(g,w)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:s,matches:d,total:d.length})}if(!t)return JSON.stringify({error:"runId is required for this type"});if(n==="log"){let c=q.get(t),d=Un(c?.logPath,o);if(d)return JSON.stringify({runId:t,source:"run-log",totalLength:d.length,tail:d})}let a=tl(t,e);if(!a)return JSON.stringify({error:`No session found for run ${t}. The run may still be starting.`});switch(n){case"list":{let c=Cn(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=Tn(H(a,i,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:i,result:c}:{error:`No result.json found in ${i}`})}case"events":{let c=Tn(H(a,i,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${i}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=H(a,i,"raw_stream_output.txt");if(!Q(c))return JSON.stringify({error:`No log found in ${i}`});let d=pt(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 il(r,e){let t=String(r?.runId||"all"),n=Number(r?.tail||2e3),i=t==="all"?[...q.keys()]:[t];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let s=i.map(c=>{let d=q.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=Un(d.logPath,n),u=String(d.error||"").slice(-Math.max(200,n));return{...rl({run:d,logTail:l,errorTail:u}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:u}}),o=s.filter(c=>c.status==="failed"||c.status==="error"),a=s.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:s.length,failed:o.length,active:a.length,diagnoses:s})}function sl(r,e){let t=r?.directory||"test-specs",n=_e(e,t);if(!Q(n))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let s=function(o,a){for(let c of mt(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(H(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&i.push(d)}},i=[];return s(n,""),JSON.stringify({specs:i.map(o=>`${t}/${o}`),total:i.length,directory:t})}catch(i){return JSON.stringify({error:i.message})}}import{spawn as ol}from"child_process";import{existsSync as X,mkdirSync as al,readdirSync as Dn,statSync as cl,readFileSync as ll}from"fs";import{resolve as zt,join as ee,basename as dl}from"path";var Wt=".zibby/repos";function ft(r,e,t={}){return new Promise((n,i)=>{let s=ol(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),s.on("error",c=>i(c))})}var de={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
591
+ Spawn error: ${R.message}`,U(w,"\u274C",`Spawn error: ${R.message}`),f.end(),In()}),g._child=b,q.set(d,g),JSON.stringify({runId:d,spec:g.spec,ticketKey:g.ticketKey,status:"running",pid:b.pid,logFile:m})}function On(r){let e=Math.round(((r.endTime||Date.now())-r.startTime)/1e3),t=r.completedNodes||[],n=r.currentNode||null;if(r.status!=="running")return{elapsed:e,stage:r.status,completedNodes:t,currentNode:null};let i;return n?(i=`Actively executing node "${n}"`,t.length&&(i+=` (completed: ${t.join(", ")})`)):t.length?i=`Between nodes (completed: ${t.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${e}s. This is normal progress \u2014 do not cancel.`,{elapsed:e,stage:"running",currentNode:n,completedNodes:t,progress:i}}function Xc(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let s=[...q.entries()].map(([l,u])=>{let p=On(u),m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:u.status,elapsed:p.elapsed,exitCode:u.exitCode,sessionId:u.sessionId||null};return u.status==="running"?(m.currentNode=p.currentNode,m.completedNodes=p.completedNodes,m.progress=p.progress):m.outputTail=u.output.slice(-500),m}),o=s.filter(l=>l.status==="running").length,a=s.filter(l=>l.status==="passed").length,c=s.filter(l=>l.status==="failed").length,d={total:s.length,running:o,passed:a,failed:c,runs:s};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let t=q.get(e);if(!t)return JSON.stringify({error:`Run not found: ${e}`});let n=On(t),i={runId:e,spec:t.spec,ticketKey:t.ticketKey,status:t.status,elapsed:n.elapsed,exitCode:t.exitCode,sessionId:t.sessionId||null};return t.status==="running"?(i.currentNode=n.currentNode,i.completedNodes=n.completedNodes,i.progress=n.progress):(i.outputTail=t.output.slice(-1e3),i.errorTail=t.error.slice(-500)),t.status==="running"&&(i._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(i)}function Rn(r,e){if(e.status==="queued"){let t=le.findIndex(n=>n.args._queuedRunId===r);return t>=0&&le.splice(t,1),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}if(e.status!=="running")return{ok:!1,runId:r,error:`Run is not active (status: ${e.status})`};try{return e._child.kill("SIGTERM"),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}catch(t){return{ok:!1,runId:r,error:`Failed to cancel: ${t.message}`}}}function el(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let n=[];for(let[i,s]of q.entries())(s.status==="running"||s.status==="queued")&&n.push(Rn(i,s));return n.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:n.length,results:n})}let t=q.get(e);return JSON.stringify(t?Rn(e,t):{error:`Run not found: ${e}`})}function tl(r,e){let t=q.get(r);if(t?.sessionPath&&Q(t.sessionPath))return t.sessionPath;if(t?.sessionId){let n=_e(e,Gt,Ft,t.sessionId);if(Q(n))return n}return null}function Cn(r,e=""){let t=[];if(!Q(r))return t;for(let n of pt(r,{withFileTypes:!0})){let i=e?`${e}/${n.name}`:n.name;if(n.isDirectory())t.push(...Cn(H(r,n.name),i));else{let s=Mc(H(r,n.name));t.push({path:i,size:s.size})}}return t}function Tn(r){if(!Q(r))return null;try{return JSON.parse(ut(r,"utf-8"))}catch{return null}}function Un(r,e=2e3){if(!r||!Q(r))return"";try{return ut(r,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function rl({run:r,logTail:e,errorTail:t}){let i=`${e||""}
592
+ ${t||""}`.toLowerCase(),s={runId:r?.runId||null,status:r?.status||null,exitCode:r?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return r?.status==="running"||r?.status==="queued"?{...s,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:i.includes("test spec not found")?{...s,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:i.includes("unknown command")&&i.includes("'run'")?{...s,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:i.includes("missing openai_api_key")||i.includes("didn't provide an api key")||i.includes("401")?{...s,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:i.includes("spawn error")||i.includes("enoent")?{...s,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:i.includes("security command failed")||i.includes("security process exited with code: 45")||i.includes("password not found for account")?{...s,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:s}function nl(r,e){let{runId:t,type:n,node:i="execute_live",query:s,tail:o=3e3}=r;if(n==="search"){if(!s)return JSON.stringify({error:'query is required for type="search"'});let c=_e(e,Gt,Ft);if(!Q(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=s.toLowerCase();for(let u of pt(c,{withFileTypes:!0})){if(!u.isDirectory())continue;let p=H(c,u.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let y=H(p,f);if(Q(y))try{let _=ut(y,"utf-8");if(_.toLowerCase().includes(l)){let b=_.toLowerCase().indexOf(l),g=Math.max(0,b-100),w=Math.min(_.length,b+s.length+100);d.push({sessionId:u.name,artifact:h,snippet:_.slice(g,w)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:s,matches:d,total:d.length})}if(!t)return JSON.stringify({error:"runId is required for this type"});if(n==="log"){let c=q.get(t),d=Un(c?.logPath,o);if(d)return JSON.stringify({runId:t,source:"run-log",totalLength:d.length,tail:d})}let a=tl(t,e);if(!a)return JSON.stringify({error:`No session found for run ${t}. The run may still be starting.`});switch(n){case"list":{let c=Cn(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=Tn(H(a,i,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:i,result:c}:{error:`No result.json found in ${i}`})}case"events":{let c=Tn(H(a,i,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${i}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=H(a,i,"raw_stream_output.txt");if(!Q(c))return JSON.stringify({error:`No log found in ${i}`});let d=ut(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 il(r,e){let t=String(r?.runId||"all"),n=Number(r?.tail||2e3),i=t==="all"?[...q.keys()]:[t];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let s=i.map(c=>{let d=q.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=Un(d.logPath,n),u=String(d.error||"").slice(-Math.max(200,n));return{...rl({run:d,logTail:l,errorTail:u}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:u}}),o=s.filter(c=>c.status==="failed"||c.status==="error"),a=s.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:s.length,failed:o.length,active:a.length,diagnoses:s})}function sl(r,e){let t=r?.directory||"test-specs",n=_e(e,t);if(!Q(n))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let s=function(o,a){for(let c of pt(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(H(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&i.push(d)}},i=[];return s(n,""),JSON.stringify({specs:i.map(o=>`${t}/${o}`),total:i.length,directory:t})}catch(i){return JSON.stringify({error:i.message})}}import{spawn as ol}from"child_process";import{existsSync as X,mkdirSync as al,readdirSync as Dn,statSync as cl,readFileSync as ll}from"fs";import{resolve as Ht,join as ee,basename as dl}from"path";var zt=".zibby/repos";function mt(r,e,t={}){return new Promise((n,i)=>{let s=ol(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),s.on("error",c=>i(c))})}var de={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
593
593
  You can clone and explore git repositories locally for codebase analysis:
594
594
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
595
595
  - git_list_repos: List locally cloned repos
@@ -600,7 +600,7 @@ When a test ticket lacks context, use this workflow:
600
600
  2. Use git_explore to understand the project structure
601
601
  3. Use shell commands (grep, cat) to read specific files for deeper understanding
602
602
  4. Use GitHub/GitLab skills to read related PRs and commits
603
- 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await ul(e,n);case"git_list_repos":return pl(e,n);case"git_explore":return ml(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"git_checkout",description:"Clone a git repository locally (or pull latest if already cloned). Auto-authenticates with GitHub/GitLab tokens if available.",input_schema:{type:"object",properties:{url:{type:"string",description:'Repository URL (e.g. "https://github.com/org/repo" or "org/repo" shorthand for GitHub)'},branch:{type:"string",description:"Branch to checkout (default: repo default branch)"},shallow:{type:"boolean",description:"Shallow clone with depth 1 (default: true, faster)"},name:{type:"string",description:"Local directory name override (default: repo name from URL)"}},required:["url"]}},{name:"git_list_repos",description:"List locally cloned repositories",input_schema:{type:"object",properties:{}}},{name:"git_explore",description:"Quick structural overview of a cloned repo: key files, package.json info, directory tree (top 2 levels), detected framework/language",input_schema:{type:"object",properties:{repo:{type:"string",description:"Repo name (as listed by git_list_repos)"},depth:{type:"number",description:"Directory tree depth (default: 2)"}},required:["repo"]}}]};async function ul(r,e){let{url:t,branch:n,shallow:i=!0,name:s}=r;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=s||dl(t.replace(/\.git$/,"")),a=zt(e,Wt);al(a,{recursive:!0});let c=ee(a,o),d=t,l=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,p=process.env.GITLAB_URL;if(t.includes("github.com")&&l)d=t.replace("https://github.com",`https://x-access-token:${l}@github.com`);else if(u&&p)try{let h=new URL(p).host;t.includes(h)&&(d=t.replace(`https://${h}`,`https://oauth2:${u}@${h}`))}catch{}if(X(ee(c,".git"))){let h=n?`git -C "${c}" fetch origin ${n} && git -C "${c}" checkout ${n} && git -C "${c}" pull origin ${n}`:`git -C "${c}" pull`;await ft(h,e);let y=await ft(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:n||"default",head:y})}let m=["git","clone"];i&&m.push("--depth","1"),n&&m.push("--branch",n),m.push(`"${d}"`,`"${c}"`),await ft(m.join(" "),e);let f=await ft(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:n||"default",shallow:i,head:f})}function pl(r,e){let t=zt(e,Wt);if(!X(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let i of Dn(t,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=ee(t,i.name);if(!X(ee(s,".git")))continue;let o=cl(s);n.push({name:i.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:t})}function ml(r,e){let{repo:t,depth:n=2}=r,i=zt(e,Wt,t);if(!X(i))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let s={repo:t,path:i},o=ee(i,"package.json");if(X(o))try{let m=JSON.parse(ll(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");X(a)&&(s.language="Python");let c=ee(i,"go.mod");X(c)&&(s.language="Go");let d=ee(i,"Cargo.toml");X(d)&&(s.language="Rust"),X(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function u(m,f,h){if(h>n)return;let y;try{y=Dn(m,{withFileTypes:!0})}catch{return}let _=y.filter(b=>!b.name.startsWith(".")&&b.name!=="node_modules"&&b.name!=="__pycache__"&&b.name!=="dist"&&b.name!=="build"&&b.name!==".git").sort((b,g)=>b.isDirectory()!==g.isDirectory()?b.isDirectory()?-1:1:b.name.localeCompare(g.name));for(let b of _){let g=b.isDirectory();l.push(`${f}${g?"\u{1F4C1}":"\u{1F4C4}"} ${b.name}`),g&&h<n&&u(ee(m,b.name),`${f} `,h+1)}}u(i,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let p=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return s.keyFilesFound=p.filter(m=>X(ee(i,m))),JSON.stringify(s)}function qn(r){let e=(r||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return e?{provider:"github",owner:e[1],repo:e[2]}:(e=(r||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),e?{provider:"gitlab",owner:e[1],repo:e[2]}:null)}var Jn={...de,id:"git-write",envKeys:[...de.envKeys||[],...Oe.envKeys||[],...Re.envKeys||[]].filter((r,e,t)=>t.indexOf(r)===e),promptFragment:`${de.promptFragment}
603
+ 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await ul(e,n);case"git_list_repos":return pl(e,n);case"git_explore":return ml(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"git_checkout",description:"Clone a git repository locally (or pull latest if already cloned). Auto-authenticates with GitHub/GitLab tokens if available.",input_schema:{type:"object",properties:{url:{type:"string",description:'Repository URL (e.g. "https://github.com/org/repo" or "org/repo" shorthand for GitHub)'},branch:{type:"string",description:"Branch to checkout (default: repo default branch)"},shallow:{type:"boolean",description:"Shallow clone with depth 1 (default: true, faster)"},name:{type:"string",description:"Local directory name override (default: repo name from URL)"}},required:["url"]}},{name:"git_list_repos",description:"List locally cloned repositories",input_schema:{type:"object",properties:{}}},{name:"git_explore",description:"Quick structural overview of a cloned repo: key files, package.json info, directory tree (top 2 levels), detected framework/language",input_schema:{type:"object",properties:{repo:{type:"string",description:"Repo name (as listed by git_list_repos)"},depth:{type:"number",description:"Directory tree depth (default: 2)"}},required:["repo"]}}]};async function ul(r,e){let{url:t,branch:n,shallow:i=!0,name:s}=r;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=s||dl(t.replace(/\.git$/,"")),a=Ht(e,zt);al(a,{recursive:!0});let c=ee(a,o),d=t,l=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,p=process.env.GITLAB_URL;if(t.includes("github.com")&&l)d=t.replace("https://github.com",`https://x-access-token:${l}@github.com`);else if(u&&p)try{let h=new URL(p).host;t.includes(h)&&(d=t.replace(`https://${h}`,`https://oauth2:${u}@${h}`))}catch{}if(X(ee(c,".git"))){let h=n?`git -C "${c}" fetch origin ${n} && git -C "${c}" checkout ${n} && git -C "${c}" pull origin ${n}`:`git -C "${c}" pull`;await mt(h,e);let y=await mt(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:n||"default",head:y})}let m=["git","clone"];i&&m.push("--depth","1"),n&&m.push("--branch",n),m.push(`"${d}"`,`"${c}"`),await mt(m.join(" "),e);let f=await mt(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:n||"default",shallow:i,head:f})}function pl(r,e){let t=Ht(e,zt);if(!X(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let i of Dn(t,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=ee(t,i.name);if(!X(ee(s,".git")))continue;let o=cl(s);n.push({name:i.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:t})}function ml(r,e){let{repo:t,depth:n=2}=r,i=Ht(e,zt,t);if(!X(i))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let s={repo:t,path:i},o=ee(i,"package.json");if(X(o))try{let m=JSON.parse(ll(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");X(a)&&(s.language="Python");let c=ee(i,"go.mod");X(c)&&(s.language="Go");let d=ee(i,"Cargo.toml");X(d)&&(s.language="Rust"),X(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function u(m,f,h){if(h>n)return;let y;try{y=Dn(m,{withFileTypes:!0})}catch{return}let _=y.filter(b=>!b.name.startsWith(".")&&b.name!=="node_modules"&&b.name!=="__pycache__"&&b.name!=="dist"&&b.name!=="build"&&b.name!==".git").sort((b,g)=>b.isDirectory()!==g.isDirectory()?b.isDirectory()?-1:1:b.name.localeCompare(g.name));for(let b of _){let g=b.isDirectory();l.push(`${f}${g?"\u{1F4C1}":"\u{1F4C4}"} ${b.name}`),g&&h<n&&u(ee(m,b.name),`${f} `,h+1)}}u(i,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let p=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return s.keyFilesFound=p.filter(m=>X(ee(i,m))),JSON.stringify(s)}function qn(r){let e=(r||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return e?{provider:"github",owner:e[1],repo:e[2]}:(e=(r||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),e?{provider:"gitlab",owner:e[1],repo:e[2]}:null)}var Jn={...de,id:"git-write",envKeys:[...de.envKeys||[],...Oe.envKeys||[],...Re.envKeys||[]].filter((r,e,t)=>t.indexOf(r)===e),promptFragment:`${de.promptFragment}
604
604
 
605
605
  ## Opening a pull request / merge request (git_open_pr)
606
606
  After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
@@ -612,7 +612,7 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
612
612
  To MERGE an open PR/MR, use the provider-agnostic tool:
613
613
  - git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
614
614
  { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
615
- Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(r,e,t){if(r!=="git_open_pr"&&r!=="git_merge_pr")return de.handleToolCall(r,e,t);try{let n=e||{},i=n.repoUrl||n.repo_url||n.url;if(!i)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(r==="git_merge_pr"){let l=n.number??n.iid??n.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let u=qn(i);return u?u.provider==="github"?Oe.handleToolCall("github_merge_pr",{owner:u.owner,repo:u.repo,number:l,mergeMethod:n.mergeMethod},t):Re.handleToolCall("gitlab_accept_mr",{project:`${u.owner}/${u.repo}`,iid:l},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_merge_pr supports github.com and gitlab.com.`})}let s=n.head||n.source_branch||n.sourceBranch||n.branch,o=n.base||n.target_branch||n.targetBranch,{title:a,body:c}=n;if(!s||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=qn(i);return d?d.provider==="github"?Oe.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:s,base:o,title:a,body:c},t):Re.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:s,target_branch:o,title:a,description:c},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_open_pr supports github.com and gitlab.com.`})}catch(n){return JSON.stringify({error:n.message})}},tools:[...de.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 Kn}from"child_process";import{existsSync as er,mkdirSync as Hn}from"fs";import{join as ie,basename as fl}from"path";import{randomBytes as hl}from"crypto";import{pathToFileURL as ze}from"url";import{createRequire as zn}from"module";var Vt=".zibby/memory",Wn="dolt",Yn={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},Qt="mem0",Yt=new Map,ht=new Map,gt=!1,gl=zn(import.meta.url),kt=()=>hl(8).toString("hex"),be=()=>new Date().toISOString(),yl=[`CREATE TABLE IF NOT EXISTS chat_memory (
615
+ Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(r,e,t){if(r!=="git_open_pr"&&r!=="git_merge_pr")return de.handleToolCall(r,e,t);try{let n=e||{},i=n.repoUrl||n.repo_url||n.url;if(!i)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(r==="git_merge_pr"){let l=n.number??n.iid??n.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let u=qn(i);return u?u.provider==="github"?Oe.handleToolCall("github_merge_pr",{owner:u.owner,repo:u.repo,number:l,mergeMethod:n.mergeMethod},t):Re.handleToolCall("gitlab_accept_mr",{project:`${u.owner}/${u.repo}`,iid:l},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_merge_pr supports github.com and gitlab.com.`})}let s=n.head||n.source_branch||n.sourceBranch||n.branch,o=n.base||n.target_branch||n.targetBranch,{title:a,body:c}=n;if(!s||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=qn(i);return d?d.provider==="github"?Oe.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:s,base:o,title:a,body:c},t):Re.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:s,target_branch:o,title:a,description:c},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_open_pr supports github.com and gitlab.com.`})}catch(n){return JSON.stringify({error:n.message})}},tools:[...de.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 Kn}from"child_process";import{existsSync as Xt,mkdirSync as Hn}from"fs";import{join as ie,basename as fl}from"path";import{randomBytes as hl}from"crypto";import{pathToFileURL as ze}from"url";import{createRequire as zn}from"module";var Zt=".zibby/memory",Wn="dolt",Yn={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},Vt="mem0",Wt=new Map,ft=new Map,ht=!1,gl=zn(import.meta.url),bt=()=>hl(8).toString("hex"),be=()=>new Date().toISOString(),yl=[`CREATE TABLE IF NOT EXISTS chat_memory (
616
616
  id VARCHAR(64) PRIMARY KEY,
617
617
  memory_key VARCHAR(160),
618
618
  category VARCHAR(32) NOT NULL,
@@ -643,10 +643,10 @@ To MERGE an open PR/MR, use the provider-agnostic tool:
643
643
  tasks_failed INT DEFAULT 0,
644
644
  key_facts TEXT,
645
645
  created_at VARCHAR(32) NOT NULL
646
- )`],Bn=new Set;function J(r,e){return Kn(Wn,e,{...Yn,cwd:r})}function ue(r,e){try{let t=J(r,["sql","-q",e,"-r","json"]);return JSON.parse(t.trim()).rows||[]}catch{return[]}}function B(r,e){J(r,["sql","-q",e])}function yt(r){if(Bn.has(r))return!0;if(!er(ie(r,".dolt"))){if(!_l())return!1;Hn(r,{recursive:!0}),J(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${yl.join(`;
647
- `)};`;B(r,e);try{B(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{B(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return Bn.add(r),!0}function _l(){try{return Kn(Wn,["version"],{...Yn,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function Xt(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function xe(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function tr(r,e){let t=["short","mid","long"].includes(r)?r:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(e||"").toLowerCase())&&t==="short"?"mid":t}function Zn(r){let e=new Map;for(let t of r||[]){let n=Xt(t.content),i=t.memory_key?`key:${t.memory_key}`:n?`norm:${n}`:"";if(!i)continue;let s=e.get(i);if(!s){e.set(i,t);continue}let o=xe(s.tier),a=xe(t.tier);if(a>o){e.set(i,t);continue}a===o&&Number(t.relevance||0)>Number(s.relevance||0)&&e.set(i,t)}return[...e.values()]}function bt(r,e){let t=String(r??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function He(r,e){let t={recentSessions:Array.isArray(r?.recentSessions)?r.recentSessions:[],topMemories:Array.isArray(r?.topMemories)?r.topMemories:[],taskStats:Array.isArray(r?.taskStats)?r.taskStats:[],ticketFilter:r?.ticketFilter||null,backend:e||String(r?.backend||Qt),error:r?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function Mn(r){let e=[];if(r.recentSessions?.length>0){e.push("Recent sessions:");for(let t of r.recentSessions.slice(0,3))t?.summary?.trim()&&e.push(`- ${bt(t.summary,150)}${t.tickets?` [${t.tickets}]`:""}`)}if(r.topMemories?.length>0){e.push("Known facts:");for(let t of r.topMemories.slice(0,10)){let n=t.tier==="long"?"\u2605":"\xB7";e.push(`${n} [${t.category}] ${bt(t.content,120)}`)}}return e.length===0?"":`## Memory Context
646
+ )`],Bn=new Set;function J(r,e){return Kn(Wn,e,{...Yn,cwd:r})}function ue(r,e){try{let t=J(r,["sql","-q",e,"-r","json"]);return JSON.parse(t.trim()).rows||[]}catch{return[]}}function B(r,e){J(r,["sql","-q",e])}function gt(r){if(Bn.has(r))return!0;if(!Xt(ie(r,".dolt"))){if(!_l())return!1;Hn(r,{recursive:!0}),J(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${yl.join(`;
647
+ `)};`;B(r,e);try{B(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{B(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return Bn.add(r),!0}function _l(){try{return Kn(Wn,["version"],{...Yn,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function Qt(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function xe(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function er(r,e){let t=["short","mid","long"].includes(r)?r:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(e||"").toLowerCase())&&t==="short"?"mid":t}function Zn(r){let e=new Map;for(let t of r||[]){let n=Qt(t.content),i=t.memory_key?`key:${t.memory_key}`:n?`norm:${n}`:"";if(!i)continue;let s=e.get(i);if(!s){e.set(i,t);continue}let o=xe(s.tier),a=xe(t.tier);if(a>o){e.set(i,t);continue}a===o&&Number(t.relevance||0)>Number(s.relevance||0)&&e.set(i,t)}return[...e.values()]}function _t(r,e){let t=String(r??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function He(r,e){let t={recentSessions:Array.isArray(r?.recentSessions)?r.recentSessions:[],topMemories:Array.isArray(r?.topMemories)?r.topMemories:[],taskStats:Array.isArray(r?.taskStats)?r.taskStats:[],ticketFilter:r?.ticketFilter||null,backend:e||String(r?.backend||Vt),error:r?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function Mn(r){let e=[];if(r.recentSessions?.length>0){e.push("Recent sessions:");for(let t of r.recentSessions.slice(0,3))t?.summary?.trim()&&e.push(`- ${_t(t.summary,150)}${t.tickets?` [${t.tickets}]`:""}`)}if(r.topMemories?.length>0){e.push("Known facts:");for(let t of r.topMemories.slice(0,10)){let n=t.tier==="long"?"\u2605":"\xB7";e.push(`${n} [${t.category}] ${_t(t.content,120)}`)}}return e.length===0?"":`## Memory Context
648
648
  ${e.join(`
649
- `)}`}function _t(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:bt(String(e?.summary||""),160),tickets:e?.tickets||null,created_at:e?.created_at||null})),topMemories:r.topMemories.slice(0,8).map(e=>({category:e?.category||null,tier:e?.tier||null,content:bt(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function bl(r,e){let t=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(t==="mem0"||t==="dolt")return t;let n=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(n==="mem0"||n==="dolt")return n;if(ht.has(r))return ht.get(r);try{let i=ie(r,".zibby.config.mjs");if(er(i)){let s=await import(ze(i).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return ht.set(r,o),o}}catch{}return ht.set(r,Qt),Qt}function Vn(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${fl(r||process.cwd())}`}var kl="mem0";function Qn(r){let e=ie(r,Vt,kl);return{dir:e,vectorDbPath:ie(e,"vectors.db"),historyDbPath:ie(e,"history.db")}}function wl(r){let e=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!e)return null;let t=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),n=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),i=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),s=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=Qn(r||process.cwd());return{llm:{provider:"openai",config:{model:n,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:s,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function Xn(r){let e=r||process.cwd();if(Yt.has(e))return Yt.get(e);let t;try{let a=zn(ze(ie(e,"package.json")).href).resolve("mem0ai/oss");t=await import(ze(a).href)}catch{try{let o=gl.resolve("mem0ai/oss");t=await import(ze(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let n=t?.Memory;if(!n)throw new Error("mem0ai/oss does not export Memory");let i=wl(e);if(i)try{Hn(Qn(e).dir,{recursive:!0})}catch{}let s=i?new n(i):new n;return Yt.set(e,s),s}function Fn(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||kt(),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:tr(n?.metadata?.tier||e,n?.metadata?.category||"fact"),relevance:Number(n?.score??n?.metadata?.relevance??.8),created_at:n?.created_at||n?.metadata?.created_at||be()})).filter(n=>String(n.content||"").trim().length>0)}var Ee={id:"dolt",store:(r,e)=>ti(r,e),recall:(r,e)=>Rl(r,e),brief:(r,e)=>Tl(r,e),endSession:(r,e)=>ni(r,e),logTask:(r,e)=>ii(r,e),taskHistory:(r,e)=>si(r,e)},Sl={id:"mem0",store:(r,e,t)=>Ol(r,e,t),recall:(r,e,t)=>ri(r,e,t),brief:(r,e,t)=>Al(r,e,t),endSession:(r,e)=>ni(r,e),logTask:(r,e)=>ii(r,e),taskHistory:(r,e)=>si(r,e)},Il={dolt:Ee,mem0:Sl};async function Gn(r,e){let t=await bl(r,e);return Il[t]||Ee}var ei={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
649
+ `)}`}function yt(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:_t(String(e?.summary||""),160),tickets:e?.tickets||null,created_at:e?.created_at||null})),topMemories:r.topMemories.slice(0,8).map(e=>({category:e?.category||null,tier:e?.tier||null,content:_t(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function bl(r,e){let t=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(t==="mem0"||t==="dolt")return t;let n=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(n==="mem0"||n==="dolt")return n;if(ft.has(r))return ft.get(r);try{let i=ie(r,".zibby.config.mjs");if(Xt(i)){let s=await import(ze(i).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return ft.set(r,o),o}}catch{}return ft.set(r,Vt),Vt}function Vn(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${fl(r||process.cwd())}`}var kl="mem0";function Qn(r){let e=ie(r,Zt,kl);return{dir:e,vectorDbPath:ie(e,"vectors.db"),historyDbPath:ie(e,"history.db")}}function wl(r){let e=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!e)return null;let t=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),n=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),i=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),s=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=Qn(r||process.cwd());return{llm:{provider:"openai",config:{model:n,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:s,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function Xn(r){let e=r||process.cwd();if(Wt.has(e))return Wt.get(e);let t;try{let a=zn(ze(ie(e,"package.json")).href).resolve("mem0ai/oss");t=await import(ze(a).href)}catch{try{let o=gl.resolve("mem0ai/oss");t=await import(ze(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let n=t?.Memory;if(!n)throw new Error("mem0ai/oss does not export Memory");let i=wl(e);if(i)try{Hn(Qn(e).dir,{recursive:!0})}catch{}let s=i?new n(i):new n;return Wt.set(e,s),s}function Fn(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||bt(),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:er(n?.metadata?.tier||e,n?.metadata?.category||"fact"),relevance:Number(n?.score??n?.metadata?.relevance??.8),created_at:n?.created_at||n?.metadata?.created_at||be()})).filter(n=>String(n.content||"").trim().length>0)}var Ee={id:"dolt",store:(r,e)=>ti(r,e),recall:(r,e)=>Rl(r,e),brief:(r,e)=>Tl(r,e),endSession:(r,e)=>ni(r,e),logTask:(r,e)=>ii(r,e),taskHistory:(r,e)=>si(r,e)},Sl={id:"mem0",store:(r,e,t)=>Ol(r,e,t),recall:(r,e,t)=>ri(r,e,t),brief:(r,e,t)=>Al(r,e,t),endSession:(r,e)=>ni(r,e),logTask:(r,e)=>ii(r,e),taskHistory:(r,e)=>si(r,e)},Il={dolt:Ee,mem0:Sl};async function Gn(r,e){let t=await bl(r,e);return Il[t]||Ee}var ei={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
650
650
  You have persistent memory across sessions. Use it to avoid losing context:
651
651
  - **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
652
652
  - **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
@@ -662,9 +662,9 @@ You have persistent memory across sessions. Use it to avoid losing context:
662
662
  - When the user's request is complete: call memory_end_session
663
663
 
664
664
  ### Categories for memory_store
665
- fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,e={}){let t=r?.options?.workspace||process.cwd(),n=ie(t,Vt),i=await Gn(t,r),s=i.id;if(s==="dolt"&&!yt(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:He({backend:s,error:o},s),promptContext:"",debugPreview:_t(He({backend:s,error:o},s)),error:o}}try{let o=await i.brief(e,n,t),a=JSON.parse(o||"{}"),c=He({...a,backend:s},s);return{backend:s,brief:c,promptContext:Mn(c),debugPreview:_t(c),error:c.error||null}}catch(o){if(s==="mem0"&&i!==Ee&&yt(n)){if(!gt){gt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
666
- `)}catch{}}try{let d=await Ee.brief(e,n,t),l=JSON.parse(d||"{}"),u=He({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:u,promptContext:Mn(u),debugPreview:_t(u),error:u.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=He({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:_t(c),error:a}}},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd(),i=ie(n,Vt),s=await Gn(n,t),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!yt(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(r){case"memory_store":return d.store(e,i,n);case"memory_recall":return d.recall(e,i,n);case"memory_brief":return d.brief(e,i,n);case"memory_end_session":return d.endSession(e,i,n);case"task_log":return d.logTask(e,i,n);case"task_history":return d.taskHistory(e,i,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(d){if(o==="mem0"&&s!==Ee){if(yt(i)){if(!gt){gt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
667
- `)}catch{}}try{return await c(Ee)}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 ti(r,e){let{content:t,category:n,source:i,ticketKey:s,tier:o,memoryKey:a}=r;if(!t||!n)return JSON.stringify({error:"content and category are required"});let c=Xt(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=tr(o,n),l=d==="long"?1:d==="mid"?.8:.5,u=String(a||"").trim().slice(0,160);if(u){let _=ue(e,`SELECT id, tier, relevance
665
+ fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,e={}){let t=r?.options?.workspace||process.cwd(),n=ie(t,Zt),i=await Gn(t,r),s=i.id;if(s==="dolt"&&!gt(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:He({backend:s,error:o},s),promptContext:"",debugPreview:yt(He({backend:s,error:o},s)),error:o}}try{let o=await i.brief(e,n,t),a=JSON.parse(o||"{}"),c=He({...a,backend:s},s);return{backend:s,brief:c,promptContext:Mn(c),debugPreview:yt(c),error:c.error||null}}catch(o){if(s==="mem0"&&i!==Ee&&gt(n)){if(!ht){ht=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
666
+ `)}catch{}}try{let d=await Ee.brief(e,n,t),l=JSON.parse(d||"{}"),u=He({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:u,promptContext:Mn(u),debugPreview:yt(u),error:u.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=He({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:yt(c),error:a}}},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd(),i=ie(n,Zt),s=await Gn(n,t),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!gt(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(r){case"memory_store":return d.store(e,i,n);case"memory_recall":return d.recall(e,i,n);case"memory_brief":return d.brief(e,i,n);case"memory_end_session":return d.endSession(e,i,n);case"task_log":return d.logTask(e,i,n);case"task_history":return d.taskHistory(e,i,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(d){if(o==="mem0"&&s!==Ee){if(gt(i)){if(!ht){ht=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
667
+ `)}catch{}}try{return await c(Ee)}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 ti(r,e){let{content:t,category:n,source:i,ticketKey:s,tier:o,memoryKey:a}=r;if(!t||!n)return JSON.stringify({error:"content and category are required"});let c=Qt(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=er(o,n),l=d==="long"?1:d==="mid"?.8:.5,u=String(a||"").trim().slice(0,160);if(u){let _=ue(e,`SELECT id, tier, relevance
668
668
  FROM chat_memory
669
669
  WHERE memory_key = ${S(u)}
670
670
  ORDER BY created_at DESC
@@ -680,22 +680,22 @@ fact, decision, context, insight, credential, url, error, workaround`,resolve(){
680
680
  FROM chat_memory
681
681
  WHERE category = ${S(n)}
682
682
  ORDER BY created_at DESC
683
- LIMIT 200`).find(y=>Xt(y.content)===c);if(m){let y=String(m.tier||"mid"),_=Number(m.relevance||0),b=xe(d)>xe(y),g=l>_;if(b||g){B(e,`UPDATE chat_memory
683
+ LIMIT 200`).find(y=>Qt(y.content)===c);if(m){let y=String(m.tier||"mid"),_=Number(m.relevance||0),b=xe(d)>xe(y),g=l>_;if(b||g){B(e,`UPDATE chat_memory
684
684
  SET tier = ${S(b?d:y)},
685
685
  relevance = ${Math.max(l,_)}
686
- WHERE id = ${S(m.id)}`);try{J(e,["add","."]),J(e,["commit","-m",`memory promote: ${n} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:n,tier:b?d:y,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:n,tier:y,deduped:!0,promoted:!1})}let f=kt(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;B(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
687
- VALUES (${S(f)}, ${S(u||null)}, ${S(n)}, ${S(t)}, ${S(i)}, ${S(s)}, ${S(h)}, ${S(d)}, ${l}, ${S(be())})`);try{J(e,["add","."]),J(e,["commit","-m",`memory: ${n} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:n,tier:d,memoryKey:u||null,stored:t.slice(0,100)})}function vl(r){let e=String(r||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var Zt=new Map;async function Nl(r,e){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return vl(process.env.ZIBBY_MEM0_INFER);let t=e||process.cwd();if(Zt.has(t))return Zt.get(t);let n=!1;try{let i=ie(t,".zibby.config.mjs");er(i)&&(n=(await import(ze(i).href))?.default?.memory?.infer===!0)}catch{}return Zt.set(t,n),n}async function Ol(r,e,t){let{content:n,category:i,source:s,ticketKey:o,tier:a,memoryKey:c,infer:d}=r;if(!n||!i)return JSON.stringify({error:"content and category are required"});try{let l=await Xn(t),u=Vn(t),p=tr(a,i),m=await Nl(d,t);return await l.add([{role:"user",content:String(n)}],{userId:u,infer:m,metadata:{memoryKey:c||null,category:i,tier:p,source:s||"zibby-chat",ticketKey:o||null,created_at:be()}}),JSON.stringify({ok:!0,backend:"mem0",userId:u,category:i,tier:p,infer:m,memoryKey:c||null,stored:String(n).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function Rl(r,e){let{query:t,category:n,ticketKey:i,tier:s,limit:o=20}=r,a=[];t&&a.push(`content LIKE ${S(`%${t}%`)}`),n&&a.push(`category = ${S(n)}`),i&&a.push(`ticket_key = ${S(i)}`),s&&a.push(`tier = ${S(s)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
686
+ WHERE id = ${S(m.id)}`);try{J(e,["add","."]),J(e,["commit","-m",`memory promote: ${n} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:n,tier:b?d:y,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:n,tier:y,deduped:!0,promoted:!1})}let f=bt(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;B(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
687
+ VALUES (${S(f)}, ${S(u||null)}, ${S(n)}, ${S(t)}, ${S(i)}, ${S(s)}, ${S(h)}, ${S(d)}, ${l}, ${S(be())})`);try{J(e,["add","."]),J(e,["commit","-m",`memory: ${n} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:n,tier:d,memoryKey:u||null,stored:t.slice(0,100)})}function vl(r){let e=String(r||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var Yt=new Map;async function Nl(r,e){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return vl(process.env.ZIBBY_MEM0_INFER);let t=e||process.cwd();if(Yt.has(t))return Yt.get(t);let n=!1;try{let i=ie(t,".zibby.config.mjs");Xt(i)&&(n=(await import(ze(i).href))?.default?.memory?.infer===!0)}catch{}return Yt.set(t,n),n}async function Ol(r,e,t){let{content:n,category:i,source:s,ticketKey:o,tier:a,memoryKey:c,infer:d}=r;if(!n||!i)return JSON.stringify({error:"content and category are required"});try{let l=await Xn(t),u=Vn(t),p=er(a,i),m=await Nl(d,t);return await l.add([{role:"user",content:String(n)}],{userId:u,infer:m,metadata:{memoryKey:c||null,category:i,tier:p,source:s||"zibby-chat",ticketKey:o||null,created_at:be()}}),JSON.stringify({ok:!0,backend:"mem0",userId:u,category:i,tier:p,infer:m,memoryKey:c||null,stored:String(n).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function Rl(r,e){let{query:t,category:n,ticketKey:i,tier:s,limit:o=20}=r,a=[];t&&a.push(`content LIKE ${S(`%${t}%`)}`),n&&a.push(`category = ${S(n)}`),i&&a.push(`ticket_key = ${S(i)}`),s&&a.push(`tier = ${S(s)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
688
688
  FROM chat_memory ${a.length>0?`WHERE ${a.join(" AND ")}`:""}
689
689
  ORDER BY relevance DESC, created_at DESC
690
690
  LIMIT ${o}`,l=ue(e,d);return JSON.stringify({total:l.length,memories:l})}async function ri(r,e,t){let{query:n,category:i,ticketKey:s,tier:o,limit:a=20}=r;try{let c=await Xn(t),d=Vn(t),l=[];if(n&&String(n).trim()){let u=await c.search(String(n),{filters:{user_id:d},topK:a});l=Fn(u)}else{let u=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=Fn(u)}return i&&(l=l.filter(u=>u.category===i)),s&&(l=l.filter(u=>u.ticket_key===s)),o&&(l=l.filter(u=>u.tier===o)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function Tl(r,e){let{ticketKey:t}=r;El(e);let i=ue(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
691
691
  FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),s=t?`AND ticket_key = ${S(t)}`:"",o=ue(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
692
692
  WHERE tier = 'long' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=ue(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
693
693
  WHERE tier = 'mid' ${s} ORDER BY relevance DESC, created_at DESC LIMIT 8`),d=ue(e,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
694
- GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=Zn([...o,...a]);return JSON.stringify({recentSessions:i,topMemories:l,taskStats:d,ticketFilter:t||null})}async function Al(r,e,t){let{ticketKey:n}=r,i=await ri({limit:80},e,t),s=JSON.parse(i||"{}"),o=Array.isArray(s.memories)?s.memories:[];n&&(o=o.filter(p=>p.ticket_key===n));let a=p=>{let m=Date.parse(String(p?.created_at||""))||0;return Number(p?.relevance||0)*1e12+m},c=(p,m)=>a(m)-a(p),d=o.filter(p=>p.tier==="long").sort(c).slice(0,10),l=o.filter(p=>p.tier==="mid").sort(c).slice(0,8),u=Zn([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:u,taskStats:[],ticketFilter:n||null,backend:"mem0"})}function ni(r,e){let{summary:t,tickets:n,tasksRun:i=0,tasksPassed:s=0,tasksFailed:o=0,keyFacts:a}=r;if(!t)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${kt()}`;if(B(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
695
- VALUES (${S(c)}, ${S(t)}, ${S(n)}, ${i}, ${s}, ${o}, ${S(a)}, ${S(be())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))ti({content:d,category:"fact",source:"session_summary",tier:"mid"},e);xl(e);try{J(e,["add","."]),J(e,["commit","-m",`session end: ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:t.slice(0,200)})}function ii(r,e){let{title:t,type:n,status:i,ticketKey:s,specPath:o,resultSummary:a}=r;if(!t||!n||!i)return JSON.stringify({error:"title, type, and status are required"});let c=kt(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;B(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
694
+ GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=Zn([...o,...a]);return JSON.stringify({recentSessions:i,topMemories:l,taskStats:d,ticketFilter:t||null})}async function Al(r,e,t){let{ticketKey:n}=r,i=await ri({limit:80},e,t),s=JSON.parse(i||"{}"),o=Array.isArray(s.memories)?s.memories:[];n&&(o=o.filter(p=>p.ticket_key===n));let a=p=>{let m=Date.parse(String(p?.created_at||""))||0;return Number(p?.relevance||0)*1e12+m},c=(p,m)=>a(m)-a(p),d=o.filter(p=>p.tier==="long").sort(c).slice(0,10),l=o.filter(p=>p.tier==="mid").sort(c).slice(0,8),u=Zn([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:u,taskStats:[],ticketFilter:n||null,backend:"mem0"})}function ni(r,e){let{summary:t,tickets:n,tasksRun:i=0,tasksPassed:s=0,tasksFailed:o=0,keyFacts:a}=r;if(!t)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${bt()}`;if(B(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
695
+ VALUES (${S(c)}, ${S(t)}, ${S(n)}, ${i}, ${s}, ${o}, ${S(a)}, ${S(be())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))ti({content:d,category:"fact",source:"session_summary",tier:"mid"},e);xl(e);try{J(e,["add","."]),J(e,["commit","-m",`session end: ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:t.slice(0,200)})}function ii(r,e){let{title:t,type:n,status:i,ticketKey:s,specPath:o,resultSummary:a}=r;if(!t||!n||!i)return JSON.stringify({error:"title, type, and status are required"});let c=bt(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;B(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
696
696
  VALUES (${S(c)}, ${S(s)}, ${S(n)}, ${S(t)}, ${S(i)}, ${S(o)}, ${S(d)}, ${S(a)}, ${S(be())}, ${S(be())})`);try{J(e,["add","."]),J(e,["commit","-m",`task: ${i} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:t,type:n,status:i})}function si(r,e){let{ticketKey:t,type:n,status:i,limit:s=20}=r,o=[];t&&o.push(`ticket_key = ${S(t)}`),n&&o.push(`type = ${S(n)}`),i&&o.push(`status = ${S(i)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
697
697
  FROM chat_tasks ${o.length>0?`WHERE ${o.join(" AND ")}`:""}
698
- ORDER BY created_at DESC LIMIT ${s}`,d=ue(e,c);return JSON.stringify({total:d.length,tasks:d})}function xl(r){try{B(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),B(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),B(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),B(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function El(r){try{let e=new Date(Date.now()-864e5).toISOString();B(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(e)}`)}catch{}}import{existsSync as oi,readFileSync as $l}from"node:fs";import{homedir as Ll}from"node:os";import{join as jl,dirname as Pl,resolve as Cl}from"node:path";import{fileURLToPath as Ul}from"node:url";function Dl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Pl(Ul(import.meta.url)),e=Cl(r,"..","bin","mcp-skill.mjs");return oi(e)?e:null}function ql(){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=jl(Ll(),".zibby","config.json");return oi(r)&&JSON.parse($l(r,"utf-8")).sessionToken||null}catch{return null}}function Jl(){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 Bl(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function rr(r){return`${Bl()}:${r}`}async function nr(r,e){let t=ql();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${Jl()}/credits/review-memory`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${i.status}): ${s.slice(0,300)}`)}return i.json()}var ai={id:"kv-memory",serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
698
+ ORDER BY created_at DESC LIMIT ${s}`,d=ue(e,c);return JSON.stringify({total:d.length,tasks:d})}function xl(r){try{B(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),B(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),B(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),B(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function El(r){try{let e=new Date(Date.now()-864e5).toISOString();B(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(e)}`)}catch{}}import{existsSync as oi,readFileSync as $l}from"node:fs";import{homedir as Ll}from"node:os";import{join as jl,dirname as Pl,resolve as Cl}from"node:path";import{fileURLToPath as Ul}from"node:url";function Dl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Pl(Ul(import.meta.url)),e=Cl(r,"..","bin","mcp-skill.mjs");return oi(e)?e:null}function ql(){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=jl(Ll(),".zibby","config.json");return oi(r)&&JSON.parse($l(r,"utf-8")).sessionToken||null}catch{return null}}function Jl(){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 Bl(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function tr(r){return`${Bl()}:${r}`}async function rr(r,e){let t=ql();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${Jl()}/credits/review-memory`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${i.status}): ${s.slice(0,300)}`)}return i.json()}var ai={id:"kv-memory",serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
699
699
  You have a PRIVATE per-agent key-value memory that survives across your
700
700
  stateless runs. It is automatically namespaced to YOU (this agent type) \u2014 other
701
701
  agents cannot see or collide with your entries, and you don't need to prefix
@@ -710,7 +710,7 @@ Tools:
710
710
  Use to record durable facts \u2014 e.g. dedup markers, prior decisions, summaries.
711
711
 
712
712
  Your namespace is added for you automatically; pass plain keys like
713
- "seen#owner/repo#42" or "lastRun".`,resolve(){let r=Dl();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/kvMemory.js","kvMemorySkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"kv_recall":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});let n=await nr("recall",{scope:rr(t)});return JSON.stringify(n)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let n=await nr("recall-prefix",{scopePrefix:rr(t)});return JSON.stringify(n)}case"kv_store":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});if(typeof e?.content!="string"||e.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let n={scope:rr(t),content:e.content};e.metadata!=null&&(n.metadata=e.metadata);let i=await nr("store",n);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"kv_recall",description:'Recall the value you stored under a plain key (exact match). Your per-agent namespace is added automatically \u2014 pass a plain key like "seen#owner/repo#42".',input_schema:{type:"object",properties:{key:{type:"string",description:'Plain storage key (no namespace prefix needed) \u2014 e.g. "seen#owner/repo#42" or "lastRun".'}},required:["key"]}},{name:"kv_recall_prefix",description:'List your entries whose plain key STARTS WITH a prefix (e.g. "seen#"). Your per-agent namespace is added automatically. Capped at 25.',input_schema:{type:"object",properties:{keyPrefix:{type:"string",description:'Plain key prefix to match (no namespace prefix needed) \u2014 e.g. "seen#".'}},required:["keyPrefix"]}},{name:"kv_store",description:"Store (overwrite) a value under a plain key so a later run of yours can recall it. Your per-agent namespace is added automatically.",input_schema:{type:"object",properties:{key:{type:"string",description:"Plain storage key (no namespace prefix needed). Same key you recall by."},content:{type:"string",description:"The value to persist. Free-form markdown/text."},metadata:{type:"object",description:"Optional structured metadata."}},required:["key","content"]}}]};import{existsSync as li,readFileSync as Ml}from"node:fs";import{homedir as Fl}from"node:os";import{join as Gl,dirname as Kl,resolve as Hl}from"node:path";import{fileURLToPath as zl}from"node:url";function Wl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Kl(zl(import.meta.url)),e=Hl(r,"..","bin","mcp-skill.mjs");return li(e)?e:null}function di(){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=Gl(Fl(),".zibby","config.json");return li(r)&&JSON.parse(Ml(r,"utf-8")).sessionToken||null}catch{return null}}function ui(){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 ci(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Yl(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}var pi={};function ir(r){let e={...Yl(),...pi},t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function Zl(r){let e=di();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${ui()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let n=await t.text().catch(()=>"");throw new Error(`ensure_store failed (${t.status}): ${n.slice(0,300)}`)}return t.json()}async function sr(r,e,t){let n=di();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${ui()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${e} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var mi={id:"dataset-store",serverName:"dataset_store",allowedTools:["mcp__dataset_store__*"],description:"Dataset store \u2014 a durable, queryable store for structured JSON records; append rows now, run SQL-style aggregations/reports later",promptFragment:`## Dataset Store (durable, queryable structured-record store)
713
+ "seen#owner/repo#42" or "lastRun".`,resolve(){let r=Dl();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/kvMemory.js","kvMemorySkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"kv_recall":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});let n=await rr("recall",{scope:tr(t)});return JSON.stringify(n)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let n=await rr("recall-prefix",{scopePrefix:tr(t)});return JSON.stringify(n)}case"kv_store":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});if(typeof e?.content!="string"||e.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let n={scope:tr(t),content:e.content};e.metadata!=null&&(n.metadata=e.metadata);let i=await rr("store",n);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"kv_recall",description:'Recall the value you stored under a plain key (exact match). Your per-agent namespace is added automatically \u2014 pass a plain key like "seen#owner/repo#42".',input_schema:{type:"object",properties:{key:{type:"string",description:'Plain storage key (no namespace prefix needed) \u2014 e.g. "seen#owner/repo#42" or "lastRun".'}},required:["key"]}},{name:"kv_recall_prefix",description:'List your entries whose plain key STARTS WITH a prefix (e.g. "seen#"). Your per-agent namespace is added automatically. Capped at 25.',input_schema:{type:"object",properties:{keyPrefix:{type:"string",description:'Plain key prefix to match (no namespace prefix needed) \u2014 e.g. "seen#".'}},required:["keyPrefix"]}},{name:"kv_store",description:"Store (overwrite) a value under a plain key so a later run of yours can recall it. Your per-agent namespace is added automatically.",input_schema:{type:"object",properties:{key:{type:"string",description:"Plain storage key (no namespace prefix needed). Same key you recall by."},content:{type:"string",description:"The value to persist. Free-form markdown/text."},metadata:{type:"object",description:"Optional structured metadata."}},required:["key","content"]}}]};import{existsSync as li,readFileSync as Ml}from"node:fs";import{homedir as Fl}from"node:os";import{join as Gl,dirname as Kl,resolve as Hl}from"node:path";import{fileURLToPath as zl}from"node:url";function Wl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Kl(zl(import.meta.url)),e=Hl(r,"..","bin","mcp-skill.mjs");return li(e)?e:null}function di(){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=Gl(Fl(),".zibby","config.json");return li(r)&&JSON.parse(Ml(r,"utf-8")).sessionToken||null}catch{return null}}function ui(){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 ci(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Yl(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}var pi={};function nr(r){let e={...Yl(),...pi},t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function Zl(r){let e=di();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${ui()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let n=await t.text().catch(()=>"");throw new Error(`ensure_store failed (${t.status}): ${n.slice(0,300)}`)}return t.json()}async function ir(r,e,t){let n=di();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${ui()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${e} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var mi={id:"dataset-store",serverName:"dataset_store",allowedTools:["mcp__dataset_store__*"],description:"Dataset store \u2014 a durable, queryable store for structured JSON records; append rows now, run SQL-style aggregations/reports later",promptFragment:`## Dataset Store (durable, queryable structured-record store)
714
714
  You have one or more durable stores for STRUCTURED records that survive across
715
715
  your stateless runs. Unlike key-value memory (for picking up where you left
716
716
  off), this is for accumulating DATA you want to QUERY and AGGREGATE later \u2014 e.g.
@@ -746,14 +746,14 @@ Tools:
746
746
  - sqlite_query: (sqlite stores) Run a SELECT (optionally with \`params\` for safe
747
747
  binding). Returns { columns, rows }. Read-only \u2014 never changes data.
748
748
  Pick the tool that matches the store's TYPE; using a dataset tool on a sqlite
749
- store (or vice-versa) is rejected.`,resolve(){let r=Wl();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);for(let t of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(t)&&process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/datasetStore.js","datasetStoreSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e){try{switch(r){case"dataset_append":{if(e?.record==null||typeof e.record!="object"||Array.isArray(e.record))return JSON.stringify({error:"record is required (a JSON object)"});let t=ir(e?.store);if(t.error)return JSON.stringify({error:t.error});let n=typeof e?.agent=="string"&&e.agent.trim()?e.agent.trim():ci(),i={record:e.record,agent:n};typeof e?.description=="string"&&e.description.trim()&&(i.description=e.description.trim());let s=await sr(t.storeId,"append",i);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"dataset_query":{let t=ir(e?.store);if(t.error)return JSON.stringify({error:t.error});let n={};for(let s of["select","where","groupBy","orderBy","limit","since","until","agent"])e?.[s]!=null&&(n[s]=e[s]);let i=await sr(t.storeId,"query",n);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}case"ensure_store":{let t=typeof e?.name=="string"?e.name.trim():"";if(!t)return JSON.stringify({error:"name is required"});let n=typeof e?.type=="string"&&e.type.trim()?e.type.trim().toLowerCase():"sqlite",i=typeof e?.description=="string"?e.description.trim():"",s=await Zl({name:t,type:n,description:i,namespace:ci()});return s?.storeId&&(pi[t]=s.storeId),JSON.stringify({...s,store:t})}case"sqlite_exec":case"sqlite_query":{let t=ir(e?.store);if(t.error)return JSON.stringify({error:t.error});if(typeof e?.sql!="string"||!e.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let n={sql:e.sql};Array.isArray(e?.params)&&(n.params=e.params);let i=await sr(t.storeId,"sql",n);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics.'},description:{type:"string",description:"What this store is for (shown in the Storage UI)."}},required:["name"]}},{name:"sqlite_exec",description:"For SQLITE-type stores: run SQL that CHANGES data \u2014 CREATE TABLE (use IF NOT EXISTS), INSERT, UPDATE, DELETE (one or more statements in one call). The store is a real, mutable SQLite database that persists across your stateless runs. Returns { rowsModified, wrote }. Use this to build schema on the fly and to update rows / track changing state (e.g. a queue with a status column).",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:'The SQL to run. May contain multiple statements separated by ";". Prefer CREATE TABLE IF NOT EXISTS for idempotent schema.'},params:{type:"array",description:'Optional positional bind params for a SINGLE parameterized statement (safe binding of values), e.g. sql "UPDATE t SET s=? WHERE id=?" with params ["done", 1].'}},required:["sql"]}},{name:"sqlite_query",description:"For SQLITE-type stores: run a read-only SELECT (optionally with `params` for safe binding) against the store's SQLite database. Returns { columns, rows }. Never changes data. Use to read back rows/state you stored earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:"A single SELECT statement. Use ? placeholders + `params` for any values."},params:{type:"array",description:'Optional positional bind params for the SELECT, e.g. ["linkedin_personal"].'}},required:["sql"]}}]};import{createRequire as Vl}from"node:module";import{existsSync as yi,mkdirSync as Ql,writeFileSync as fi}from"node:fs";import{dirname as _i,join as $e,resolve as bi}from"node:path";import{fileURLToPath as ki}from"node:url";var wi=Vl(import.meta.url),or=null;function Xl(){return or||(or=wi("echarts")),or}var ar=null;function ed(){return ar||(ar=wi("@resvg/resvg-js")),ar}var td=800,rd=600,nd=4096,id=16,hi=60,Si="Noto Sans";function sd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=_i(ki(import.meta.url)),e=bi(r,"..","bin","mcp-skill.mjs");return yi(e)?e:null}function od(){let r=_i(ki(import.meta.url)),e=bi(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>$e(e,t)).filter(t=>yi(t))}function ad(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?$e(e,"chart-render"):$e(process.cwd(),".zibby","output","charts"));return Ql(t,{recursive:!0}),t}function ke(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function gi(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(id,Math.min(nd,Math.round(t))):e}function cr(r){return typeof r!="string"||r.length<=hi?r:`${r.slice(0,hi-1)}\u2026`}function wt(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=cr(t):ke(t)&&typeof t.name=="string"&&(t.name=cr(t.name))}}function cd(r){for(let n of["xAxis","yAxis"]){let i=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let s of i)ke(s)&&wt(s.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of e)ke(n)&&wt(n.indicator);ke(r.legend)&&wt(r.legend.data);let t=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of t)ke(n)&&(typeof n.name=="string"&&(n.name=cr(n.name)),wt(n.data))}function ld(r){let e=JSON.parse(JSON.stringify(r));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),ke(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=Si),cd(e),e}function dd(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function ud(r,e,t){let i=Xl().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return i.setOption(r),i.renderToSVGString()}finally{i.dispose()}}function pd(r){let{Resvg:e}=ed();return new e(r,{font:{fontFiles:od(),loadSystemFonts:!0,defaultFontFamily:Si}}).render().asPng()}var Ii={id:"chart-render",serverName:"chart_render",allowedTools:["mcp__chart_render__*"],description:"Chart render \u2014 local server-side chart rendering (Apache ECharts SVG SSR + resvg PNG); data never leaves the box",promptFragment:`## Chart Render (local, no external service)
749
+ store (or vice-versa) is rejected.`,resolve(){let r=Wl();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);for(let t of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(t)&&process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/datasetStore.js","datasetStoreSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e){try{switch(r){case"dataset_append":{if(e?.record==null||typeof e.record!="object"||Array.isArray(e.record))return JSON.stringify({error:"record is required (a JSON object)"});let t=nr(e?.store);if(t.error)return JSON.stringify({error:t.error});let n=typeof e?.agent=="string"&&e.agent.trim()?e.agent.trim():ci(),i={record:e.record,agent:n};typeof e?.description=="string"&&e.description.trim()&&(i.description=e.description.trim());let s=await ir(t.storeId,"append",i);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"dataset_query":{let t=nr(e?.store);if(t.error)return JSON.stringify({error:t.error});let n={};for(let s of["select","where","groupBy","orderBy","limit","since","until","agent"])e?.[s]!=null&&(n[s]=e[s]);let i=await ir(t.storeId,"query",n);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}case"ensure_store":{let t=typeof e?.name=="string"?e.name.trim():"";if(!t)return JSON.stringify({error:"name is required"});let n=typeof e?.type=="string"&&e.type.trim()?e.type.trim().toLowerCase():"sqlite",i=typeof e?.description=="string"?e.description.trim():"",s=await Zl({name:t,type:n,description:i,namespace:ci()});return s?.storeId&&(pi[t]=s.storeId),JSON.stringify({...s,store:t})}case"sqlite_exec":case"sqlite_query":{let t=nr(e?.store);if(t.error)return JSON.stringify({error:t.error});if(typeof e?.sql!="string"||!e.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let n={sql:e.sql};Array.isArray(e?.params)&&(n.params=e.params);let i=await ir(t.storeId,"sql",n);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics.'},description:{type:"string",description:"What this store is for (shown in the Storage UI)."}},required:["name"]}},{name:"sqlite_exec",description:"For SQLITE-type stores: run SQL that CHANGES data \u2014 CREATE TABLE (use IF NOT EXISTS), INSERT, UPDATE, DELETE (one or more statements in one call). The store is a real, mutable SQLite database that persists across your stateless runs. Returns { rowsModified, wrote }. Use this to build schema on the fly and to update rows / track changing state (e.g. a queue with a status column).",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:'The SQL to run. May contain multiple statements separated by ";". Prefer CREATE TABLE IF NOT EXISTS for idempotent schema.'},params:{type:"array",description:'Optional positional bind params for a SINGLE parameterized statement (safe binding of values), e.g. sql "UPDATE t SET s=? WHERE id=?" with params ["done", 1].'}},required:["sql"]}},{name:"sqlite_query",description:"For SQLITE-type stores: run a read-only SELECT (optionally with `params` for safe binding) against the store's SQLite database. Returns { columns, rows }. Never changes data. Use to read back rows/state you stored earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:"A single SELECT statement. Use ? placeholders + `params` for any values."},params:{type:"array",description:'Optional positional bind params for the SELECT, e.g. ["linkedin_personal"].'}},required:["sql"]}}]};import{createRequire as Vl}from"node:module";import{existsSync as yi,mkdirSync as Ql,writeFileSync as fi}from"node:fs";import{dirname as _i,join as $e,resolve as bi}from"node:path";import{fileURLToPath as ki}from"node:url";var wi=Vl(import.meta.url),sr=null;function Xl(){return sr||(sr=wi("echarts")),sr}var or=null;function ed(){return or||(or=wi("@resvg/resvg-js")),or}var td=800,rd=600,nd=4096,id=16,hi=60,Si="Noto Sans";function sd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=_i(ki(import.meta.url)),e=bi(r,"..","bin","mcp-skill.mjs");return yi(e)?e:null}function od(){let r=_i(ki(import.meta.url)),e=bi(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>$e(e,t)).filter(t=>yi(t))}function ad(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?$e(e,"chart-render"):$e(process.cwd(),".zibby","output","charts"));return Ql(t,{recursive:!0}),t}function ke(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function gi(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(id,Math.min(nd,Math.round(t))):e}function ar(r){return typeof r!="string"||r.length<=hi?r:`${r.slice(0,hi-1)}\u2026`}function kt(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=ar(t):ke(t)&&typeof t.name=="string"&&(t.name=ar(t.name))}}function cd(r){for(let n of["xAxis","yAxis"]){let i=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let s of i)ke(s)&&kt(s.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of e)ke(n)&&kt(n.indicator);ke(r.legend)&&kt(r.legend.data);let t=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of t)ke(n)&&(typeof n.name=="string"&&(n.name=ar(n.name)),kt(n.data))}function ld(r){let e=JSON.parse(JSON.stringify(r));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),ke(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=Si),cd(e),e}function dd(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function ud(r,e,t){let i=Xl().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return i.setOption(r),i.renderToSVGString()}finally{i.dispose()}}function pd(r){let{Resvg:e}=ed();return new e(r,{font:{fontFiles:od(),loadSystemFonts:!0,defaultFontFamily:Si}}).render().asPng()}var Ii={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)
750
750
  You can render charts LOCALLY with the chart_render tool \u2014 pass a standard
751
751
  Apache ECharts option object as \`spec\` (any chart type: bar, line, pie,
752
752
  radar, scatter, heatmap, \u2026). It renders server-side to SVG/PNG files in the
753
753
  run's output folder (auto-attached to the run as artifacts) and returns the
754
754
  file paths. No browser, no external chart service \u2014 the data never leaves
755
- the machine. Don't set animation (it's forced off). Default 800\xD7600 PNG.`,resolve({sessionPath:r,nodeName:e}={}){let t=sd();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?$e(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/chartRender.js","chartRenderSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="chart_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.spec;if(!ke(t))return JSON.stringify({error:"spec must be a plain ECharts option OBJECT (e.g. { xAxis: {...}, yAxis: {...}, series: [...] }) \u2014 got "+(t===null?"null":Array.isArray(t)?"an array":typeof t)+". Pass the option object itself, not a string or an array."});let n=gi(e?.width,td),i=gi(e?.height,rd),s=["svg","png","both"].includes(e?.output)?e.output:"png",o=dd(e?.filename)||`chart-${Date.now()}`,a;try{a=ud(ld(t),n,i)}catch(l){return JSON.stringify({error:`Chart render failed: ${l.message}. The spec must be a valid Apache ECharts option (check series[].type, and that xAxis/yAxis/radar match the series type). Fix the spec and retry.`})}if(typeof a!="string"||!a.includes("<svg"))return JSON.stringify({error:"Chart render produced no SVG \u2014 the spec likely describes an empty chart (no series?). Add at least one series and retry."});let c=ad(),d=[];if(s==="svg"||s==="both"){let l=$e(c,`${o}.svg`);fi(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=pd(a)}catch(p){return JSON.stringify({error:`PNG rasterization failed: ${p.message}. Retry with output:'svg' if you only need the vector.`})}let u=$e(c,`${o}.png`);fi(u,l),d.push({path:u,format:"png",bytes:l.length})}return JSON.stringify({ok:!0,width:n,height:i,files:d})}catch(t){return JSON.stringify({error:`chart_render failed: ${t.message}`})}},tools:[{name:"chart_render",description:'Render a chart LOCALLY (no external service) from a standard Apache ECharts option and save it as SVG/PNG files in the run output folder. Pass the raw ECharts option as `spec` \u2014 every ECharts chart type works (bar, line, pie, radar, scatter, heatmap, \u2026). Returns the written file path(s). animation is forced off; background defaults to white. Bar example: {"xAxis":{"type":"category","data":["Q1","Q2"]},"yAxis":{},"series":[{"type":"bar","data":[12,30]}]}. Radar example: {"legend":{"data":["A","B"]},"radar":{"indicator":[{"name":"speed","max":10},{"name":"cost","max":10},{"name":"quality","max":10}]},"series":[{"type":"radar","data":[{"name":"A","value":[7,4,9]},{"name":"B","value":[5,8,6]}]}]}.',input_schema:{type:"object",properties:{spec:{type:"object",description:"The Apache ECharts option object, passed through as-is (series, xAxis/yAxis, radar, legend, title, \u2026)."},width:{type:"number",description:"Image width in px (default 800, max 4096)."},height:{type:"number",description:"Image height in px (default 600, max 4096)."},output:{type:"string",enum:["svg","png","both"],description:"Which file(s) to write (default 'png')."},filename:{type:"string",description:"Optional file basename (no extension); defaults to chart-<timestamp>."}},required:["spec"]}}]};import{createRequire as md}from"node:module";import{existsSync as Ri,mkdirSync as fd,writeFileSync as vi}from"node:fs";import{dirname as Ti,join as je,resolve as Ai}from"node:path";import{fileURLToPath as xi}from"node:url";var hd=md(import.meta.url),lr=null;function gd(){return lr||(lr=hd("@resvg/resvg-js")),lr}var Ei=1200,yd=627,_d=4096,bd=320,kd="#3b82f6",we="Noto Sans",wd=3;function Sd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ti(xi(import.meta.url)),e=Ai(r,"..","bin","mcp-skill.mjs");return Ri(e)?e:null}function Id(){let r=Ti(xi(import.meta.url)),e=Ai(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>je(e,t)).filter(t=>Ri(t))}function vd(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?je(e,"social-card"):je(process.cwd(),".zibby","output","social-cards"));return fd(t,{recursive:!0}),t}function Ni(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(bd,Math.min(_d,Math.round(t))):e}function Le(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Nd(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Od(r,e){if(typeof r!="string")return e;let t=r.trim();return/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(t)?t:e}function $i(r,e,t){return String(r).length*e*t}function dr(r,e,t,n){let i=String(r).trim().split(/\s+/).filter(Boolean),s=[],o="";for(let a of i){let c=o?`${o} ${a}`:a;o&&$i(c,t,n)>e?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function Rd(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 Oi(r,e,t,n,i){let s=(Array.isArray(r)?r:[]).map(y=>String(y??"").trim()).filter(Boolean).slice(0,wd);if(s.length<2)return null;let o=24,a=54,c=26,d=90,l=17,u=s.map(y=>Math.max(96,$i(y,o,.58)+c*2)),p=u.reduce((y,_)=>y+_,0)+d*(s.length-1),m=e-p/2,f=t+a/2,h=[];for(let y=0;y<s.length;y++){let _=u[y];if(h.push(`<rect x="${m.toFixed(1)}" y="${t}" width="${_.toFixed(1)}" height="${a}" rx="${a/2}" fill="${i}" fill-opacity="0.12" stroke="${i}" stroke-opacity="0.55" stroke-width="1.5"/>`,`<text x="${(m+_/2).toFixed(1)}" y="${(f+o*.35).toFixed(1)}" text-anchor="middle" font-family="${we}" font-size="${o}" font-weight="700" fill="${n.pillText}">${Le(s[y])}</text>`),m+=_,y<s.length-1){let b=m,g=m+d,w=(b+g)/2;h.push(`<line x1="${b.toFixed(1)}" y1="${f}" x2="${g.toFixed(1)}" y2="${f}" stroke="${i}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${w.toFixed(1)}" cy="${f}" r="${l}" fill="${i}"/>`,`<path d="M ${(w-8).toFixed(1)} ${f.toFixed(1)} l 5 5 l 9 -11" fill="none" stroke="${n.checkFg}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`),m=g}}return{svg:h.join(`
756
- `),height:a}}function Td(r){let{width:e,height:t,theme:n,accent:i}=r,s=Rd(n),o=e/2,a=Math.round(e*.07),c=e-a*2,d=String(r.headline).trim(),l=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",u=r.subhead?String(r.subhead).trim():"",p=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=e/Ei,h=Math.round(22*f),y=Math.round(29*f),_=u?dr(u,c,y,.52):[],b=Math.round(y*1.28),g=4,w=Math.round(26*f),T=Math.round(20*f),F=Math.round(24*f),Ie=Math.round(30*f),R=!!(p||m),O=a,D=R?Math.round(110*f):a,x=t-O-D,pe=Oi(r.diagram,o,0,s,i),_r=(L,oe)=>{let Ce=g+w;return l&&(Ce+=h+T),Ce+=oe.length*Math.round(L*1.16),_.length&&(Ce+=F+_.length*b),pe&&(Ce+=Ie+pe.height),Ce},At=[76,66,58,50,44,38].map(L=>Math.round(L*f)),cs=4,ve=At[At.length-1],xt=dr(d,c,ve,.6);for(let L of At){let oe=dr(d,c,L,.6);if(oe.length<=cs&&_r(L,oe)<=x){ve=L,xt=oe;break}}let ls=Math.round(ve*1.16),ds=_r(ve,xt),G=O+Math.max(0,(x-ds)/2),re=[];re.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${s.bg}"/>`);let br=Math.round(60*f);re.push(`<rect x="${(o-br/2).toFixed(1)}" y="${G}" width="${br}" height="${g}" rx="2" fill="${i}"/>`),G+=g+w,l&&(re.push(`<text x="${o}" y="${(G+h*.82).toFixed(1)}" text-anchor="middle" font-family="${we}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${i}">${Le(l)}</text>`),G+=h+T);for(let L of xt)re.push(`<text x="${o}" y="${(G+ve*.82).toFixed(1)}" text-anchor="middle" font-family="${we}" font-size="${ve}" font-weight="700" fill="${s.fg}">${Le(L)}</text>`),G+=ls;if(_.length){G+=F;for(let L of _)re.push(`<text x="${o}" y="${(G+y*.82).toFixed(1)}" text-anchor="middle" font-family="${we}" font-size="${y}" font-weight="400" fill="${s.muted}">${Le(L)}</text>`),G+=b}if(pe){G+=Ie;let L=Oi(r.diagram,o,G,s,i);L&&re.push(L.svg)}if(R){let L=Math.round(24*f),oe=t-Math.round(46*f);m&&re.push(`<text x="${a}" y="${oe}" text-anchor="start" font-family="${we}" font-size="${L}" font-weight="400" fill="${s.muted}">${Le(m)}</text>`),p&&re.push(`<text x="${e-a}" y="${oe}" text-anchor="end" font-family="${we}" font-size="${L}" font-weight="700" fill="${i}">${Le(p)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
755
+ the machine. Don't set animation (it's forced off). Default 800\xD7600 PNG.`,resolve({sessionPath:r,nodeName:e}={}){let t=sd();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?$e(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/chartRender.js","chartRenderSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="chart_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.spec;if(!ke(t))return JSON.stringify({error:"spec must be a plain ECharts option OBJECT (e.g. { xAxis: {...}, yAxis: {...}, series: [...] }) \u2014 got "+(t===null?"null":Array.isArray(t)?"an array":typeof t)+". Pass the option object itself, not a string or an array."});let n=gi(e?.width,td),i=gi(e?.height,rd),s=["svg","png","both"].includes(e?.output)?e.output:"png",o=dd(e?.filename)||`chart-${Date.now()}`,a;try{a=ud(ld(t),n,i)}catch(l){return JSON.stringify({error:`Chart render failed: ${l.message}. The spec must be a valid Apache ECharts option (check series[].type, and that xAxis/yAxis/radar match the series type). Fix the spec and retry.`})}if(typeof a!="string"||!a.includes("<svg"))return JSON.stringify({error:"Chart render produced no SVG \u2014 the spec likely describes an empty chart (no series?). Add at least one series and retry."});let c=ad(),d=[];if(s==="svg"||s==="both"){let l=$e(c,`${o}.svg`);fi(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=pd(a)}catch(p){return JSON.stringify({error:`PNG rasterization failed: ${p.message}. Retry with output:'svg' if you only need the vector.`})}let u=$e(c,`${o}.png`);fi(u,l),d.push({path:u,format:"png",bytes:l.length})}return JSON.stringify({ok:!0,width:n,height:i,files:d})}catch(t){return JSON.stringify({error:`chart_render failed: ${t.message}`})}},tools:[{name:"chart_render",description:'Render a chart LOCALLY (no external service) from a standard Apache ECharts option and save it as SVG/PNG files in the run output folder. Pass the raw ECharts option as `spec` \u2014 every ECharts chart type works (bar, line, pie, radar, scatter, heatmap, \u2026). Returns the written file path(s). animation is forced off; background defaults to white. Bar example: {"xAxis":{"type":"category","data":["Q1","Q2"]},"yAxis":{},"series":[{"type":"bar","data":[12,30]}]}. Radar example: {"legend":{"data":["A","B"]},"radar":{"indicator":[{"name":"speed","max":10},{"name":"cost","max":10},{"name":"quality","max":10}]},"series":[{"type":"radar","data":[{"name":"A","value":[7,4,9]},{"name":"B","value":[5,8,6]}]}]}.',input_schema:{type:"object",properties:{spec:{type:"object",description:"The Apache ECharts option object, passed through as-is (series, xAxis/yAxis, radar, legend, title, \u2026)."},width:{type:"number",description:"Image width in px (default 800, max 4096)."},height:{type:"number",description:"Image height in px (default 600, max 4096)."},output:{type:"string",enum:["svg","png","both"],description:"Which file(s) to write (default 'png')."},filename:{type:"string",description:"Optional file basename (no extension); defaults to chart-<timestamp>."}},required:["spec"]}}]};import{createRequire as md}from"node:module";import{existsSync as Ri,mkdirSync as fd,writeFileSync as vi}from"node:fs";import{dirname as Ti,join as je,resolve as Ai}from"node:path";import{fileURLToPath as xi}from"node:url";var hd=md(import.meta.url),cr=null;function gd(){return cr||(cr=hd("@resvg/resvg-js")),cr}var Ei=1200,yd=627,_d=4096,bd=320,kd="#3b82f6",we="Noto Sans",wd=3;function Sd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ti(xi(import.meta.url)),e=Ai(r,"..","bin","mcp-skill.mjs");return Ri(e)?e:null}function Id(){let r=Ti(xi(import.meta.url)),e=Ai(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>je(e,t)).filter(t=>Ri(t))}function vd(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?je(e,"social-card"):je(process.cwd(),".zibby","output","social-cards"));return fd(t,{recursive:!0}),t}function Ni(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(bd,Math.min(_d,Math.round(t))):e}function Le(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Nd(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Od(r,e){if(typeof r!="string")return e;let t=r.trim();return/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(t)?t:e}function $i(r,e,t){return String(r).length*e*t}function lr(r,e,t,n){let i=String(r).trim().split(/\s+/).filter(Boolean),s=[],o="";for(let a of i){let c=o?`${o} ${a}`:a;o&&$i(c,t,n)>e?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function Rd(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 Oi(r,e,t,n,i){let s=(Array.isArray(r)?r:[]).map(y=>String(y??"").trim()).filter(Boolean).slice(0,wd);if(s.length<2)return null;let o=24,a=54,c=26,d=90,l=17,u=s.map(y=>Math.max(96,$i(y,o,.58)+c*2)),p=u.reduce((y,_)=>y+_,0)+d*(s.length-1),m=e-p/2,f=t+a/2,h=[];for(let y=0;y<s.length;y++){let _=u[y];if(h.push(`<rect x="${m.toFixed(1)}" y="${t}" width="${_.toFixed(1)}" height="${a}" rx="${a/2}" fill="${i}" fill-opacity="0.12" stroke="${i}" stroke-opacity="0.55" stroke-width="1.5"/>`,`<text x="${(m+_/2).toFixed(1)}" y="${(f+o*.35).toFixed(1)}" text-anchor="middle" font-family="${we}" font-size="${o}" font-weight="700" fill="${n.pillText}">${Le(s[y])}</text>`),m+=_,y<s.length-1){let b=m,g=m+d,w=(b+g)/2;h.push(`<line x1="${b.toFixed(1)}" y1="${f}" x2="${g.toFixed(1)}" y2="${f}" stroke="${i}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${w.toFixed(1)}" cy="${f}" r="${l}" fill="${i}"/>`,`<path d="M ${(w-8).toFixed(1)} ${f.toFixed(1)} l 5 5 l 9 -11" fill="none" stroke="${n.checkFg}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`),m=g}}return{svg:h.join(`
756
+ `),height:a}}function Td(r){let{width:e,height:t,theme:n,accent:i}=r,s=Rd(n),o=e/2,a=Math.round(e*.07),c=e-a*2,d=String(r.headline).trim(),l=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",u=r.subhead?String(r.subhead).trim():"",p=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=e/Ei,h=Math.round(22*f),y=Math.round(29*f),_=u?lr(u,c,y,.52):[],b=Math.round(y*1.28),g=4,w=Math.round(26*f),T=Math.round(20*f),F=Math.round(24*f),Ie=Math.round(30*f),R=!!(p||m),O=a,D=R?Math.round(110*f):a,x=t-O-D,pe=Oi(r.diagram,o,0,s,i),_r=(L,oe)=>{let Ce=g+w;return l&&(Ce+=h+T),Ce+=oe.length*Math.round(L*1.16),_.length&&(Ce+=F+_.length*b),pe&&(Ce+=Ie+pe.height),Ce},Tt=[76,66,58,50,44,38].map(L=>Math.round(L*f)),cs=4,ve=Tt[Tt.length-1],At=lr(d,c,ve,.6);for(let L of Tt){let oe=lr(d,c,L,.6);if(oe.length<=cs&&_r(L,oe)<=x){ve=L,At=oe;break}}let ls=Math.round(ve*1.16),ds=_r(ve,At),G=O+Math.max(0,(x-ds)/2),re=[];re.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${s.bg}"/>`);let br=Math.round(60*f);re.push(`<rect x="${(o-br/2).toFixed(1)}" y="${G}" width="${br}" height="${g}" rx="2" fill="${i}"/>`),G+=g+w,l&&(re.push(`<text x="${o}" y="${(G+h*.82).toFixed(1)}" text-anchor="middle" font-family="${we}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${i}">${Le(l)}</text>`),G+=h+T);for(let L of At)re.push(`<text x="${o}" y="${(G+ve*.82).toFixed(1)}" text-anchor="middle" font-family="${we}" font-size="${ve}" font-weight="700" fill="${s.fg}">${Le(L)}</text>`),G+=ls;if(_.length){G+=F;for(let L of _)re.push(`<text x="${o}" y="${(G+y*.82).toFixed(1)}" text-anchor="middle" font-family="${we}" font-size="${y}" font-weight="400" fill="${s.muted}">${Le(L)}</text>`),G+=b}if(pe){G+=Ie;let L=Oi(r.diagram,o,G,s,i);L&&re.push(L.svg)}if(R){let L=Math.round(24*f),oe=t-Math.round(46*f);m&&re.push(`<text x="${a}" y="${oe}" text-anchor="start" font-family="${we}" font-size="${L}" font-weight="400" fill="${s.muted}">${Le(m)}</text>`),p&&re.push(`<text x="${e-a}" y="${oe}" text-anchor="end" font-family="${we}" font-size="${L}" font-weight="700" fill="${i}">${Le(p)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
757
757
  ${re.join(`
758
758
  `)}
759
759
  </svg>`}function Ad(r){let{Resvg:e}=gd();return new e(r,{font:{fontFiles:Id(),loadSystemFonts:!0,defaultFontFamily:we}}).render().asPng()}var Li={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)
@@ -770,15 +770,15 @@ fields that capture the ONE key idea of your post:
770
770
  It renders server-side to a PNG in the run's output folder and returns
771
771
  { ok:true, files:[{ path, format:'png', bytes }] }. Pass the returned \`path\` as
772
772
  \`imagePath\` when you draft/publish a LinkedIn post to ATTACH the card as the
773
- post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=Sd();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?je(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/socialCard.js","socialCardSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="social_card_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.headline;if(typeof t!="string"||!t.trim())return JSON.stringify({error:"headline (the big bold line) is required and must be a non-empty string."});let n=Ni(e?.width,Ei),i=Ni(e?.height,yd),s=e?.theme==="light"?"light":"dark",o=Od(e?.accent,kd),a;try{a=Td({width:n,height:i,theme:s,accent:o,headline:t,eyebrow:e?.eyebrow,subhead:e?.subhead,stat:e?.stat,footer:e?.footer,diagram:e?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=Ad(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=vd(),l=Nd(e?.filename)||`social-card-${Date.now()}`,u=je(d,`${l}.png`);vi(u,c);let p=[{path:u,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=je(d,`${l}.svg`);vi(m,a,"utf-8"),p.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:i,theme:s,files:p})}catch(t){return JSON.stringify({error:`social_card_render failed: ${t.message}`})}},tools:[{name:"social_card_render",description:'Render a BRANDED "concept card" PNG LOCALLY (no external service) from structured fields \u2014 the clean LinkedIn concept-card style: bold headline + small uppercase eyebrow + optional supporting subhead, stat, footer, and an A\u2014\u2713\u2014B diagram. Returns { ok:true, files:[{ path, format:"png", bytes }] }. Pass the returned `path` as `imagePath` to a LinkedIn post tool to attach it as the post image. Example: { "headline":"No more copy-paste between AI tools", "eyebrow":"MY WORKFLOW", "stat":"11.8k stars", "footer":"Apache 2.0", "diagram":["Claude Code","Codex"] }.',input_schema:{type:"object",properties:{headline:{type:"string",description:"REQUIRED. The big, bold line \u2014 the single key idea/takeaway. Word-wrapped + auto-sized."},eyebrow:{type:"string",description:'Small uppercase kicker above the headline (e.g. "MY WORKFLOW", "OPEN SOURCE"). Rendered uppercased in the accent color.'},subhead:{type:"string",description:"One supporting line under the headline (muted)."},stat:{type:"string",description:'Optional stat, shown bottom-right in the accent color (e.g. "11.8k stars", "3x faster").'},footer:{type:"string",description:'Optional footer, shown bottom-left (muted) (e.g. "Apache 2.0", a repo name).'},diagram:{type:"array",items:{type:"string"},description:'Optional 2-3 short labels rendered as a chain of pills joined by a checkmark (A \u2014\u2713\u2014 B), e.g. ["Claude Code","Codex"].'},theme:{type:"string",enum:["dark","light"],description:"Card theme (default 'dark' \u2014 near-black bg, off-white text)."},accent:{type:"string",description:'Accent hex color (e.g. "#f97316"). Defaults to a tasteful blue (#3b82f6).'},width:{type:"number",description:"Image width in px (default 1200 \u2014 LinkedIn 1.91:1 link image)."},height:{type:"number",description:"Image height in px (default 627)."},filename:{type:"string",description:"Optional file basename (no extension); defaults to social-card-<timestamp>."},output:{type:"string",enum:["png","both"],description:"Which file(s) to write (default 'png'; 'both' also writes the .svg)."}},required:["headline"]}}]};import{spawnSync as xd}from"node:child_process";import{existsSync as z,readdirSync as Ed,statSync as ji,writeFileSync as $d,mkdirSync as Ld}from"node:fs";import{dirname as It,extname as Pi,join as te,relative as jd,resolve as We}from"node:path";import{tmpdir as Pd}from"node:os";import{fileURLToPath as Cd}from"node:url";import{createRequire as Ud}from"node:module";import{SKILL_META as Dd}from"@zibby/skill-ids";var qd=Ud(import.meta.url);function Jd(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=qd.resolve("oxlint/package.json"),e=We(It(r),"bin","oxlint");if(z(e))return e}catch{}return"oxlint"}function Bd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=It(Cd(import.meta.url)),e=We(r,"..","bin","mcp-skill.mjs");return z(e)?e:null}var Md=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),Fd=400,Gd={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"}},Kd=[".oxlintrc.json",".oxlintrc","oxlint.json"],St=null;function Hd(){if(St&&z(St))return St;try{let r=te(Pd(),"zibby-code-scan");Ld(r,{recursive:!0});let e=te(r,"oxlintrc.curated.json");return $d(e,JSON.stringify(Gd),"utf-8"),St=e,e}catch{return null}}function zd(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return(Array.isArray(t)?t:t&&Array.isArray(t.diagnostics)?t.diagnostics:[]).map(i=>{if(!i||typeof i!="object")return null;let s=Array.isArray(i.labels)&&i.labels.length?i.labels[0]:null,o=s&&s.span?s.span:null;return{file:i.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:i.severity||"warning",rule:i.code||"",message:i.message||""}}).filter(i=>i&&(i.file||i.message))}function Wd(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.map(n=>n&&typeof n=="object"?{file:n.filename||"",line:n.location&&Number.isFinite(n.location.row)?n.location.row:"",severity:"warning",rule:n.code||"",message:n.message||""}:null).filter(n=>n&&(n.file||n.message)):[]}function Yd(r){let e=String(r||"").trim();if(!e)return[];let t=[];for(let n of e.split(`
774
- `)){let i=n.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{continue}if(!s||typeof s!="object")continue;let o=s.location||{};t.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""})}return t.filter(n=>n.file||n.message)}var Zd=[{id:"oxlint",detect:r=>z(te(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>Jd(),args:(r,e={})=>{let t=e.baseDir||".",i=Kd.some(o=>z(te(t,o)))?null:Hd();return["--format","json",...i?["--config",i]:[],...r]},parse:zd},{id:"ruff",detect:r=>z(te(r,"pyproject.toml"))||z(te(r,"requirements.txt"))||z(te(r,"setup.py")),langs:[".py"],bin:()=>process.env.RUFF_BIN||"ruff",args:r=>["check","--output-format","json",...r],parse:Wd},{id:"staticcheck",detect:r=>z(te(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:Yd}];function Vd(r,e,t){let n=[],i=new Set(e.map(o=>o.toLowerCase())),s=[r];for(;s.length&&n.length<t;){let o=s.pop(),a;try{a=Ed(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(n.length>=t)break;c.isDirectory()?!Md.has(c.name)&&!c.name.startsWith(".")&&s.push(te(o,c.name)):c.isFile()&&i.has(Pi(c.name).toLowerCase())&&n.push(te(o,c.name))}}return n}function Qd(r,e,t){let n=t.map(a=>jd(e,a)).filter(Boolean);if(!n.length)return{scanner:r.id,skipped:"no matching files"};let i=r.bin(),s=xd(i,r.args(n,{baseDir:e}),{cwd:e,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(s.error){let a=s.error.code==="ENOENT"?`binary not installed (${i})`:String(s.error.message||s.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(s.stdout,s.stderr,s.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:n.length,findings:o}}var Ci={id:"code-scan",serverName:"code_scan",meta:Dd["code-scan"],allowedTools:["mcp__code_scan__*"],description:"Code scan \u2014 run the RIGHT deterministic linter for a checked-out repo (auto-detects the stack: JS/TS\u2192oxlint, etc.) and return structured findings. Fully local; the code never leaves the box.",promptFragment:`## Code Scan (deterministic linter, auto-detects the stack)
773
+ post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=Sd();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?je(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/socialCard.js","socialCardSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="social_card_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.headline;if(typeof t!="string"||!t.trim())return JSON.stringify({error:"headline (the big bold line) is required and must be a non-empty string."});let n=Ni(e?.width,Ei),i=Ni(e?.height,yd),s=e?.theme==="light"?"light":"dark",o=Od(e?.accent,kd),a;try{a=Td({width:n,height:i,theme:s,accent:o,headline:t,eyebrow:e?.eyebrow,subhead:e?.subhead,stat:e?.stat,footer:e?.footer,diagram:e?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=Ad(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=vd(),l=Nd(e?.filename)||`social-card-${Date.now()}`,u=je(d,`${l}.png`);vi(u,c);let p=[{path:u,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=je(d,`${l}.svg`);vi(m,a,"utf-8"),p.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:i,theme:s,files:p})}catch(t){return JSON.stringify({error:`social_card_render failed: ${t.message}`})}},tools:[{name:"social_card_render",description:'Render a BRANDED "concept card" PNG LOCALLY (no external service) from structured fields \u2014 the clean LinkedIn concept-card style: bold headline + small uppercase eyebrow + optional supporting subhead, stat, footer, and an A\u2014\u2713\u2014B diagram. Returns { ok:true, files:[{ path, format:"png", bytes }] }. Pass the returned `path` as `imagePath` to a LinkedIn post tool to attach it as the post image. Example: { "headline":"No more copy-paste between AI tools", "eyebrow":"MY WORKFLOW", "stat":"11.8k stars", "footer":"Apache 2.0", "diagram":["Claude Code","Codex"] }.',input_schema:{type:"object",properties:{headline:{type:"string",description:"REQUIRED. The big, bold line \u2014 the single key idea/takeaway. Word-wrapped + auto-sized."},eyebrow:{type:"string",description:'Small uppercase kicker above the headline (e.g. "MY WORKFLOW", "OPEN SOURCE"). Rendered uppercased in the accent color.'},subhead:{type:"string",description:"One supporting line under the headline (muted)."},stat:{type:"string",description:'Optional stat, shown bottom-right in the accent color (e.g. "11.8k stars", "3x faster").'},footer:{type:"string",description:'Optional footer, shown bottom-left (muted) (e.g. "Apache 2.0", a repo name).'},diagram:{type:"array",items:{type:"string"},description:'Optional 2-3 short labels rendered as a chain of pills joined by a checkmark (A \u2014\u2713\u2014 B), e.g. ["Claude Code","Codex"].'},theme:{type:"string",enum:["dark","light"],description:"Card theme (default 'dark' \u2014 near-black bg, off-white text)."},accent:{type:"string",description:'Accent hex color (e.g. "#f97316"). Defaults to a tasteful blue (#3b82f6).'},width:{type:"number",description:"Image width in px (default 1200 \u2014 LinkedIn 1.91:1 link image)."},height:{type:"number",description:"Image height in px (default 627)."},filename:{type:"string",description:"Optional file basename (no extension); defaults to social-card-<timestamp>."},output:{type:"string",enum:["png","both"],description:"Which file(s) to write (default 'png'; 'both' also writes the .svg)."}},required:["headline"]}}]};import{spawnSync as xd}from"node:child_process";import{existsSync as z,readdirSync as Ed,statSync as ji,writeFileSync as $d,mkdirSync as Ld}from"node:fs";import{dirname as dr,extname as Pi,join as te,relative as jd,resolve as St}from"node:path";import{tmpdir as Pd}from"node:os";import{fileURLToPath as Cd}from"node:url";import{SKILL_META as Ud}from"@zibby/skill-ids";import{binPath as Dd}from"@zibby/bin-oxlint";function qd(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=Dd();if(r&&z(r))return r}catch{}return"oxlint"}function Jd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=dr(Cd(import.meta.url)),e=St(r,"..","bin","mcp-skill.mjs");return z(e)?e:null}var Bd=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),Md=400,Fd={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"}},Gd=[".oxlintrc.json",".oxlintrc","oxlint.json"],wt=null;function Kd(){if(wt&&z(wt))return wt;try{let r=te(Pd(),"zibby-code-scan");Ld(r,{recursive:!0});let e=te(r,"oxlintrc.curated.json");return $d(e,JSON.stringify(Fd),"utf-8"),wt=e,e}catch{return null}}function Hd(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return(Array.isArray(t)?t:t&&Array.isArray(t.diagnostics)?t.diagnostics:[]).map(i=>{if(!i||typeof i!="object")return null;let s=Array.isArray(i.labels)&&i.labels.length?i.labels[0]:null,o=s&&s.span?s.span:null;return{file:i.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:i.severity||"warning",rule:i.code||"",message:i.message||""}}).filter(i=>i&&(i.file||i.message))}function zd(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.map(n=>n&&typeof n=="object"?{file:n.filename||"",line:n.location&&Number.isFinite(n.location.row)?n.location.row:"",severity:"warning",rule:n.code||"",message:n.message||""}:null).filter(n=>n&&(n.file||n.message)):[]}function Wd(r){let e=String(r||"").trim();if(!e)return[];let t=[];for(let n of e.split(`
774
+ `)){let i=n.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{continue}if(!s||typeof s!="object")continue;let o=s.location||{};t.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""})}return t.filter(n=>n.file||n.message)}var Yd=[{id:"oxlint",detect:r=>z(te(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>qd(),args:(r,e={})=>{let t=e.baseDir||".",i=Gd.some(o=>z(te(t,o)))?null:Kd();return["--format","json",...i?["--config",i]:[],...r]},parse:Hd},{id:"ruff",detect:r=>z(te(r,"pyproject.toml"))||z(te(r,"requirements.txt"))||z(te(r,"setup.py")),langs:[".py"],bin:()=>process.env.RUFF_BIN||"ruff",args:r=>["check","--output-format","json",...r],parse:zd},{id:"staticcheck",detect:r=>z(te(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:Wd}];function Zd(r,e,t){let n=[],i=new Set(e.map(o=>o.toLowerCase())),s=[r];for(;s.length&&n.length<t;){let o=s.pop(),a;try{a=Ed(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(n.length>=t)break;c.isDirectory()?!Bd.has(c.name)&&!c.name.startsWith(".")&&s.push(te(o,c.name)):c.isFile()&&i.has(Pi(c.name).toLowerCase())&&n.push(te(o,c.name))}}return n}function Vd(r,e,t){let n=t.map(a=>jd(e,a)).filter(Boolean);if(!n.length)return{scanner:r.id,skipped:"no matching files"};let i=r.bin(),s=xd(i,r.args(n,{baseDir:e}),{cwd:e,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(s.error){let a=s.error.code==="ENOENT"?`binary not installed (${i})`:String(s.error.message||s.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(s.stdout,s.stderr,s.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:n.length,findings:o}}var Ci={id:"code-scan",serverName:"code_scan",meta:Ud["code-scan"],allowedTools:["mcp__code_scan__*"],description:"Code scan \u2014 run the RIGHT deterministic linter for a checked-out repo (auto-detects the stack: JS/TS\u2192oxlint, etc.) and return structured findings. Fully local; the code never leaves the box.",promptFragment:`## Code Scan (deterministic linter, auto-detects the stack)
775
775
  After you've cloned the repo, call \`scan_code\` to get DETERMINISTIC linter
776
776
  findings for WHATEVER stack this repo is \u2014 it auto-detects (JS/TS\u2192oxlint, more
777
777
  coming) and runs the matching tool. Pass \`files\` (the changed files, ideal for
778
778
  a review) or \`dir\` (a directory to scan). Findings are GROUND-TRUTH CANDIDATES:
779
779
  triage them for THIS change, verify each in context (false positives exist \u2014
780
780
  trace before asserting), fold noise, and turn the real ones into inline
781
- suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=Bd();return r?{type:"stdio",command:"node",args:[r,"../dist/code-scan.js","codeScanSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,e){if(r!=="scan_code")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=Array.isArray(e?.files)?e.files.filter(a=>typeof a=="string"&&a.trim()):null,n;if(e?.dir&&typeof e.dir=="string"?n=We(e.dir):t&&t.length?n=Xd(t.map(a=>We(a))):n=process.cwd(),!z(n)||!ji(n).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${n}`});let i=t?t.map(a=>We(n,a)):null,s=[],o=0;for(let a of Zd){let c=!1;try{c=!!a.detect(n)}catch{c=!1}if(!c)continue;let d=new Set(a.langs.map(p=>p.toLowerCase())),l=i?i.filter(p=>d.has(Pi(p).toLowerCase())):Vd(n,a.langs,Fd),u=Qd(a,n,l);Array.isArray(u.findings)&&(o+=u.findings.length),s.push(u)}return s.length?JSON.stringify({ok:!0,baseDir:n,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:n,scanners:[],totalFindings:0,note:"No known stack detected (no package.json / pyproject / go.mod \u2026). Review by hand."})}catch(t){return JSON.stringify({error:`scan_code failed: ${t.message}`})}},tools:[{name:"scan_code",description:"Run the right deterministic linter for a checked-out repo and return structured findings. Auto-detects the stack (JS/TS via package.json \u2192 oxlint; more scanners coming) 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 Xd(r){if(!r.length)return process.cwd();if(r.length===1)return It(r[0]);let e=r.map(s=>s.split("/")),t=e[0],n=[];for(let s=0;s<t.length;s++){let o=t[s];if(e.every(a=>a[s]===o))n.push(o);else break}let i=n.join("/");return i&&z(i)&&ji(i).isDirectory()?i:It(r[0])}import{dirname as eu,resolve as tu}from"path";import{fileURLToPath as ru}from"url";import{existsSync as nu}from"fs";function iu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=eu(ru(import.meta.url)),e=tu(r,"..","bin","mcp-skill.mjs");return nu(e)?e:null}function su(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function ou(){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 au={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:[]}},Ui={id:"trigger-agent",serverName:"trigger",allowedTools:["mcp__trigger__*"],envKeys:[],description:"Trigger another Zibby workflow/agent run in this project (agent-driven, fire-and-forget; cloud + self-hosted).",promptFragment:"## Trigger another agent (agent-driven)\nYou can start another Zibby agent run yourself with the `trigger_agent`\ntool \u2014 and YOU decide when and how many times to call it. Each call starts ONE\nindependent run (fire-and-forget) and returns its executionId; it does NOT wait for\nthat run to finish.\n- To re-run THIS same agent (self-dispatch) \u2014 e.g. to hand an item to another of\n this agent's scenarios \u2014 OMIT `workflowType` and pass the `input` for that run.\n- To trigger a DIFFERENT agent in the project, pass its `workflowType` + `input`.\nCall it once per run you want to start (loop over your items and call it for each).\nIt never throws \u2014 a failure comes back as { ok:false, error }; log it and move on.",resolve(){let r=iu();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","PROJECT_ID","WORKFLOW_TYPE","PROGRESS_API_URL","ZIBBY_ACCOUNT_API_URL","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_USER_TOKEN"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/triggerAgent.js","triggerAgentSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e={}){if(r!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${r}`});try{let t=process.env.PROJECT_ID,n=su(),i=typeof e.workflowType=="string"&&e.workflowType.trim()?e.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!t)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!n)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!i)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let s=`${ou()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(i)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(s,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({input:e.input&&typeof e.input=="object"?e.input:{}}),signal:o.signal})}finally{clearTimeout(a)}let d=await c.text().catch(()=>""),l;try{l=d?JSON.parse(d):{}}catch{l={raw:d}}if(!c.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${c.status})`,detail:l&&(l.error||l.message)||d.slice(0,300)});let u=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:u,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[au]};import{spawnSync as cu}from"node:child_process";import{existsSync as vt,mkdirSync as Di,readdirSync as lu,writeFileSync as du}from"node:fs";import{createHash as uu}from"node:crypto";import{join as Nt}from"node:path";import{SKILL_META as pu}from"@zibby/skill-ids";function qi(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function Ji(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?Nt(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function mu(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=Nt(r,".zibby","repos");try{if(vt(e)){let t=lu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>Nt(e,n.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return vt(r)?r:null}function fu(r){return uu("sha256").update(r).digest("hex").slice(0,16)}var Bi={id:"codebase-memory",serverName:"codebase_memory",meta:pu["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)
781
+ suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=Jd();return r?{type:"stdio",command:"node",args:[r,"../dist/code-scan.js","codeScanSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,e){if(r!=="scan_code")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=Array.isArray(e?.files)?e.files.filter(a=>typeof a=="string"&&a.trim()):null,n;if(e?.dir&&typeof e.dir=="string"?n=St(e.dir):t&&t.length?n=Qd(t.map(a=>St(a))):n=process.cwd(),!z(n)||!ji(n).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${n}`});let i=t?t.map(a=>St(n,a)):null,s=[],o=0;for(let a of Yd){let c=!1;try{c=!!a.detect(n)}catch{c=!1}if(!c)continue;let d=new Set(a.langs.map(p=>p.toLowerCase())),l=i?i.filter(p=>d.has(Pi(p).toLowerCase())):Zd(n,a.langs,Md),u=Vd(a,n,l);Array.isArray(u.findings)&&(o+=u.findings.length),s.push(u)}return s.length?JSON.stringify({ok:!0,baseDir:n,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:n,scanners:[],totalFindings:0,note:"No known stack detected (no package.json / pyproject / go.mod \u2026). Review by hand."})}catch(t){return JSON.stringify({error:`scan_code failed: ${t.message}`})}},tools:[{name:"scan_code",description:"Run the right deterministic linter for a checked-out repo and return structured findings. Auto-detects the stack (JS/TS via package.json \u2192 oxlint; more scanners coming) 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 Qd(r){if(!r.length)return process.cwd();if(r.length===1)return dr(r[0]);let e=r.map(s=>s.split("/")),t=e[0],n=[];for(let s=0;s<t.length;s++){let o=t[s];if(e.every(a=>a[s]===o))n.push(o);else break}let i=n.join("/");return i&&z(i)&&ji(i).isDirectory()?i:dr(r[0])}import{dirname as Xd,resolve as eu}from"path";import{fileURLToPath as tu}from"url";import{existsSync as ru}from"fs";function nu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Xd(tu(import.meta.url)),e=eu(r,"..","bin","mcp-skill.mjs");return ru(e)?e:null}function iu(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function su(){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 ou={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:[]}},Ui={id:"trigger-agent",serverName:"trigger",allowedTools:["mcp__trigger__*"],envKeys:[],description:"Trigger another Zibby workflow/agent run in this project (agent-driven, fire-and-forget; cloud + self-hosted).",promptFragment:"## Trigger another agent (agent-driven)\nYou can start another Zibby agent run yourself with the `trigger_agent`\ntool \u2014 and YOU decide when and how many times to call it. Each call starts ONE\nindependent run (fire-and-forget) and returns its executionId; it does NOT wait for\nthat run to finish.\n- To re-run THIS same agent (self-dispatch) \u2014 e.g. to hand an item to another of\n this agent's scenarios \u2014 OMIT `workflowType` and pass the `input` for that run.\n- To trigger a DIFFERENT agent in the project, pass its `workflowType` + `input`.\nCall it once per run you want to start (loop over your items and call it for each).\nIt never throws \u2014 a failure comes back as { ok:false, error }; log it and move on.",resolve(){let r=nu();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","PROJECT_ID","WORKFLOW_TYPE","PROGRESS_API_URL","ZIBBY_ACCOUNT_API_URL","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_USER_TOKEN"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/triggerAgent.js","triggerAgentSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e={}){if(r!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${r}`});try{let t=process.env.PROJECT_ID,n=iu(),i=typeof e.workflowType=="string"&&e.workflowType.trim()?e.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!t)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!n)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!i)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let s=`${su()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(i)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(s,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({input:e.input&&typeof e.input=="object"?e.input:{}}),signal:o.signal})}finally{clearTimeout(a)}let d=await c.text().catch(()=>""),l;try{l=d?JSON.parse(d):{}}catch{l={raw:d}}if(!c.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${c.status})`,detail:l&&(l.error||l.message)||d.slice(0,300)});let u=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:u,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[ou]};import{spawnSync as au}from"node:child_process";import{existsSync as It,mkdirSync as Di,readdirSync as cu,writeFileSync as lu}from"node:fs";import{createHash as du}from"node:crypto";import{join as vt}from"node:path";import{SKILL_META as uu}from"@zibby/skill-ids";function qi(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function Ji(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?vt(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function pu(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=vt(r,".zibby","repos");try{if(It(e)){let t=cu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>vt(e,n.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return It(r)?r:null}function mu(r){return du("sha256").update(r).digest("hex").slice(0,16)}var Bi={id:"codebase-memory",serverName:"codebase_memory",meta:uu["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)
782
782
  The checked-out repository is indexed into a queryable code graph + semantic
783
783
  index. Reach for these instead of blindly grepping when you need structure,
784
784
  relationships, or "where does X live / what depends on Y":
@@ -790,8 +790,8 @@ relationships, or "where does X live / what depends on Y":
790
790
  - get_code_snippet / search_code: pull the exact code for a node / text match.
791
791
  - index_status / list_projects: confirm the index is present before querying.
792
792
  The repo is indexed for you at the start of the run; if a query comes back
793
- empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=Ji();try{Di(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:qi(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=mu();if(!r)return{};let e=Ji();try{Di(e,{recursive:!0})}catch{}let t=Nt(e,`.cbm-indexed-${fu(r)}`);if(vt(t))return{};let n=qi();if(!vt(n)&&!process.env.CBM_BIN)return{};let i=cu(n,["cli","index_repository",JSON.stringify({repo_path:r})],{env:{...process.env,CBM_CACHE_DIR:e},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{du(t,`${new Date().toISOString()} status=${i.status}
794
- `)}catch{}}catch{}return{}}};import{existsSync as se,readFileSync as Ze,readdirSync as ur,mkdirSync as hu,writeFileSync as Pe,statSync as Gi}from"fs";import{join as A,resolve as pr,relative as Ki,dirname as Hi}from"path";import{fileURLToPath as gu}from"url";import{createRequire as yu}from"module";var _u=yu(import.meta.url),bu=`## Workflow Builder
793
+ empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=Ji();try{Di(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:qi(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=pu();if(!r)return{};let e=Ji();try{Di(e,{recursive:!0})}catch{}let t=vt(e,`.cbm-indexed-${mu(r)}`);if(It(t))return{};let n=qi();if(!It(n)&&!process.env.CBM_BIN)return{};let i=au(n,["cli","index_repository",JSON.stringify({repo_path:r})],{env:{...process.env,CBM_CACHE_DIR:e},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{lu(t,`${new Date().toISOString()} status=${i.status}
794
+ `)}catch{}}catch{}return{}}};import{existsSync as se,readFileSync as Ye,readdirSync as ur,mkdirSync as fu,writeFileSync as Pe,statSync as Gi}from"fs";import{join as A,resolve as pr,relative as Ki,dirname as Hi}from"path";import{fileURLToPath as hu}from"url";import{createRequire as gu}from"module";var yu=gu(import.meta.url),_u=`## Workflow Builder
795
795
 
796
796
  You can help users build custom AI workflows using the Zibby workflow framework.
797
797
 
@@ -901,9 +901,9 @@ Call with no arguments to see all available topics.
901
901
  - Workflow names must be kebab-case (e.g., ticket-triage, pr-review).
902
902
  - State flows through: each node's validated output is stored under its name in state (e.g., state.classify_ticket).
903
903
  - Downstream nodes reference upstream outputs in their prompt function (e.g., \\\`\\\${JSON.stringify(state.classify_ticket, null, 2)}\\\`).
904
- - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,zi=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function Wi(r){return`${r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function Ye(r){return`${r.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}Node`}function ku(r){let e=r?.agent;return e?e.provider?e.provider:e.gemini?"gemini":e.codex?"codex":e.claude?"claude":e.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function wu(r){let e=pr(r,".zibby.config.mjs");if(!se(e))return{};try{return(await import(e)).default||{}}catch{return{}}}function Su(){try{let r=Hi(_u.resolve("@zibby/core/package.json")),e=A(r,"templates","browser-test-automation"),t=Ze(A(e,"nodes","preflight.mjs"),"utf-8"),n=Ze(A(e,"graph.mjs"),"utf-8");return{preflight:t,graph:n}}catch{return null}}var Mi=Hi(gu(import.meta.url));function Yi(){let r=pr(Mi,"..","..","..","docsite","docs");if(se(r))return r;let e=pr(Mi,"..","docs");return se(e)?e:null}function Fi(){let r=Yi();if(!r)return[];try{let e=(t,n="")=>{let i=[];for(let s of ur(t)){let o=A(t,s);try{if(Gi(o).isDirectory())i=i.concat(e(o,`${n}${s}/`));else if(s.endsWith(".md")){let a=`${n}${s.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return e(r)}catch{return[]}}function Zi(r){let e=Yi();if(!e)return null;let t=A(e,`${r}.md`);if(!se(t))return null;try{return Ze(t,"utf-8")}catch{return null}}function Iu(r){let e=r.nodes.map(o=>{let a=o.inputFields?.length?`Input fields: ${o.inputFields.join(", ")}`:"Input: receives full state",c=o.outputFields?.length?`Output fields: ${o.outputFields.join(", ")}`:"Output: determined by task",d=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${a}. ${c}.${d?` ${d}`:""}`}).join(`
904
+ - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,zi=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function Wi(r){return`${r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function We(r){return`${r.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}Node`}function bu(r){let e=r?.agent;return e?e.provider?e.provider:e.gemini?"gemini":e.codex?"codex":e.claude?"claude":e.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function ku(r){let e=pr(r,".zibby.config.mjs");if(!se(e))return{};try{return(await import(e)).default||{}}catch{return{}}}function wu(){try{let r=Hi(yu.resolve("@zibby/core/package.json")),e=A(r,"templates","browser-test-automation"),t=Ye(A(e,"nodes","preflight.mjs"),"utf-8"),n=Ye(A(e,"graph.mjs"),"utf-8");return{preflight:t,graph:n}}catch{return null}}var Mi=Hi(hu(import.meta.url));function Yi(){let r=pr(Mi,"..","..","..","docsite","docs");if(se(r))return r;let e=pr(Mi,"..","docs");return se(e)?e:null}function Fi(){let r=Yi();if(!r)return[];try{let e=(t,n="")=>{let i=[];for(let s of ur(t)){let o=A(t,s);try{if(Gi(o).isDirectory())i=i.concat(e(o,`${n}${s}/`));else if(s.endsWith(".md")){let a=`${n}${s.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return e(r)}catch{return[]}}function Zi(r){let e=Yi();if(!e)return null;let t=A(e,`${r}.md`);if(!se(t))return null;try{return Ye(t,"utf-8")}catch{return null}}function Su(r){let e=r.nodes.map(o=>{let a=o.inputFields?.length?`Input fields: ${o.inputFields.join(", ")}`:"Input: receives full state",c=o.outputFields?.length?`Output fields: ${o.outputFields.join(", ")}`:"Output: determined by task",d=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${a}. ${c}.${d?` ${d}`:""}`}).join(`
905
905
  `),t=r.edges.map(o=>o.condition?`- ${o.from} \u2192 ${o.to} (conditional: ${o.condition})`:`- ${o.from} \u2192 ${o.to}`).join(`
906
- `),n=Su(),i=Zi("custom-workflows"),s="";return n&&(s+=`
906
+ `),n=wu(),i=Zi("custom-workflows"),s="";return n&&(s+=`
907
907
  ## Real working examples from the Zibby framework
908
908
 
909
909
  ### Example node (preflight.mjs) \u2014 a prompt-only node with Zod schema and onComplete hook:
@@ -980,7 +980,7 @@ Return a JSON object with this exact structure:
980
980
  }
981
981
  }
982
982
 
983
- IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function Vi(r,e){let t=await wu(e),n=ku(t);try{let{invokeAgent:i}=await import("@zibby/core"),s=Iu(r),o=await i(s,{state:{agentType:n,config:t,cwd:e,workspace:e}},{model:t?.agent?.[n]?.model||"auto",workspace:e,config:t,timeout:12e4}),c=(typeof o=="string"?o:o?.raw||JSON.stringify(o?.structured||o)).match(/\{[\s\S]*\}/);if(!c)throw new Error("Agent did not return valid JSON");return JSON.parse(c[0])}catch(i){return console.warn(`Agent code generation failed (${i.message}), using templates`),vu(r)}}function vu(r){let e={};for(let t of r.nodes){let n=Ye(t.name),i=`${t.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,s=t.outputFields?.length?t.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
983
+ IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function Vi(r,e){let t=await ku(e),n=bu(t);try{let{invokeAgent:i}=await import("@zibby/core"),s=Su(r),o=await i(s,{state:{agentType:n,config:t,cwd:e,workspace:e}},{model:t?.agent?.[n]?.model||"auto",workspace:e,config:t,timeout:12e4}),c=(typeof o=="string"?o:o?.raw||JSON.stringify(o?.structured||o)).match(/\{[\s\S]*\}/);if(!c)throw new Error("Agent did not return valid JSON");return JSON.parse(c[0])}catch(i){return console.warn(`Agent code generation failed (${i.message}), using templates`),Iu(r)}}function Iu(r){let e={};for(let t of r.nodes){let n=We(t.name),i=`${t.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,s=t.outputFields?.length?t.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
984
984
  `):` summary: z.string().describe('Summary of the result'),
985
985
  status: z.enum(['ok', 'warn', 'error']).describe('Overall status'),`,o=r.edges.filter(c=>c.to===t.name&&c.from!=="START").map(c=>`Previous step (${c.from}): \${JSON.stringify(state.${c.from} || {}, null, 2)}`).join(`
986
986
  `),a=o?`${t.description}
@@ -1002,9 +1002,9 @@ export const ${n} = {
1002
1002
  prompt: (state) => \`${a}\`,
1003
1003
  outputSchema: ${i},
1004
1004
  };
1005
- `}}return{nodes:e}}function Nu(r,e,t,n){let i=e.toLowerCase(),s=Wi(i),o=A(r,".zibby","workflows",i),a=A(o,"nodes");hu(a,{recursive:!0});let c=t.nodes.map(_=>_.name);for(let _ of t.nodes){let b=n.nodes?.[_.name]?.code;b&&Pe(A(a,`${_.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let d=c.map(_=>{let b=Ye(_),g=_.replace(/_/g,"-");return`export { ${b} } from './${g}.mjs';`});Pe(A(a,"index.mjs"),`${d.join(`
1005
+ `}}return{nodes:e}}function vu(r,e,t,n){let i=e.toLowerCase(),s=Wi(i),o=A(r,".zibby","workflows",i),a=A(o,"nodes");fu(a,{recursive:!0});let c=t.nodes.map(_=>_.name);for(let _ of t.nodes){let b=n.nodes?.[_.name]?.code;b&&Pe(A(a,`${_.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let d=c.map(_=>{let b=We(_),g=_.replace(/_/g,"-");return`export { ${b} } from './${g}.mjs';`});Pe(A(a,"index.mjs"),`${d.join(`
1006
1006
  `)}
1007
- `,"utf-8");let l=c[0],u=c.map(_=>Ye(_)).join(", "),p=c.map(_=>` graph.addNode('${_}', ${Ye(_)});`).join(`
1007
+ `,"utf-8");let l=c[0],u=c.map(_=>We(_)).join(", "),p=c.map(_=>` graph.addNode('${_}', ${We(_)});`).join(`
1008
1008
  `),m=t.edges.map(_=>_.condition?` graph.addConditionalEdges('${_.from}', (state) => {
1009
1009
  ${_.condition}
1010
1010
  });`:` graph.addEdge('${_.from}', '${_.to}');`).join(`
@@ -1028,17 +1028,17 @@ ${m}
1028
1028
  }
1029
1029
  }
1030
1030
  `;Pe(A(o,"graph.mjs"),f,"utf-8");let h={name:i,description:t.description||`${s} workflow`,entryClass:s,triggers:{api:!0}};Pe(A(o,"workflow.json"),`${JSON.stringify(h,null,2)}
1031
- `,"utf-8");let y=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(_=>`nodes/${_.replace(/_/g,"-")}.mjs`)];return{workflowDir:Ki(r,o),files:y,className:s,slug:i}}async function Ou(r){let{name:e,description:t,nodes:n,edges:i}=r;if(!e||!zi.test(e.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${e}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!n||n.length===0)return JSON.stringify({error:"At least one node is required."});let s={name:e.toLowerCase(),description:t||`${Wi(e.toLowerCase())} workflow`,nodes:n.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:i||[]};if(s.edges.length===0&&s.nodes.length>0){for(let o=0;o<s.nodes.length-1;o++)s.edges.push({from:s.nodes[o].name,to:s.nodes[o+1].name});s.edges.push({from:s.nodes[s.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:s,message:`Workflow "${s.name}" designed with ${s.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:s.nodes.map(o=>o.name),flow:s.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function Ru(r,e){let{name:t,spec:n}=r,i=(t||n?.name||"").toLowerCase();if(!i||!zi.test(i))return JSON.stringify({error:`Invalid workflow name "${i}".`});if(!n||!n.nodes||n.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let s=A(e,".zibby","workflows",i);if(se(s))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await Vi(n,e),a=Nu(e,i,n,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${i}" created at ${a.workflowDir}/`,nextSteps:[`Test locally: zibby start ${i}`,`Deploy to cloud: zibby deploy ${i} --project <project-id>`,`Tail logs: zibby logs --workflow ${i} --project <project-id>`]})}async function Tu(r,e){let{workflowName:t,nodeName:n,description:i,inputFields:s,outputFields:o}=r,a=(t||"").toLowerCase(),c=(n||"").replace(/-/g,"_"),d=A(e,".zibby","workflows",a);if(!se(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:i||`Process ${c}`,inputFields:s||[],outputFields:o||[]}],edges:[]},p=(await Vi(l,e)).nodes?.[c]?.code;if(!p)return JSON.stringify({error:"Failed to generate node code."});let m=A(d,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;Pe(A(m,f),p,"utf-8");let h=A(m,"index.mjs"),y=Ye(c),_=`export { ${y} } from './${c.replace(/_/g,"-")}.mjs';
1032
- `,b=se(h)?Ze(h,"utf-8"):"";return b.includes(y)||Pe(h,b+_,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:y,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Au(r,e){let{name:t,projectId:n}=r,i=(t||"").toLowerCase();if(!i)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let s=A(e,".zibby","workflows",i);if(!se(s))return JSON.stringify({error:`Workflow "${i}" not found at .zibby/workflows/${i}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${A(e,"packages/cli/bin/zibby.js")}" deploy ${i} --project ${n}`,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:a.trim()})}catch{try{let{execSync:a}=await import("child_process"),c=a(`npx zibby deploy ${i} --project ${n}`,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:c.trim()})}catch(a){return JSON.stringify({error:`Deploy failed: ${a.message}`})}}}function xu(r){let e=A(r,".zibby","workflows");if(!se(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=ur(e).filter(i=>{try{return Gi(A(e,i)).isDirectory()}catch{return!1}}).map(i=>{let s=A(e,i,"workflow.json"),o={};try{o=JSON.parse(Ze(s,"utf-8"))}catch{}let a=A(e,i,"nodes"),c=0;try{c=ur(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:c,path:Ki(r,A(e,i))}});return JSON.stringify({workflows:n})}var Qi={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:bu,tools:[{name:"design_workflow",description:"Design a workflow spec (nodes, edges, descriptions) for the user to review before building. Call this after understanding requirements.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name in kebab-case (e.g., ticket-triage)"},description:{type:"string",description:"What the workflow does"},nodes:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Node name in snake_case (e.g., classify_ticket)"},description:{type:"string",description:"What this node does \u2014 be specific about input/output"},inputFields:{type:"array",items:{type:"string"},description:"Key fields this node reads from state"},outputFields:{type:"array",items:{type:"string"},description:"Key fields this node produces"}},required:["name","description"]},description:"Workflow nodes (processing steps)"},edges:{type:"array",items:{type:"object",properties:{from:{type:"string",description:"Source node name"},to:{type:"string",description:'Target node name (or "END")'},condition:{type:"string",description:"JS expression for conditional routing (optional)"}},required:["from","to"]},description:"Edges connecting nodes. If omitted, nodes are wired linearly."}},required:["name","description","nodes"]}},{name:"build_workflow",description:"Generate real workflow code on disk from a design spec. Uses the configured AI agent for high-quality code generation.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name (from design_workflow)"},spec:{type:"object",description:"The full spec object returned by design_workflow",properties:{name:{type:"string"},description:{type:"string"},nodes:{type:"array",items:{type:"object"}},edges:{type:"array",items:{type:"object"}}}}},required:["name","spec"]}},{name:"add_node",description:"Add a new node to an existing workflow. Generates the node file and updates the barrel export.",input_schema:{type:"object",properties:{workflowName:{type:"string",description:"Existing workflow name (kebab-case)"},nodeName:{type:"string",description:"New node name (snake_case)"},description:{type:"string",description:"What this node does"},inputFields:{type:"array",items:{type:"string"},description:"Fields read from state"},outputFields:{type:"array",items:{type:"string"},description:"Fields produced"}},required:["workflowName","nodeName","description"]}},{name:"deploy_workflow",description:"Deploy a workflow to Zibby Cloud. Returns the trigger URL.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name to deploy"},projectId:{type:"string",description:"Target project ID"}},required:["name","projectId"]}},{name:"list_workflows",description:"List all local workflows in .zibby/workflows/.",input_schema:{type:"object",properties:{}}},{name:"explore_framework_docs",description:"Read Zibby framework documentation on demand. Call this before building complex workflows or when you need details on advanced patterns (middleware, conditional routing, skills, deployment, CLI commands).",input_schema:{type:"object",properties:{topic:{type:"string",description:'Doc topic to read (e.g., "workflow", "custom-workflows", "cli-reference", "packages/core", "packages/skills", "integrations/jira"). Call with no topic to list all available docs.'}}}}],async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Ou(e);case"build_workflow":return await Ru(e,n);case"add_node":return await Tu(e,n);case"deploy_workflow":return await Au(e,n);case"list_workflows":return xu(n);case"explore_framework_docs":{let i=(e.topic||"").trim();if(!i){let o=Fi();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=Zi(i);if(!s){let o=Fi();return JSON.stringify({error:`Doc "${i}" not found.`,available:o})}return JSON.stringify({topic:i,content:s})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};import{resolveIntegrationToken as Eu}from"@zibby/core/backend-client.js";var fr=Object.freeze({id:"openai_billing",requiresIntegration:N.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),hr=Object.freeze({id:"anthropic_billing",requiresIntegration:N.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),gr=Object.freeze({id:"cursor_admin",requiresIntegration:N.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Xi(r){return Math.floor(r/1e3)}function mr(r){return new Date(r).toISOString().slice(0,10)}function es(r){return new Date(r).toISOString()}async function Ve(r){let e=await Eu(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function ts({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let n=await Ve("openai_billing"),i=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.openai.com/v1/organization/costs?${[`start_time=${Xi(r)}`,`end_time=${Xi(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{Authorization:`Bearer ${n}`}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`OpenAI costs API ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){s+=1;let f=mr((m.start_time||0)*1e3);for(let h of m.results||[])i.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:i,rawBuckets:s}}async function $u(){let r=await Ve("openai_billing"),t=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function rs({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let n=await Ve("anthropic_billing"),i=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(es(r))}`,`ending_at=${encodeURIComponent(es(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Anthropic cost_report ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){s+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])i.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Lu(){let r=await Ve("anthropic_billing"),t=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function ns({startMs:r,endMs:e}){let t=await Ve("cursor_admin"),n=mr(r),i=mr(e),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${i}`,o=await fetch(s,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${l.slice(0,200)}`)}let a=await o.json(),c=[],d=0;for(let l of a.data||[]){d+=1;let u=l.date;for(let p of l.userMetrics||[]){for(let m of p.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:u,costUsd:Number(m.totalCents??0)/100,userEmail:p.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!p.modelUsage||p.modelUsage.length===0)&&c.push({provider:"cursor",day:u,costUsd:Number(p.totalCents??0)/100,userEmail:p.email})}}return{ok:!0,items:c,rawBuckets:d}}async function ju({startMs:r,endMs:e}){let[t,n,i]=await Promise.allSettled([ts({startMs:r,endMs:e}),rs({startMs:r,endMs:e}),ns({startMs:r,endMs:e})]),s=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=s(t),a=s(n),c=s(i),d=[{provider:"openai",totalUsd:o.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,u)=>l+(u.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function Pu(r,e){let t=new Map;for(let n of r){let i=e(n);if(!i)continue;let s=t.get(i)||{key:i,totalUsd:0,count:0};s.totalUsd+=n.costUsd||0,s.count+=1,t.set(i,s)}return[...t.values()].sort((n,i)=>i.totalUsd-n.totalUsd)}function Cu(r){if(!r.length)return{mean:0,stddev:0};let e=r.reduce((n,i)=>n+i,0)/r.length,t=r.reduce((n,i)=>n+(i-e)**2,0)/r.length;return{mean:e,stddev:Math.sqrt(t)}}import{SKILL_IDS as og}from"@zibby/skill-ids";import{z as k}from"zod";var Qe=["ok","info","warn","critical"],Uu=k.object({primary:k.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:k.object({value:k.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:k.enum(["up","down","flat"]).optional(),severity:k.enum(Qe).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:k.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),Du=k.object({kind:k.literal("trend"),title:k.string().max(120).optional(),labels:k.array(k.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:k.array(k.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:k.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:k.enum(Qe).optional()}),qu=k.object({kind:k.literal("table"),title:k.string().max(120).optional(),headers:k.array(k.string().max(40)).min(1).max(8),rows:k.array(k.array(k.union([k.string().max(200),k.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),Ju=k.object({kind:k.literal("callouts"),title:k.string().max(120).optional(),tone:k.enum(Qe).default("info").optional(),items:k.array(k.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),Bu=k.object({kind:k.literal("breakdown"),title:k.string().max(120).optional(),rows:k.array(k.object({label:k.string().min(1).max(80),value:k.string().min(1).max(80),sub:k.string().max(120).optional(),severity:k.enum(Qe).optional()})).min(1).max(20)}),Mu=k.object({kind:k.literal("paragraph"),title:k.string().max(120).optional(),text:k.string().min(1).max(3e3)}),Fu=k.discriminatedUnion("kind",[Du,qu,Ju,Bu,Mu]),Xe=k.object({title:k.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:k.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:Uu,sections:k.array(Fu).max(20).default([]).superRefine((r,e)=>{r.forEach((t,n)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:k.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(i=>i.length===t.headers.length)&&e.addIssue({code:k.ZodIssueCode.custom,path:[n,"rows"],message:"every row must have headers.length entries"})})}),footer:k.object({viewUrl:k.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:k.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),C=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),Ot=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),Gu=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Rt(r,e,t=12){if(!Number.isFinite(r)||!Number.isFinite(e)||e<=0)return"";let n=Math.max(0,Math.min(1,r/e)),i=Math.round(n*t);return"\u2593".repeat(i)+"\u2591".repeat(t-i)}function et(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function Tt(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function os({headers:r,rows:e}){let t=r.map((o,a)=>{let c=Math.max(String(o).length,...e.map(d=>String(d[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>et(a,t[c])).join(" "),i=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),i,...e.map(o=>n(o))].join(`
1033
- `)+"\n```"}function Ku(r){let e=Xe.parse(r),t=[];t.push({type:"header",text:{type:"plain_text",text:e.title.slice(0,150),emoji:!0}}),e.subtitle&&t.push({type:"context",elements:[{type:"mrkdwn",text:e.subtitle}]});let n=[`*${e.headline.primary}*`];if(e.headline.delta){let s=Ot[e.headline.delta.direction]||"",o=e.headline.delta.severity?C[e.headline.delta.severity]:"";n.push(`${s} ${e.headline.delta.value} ${o}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1034
- `+e.headline.summary),t.push({type:"section",text:{type:"mrkdwn",text:i}});for(let s of e.sections)switch(t.push({type:"divider"}),s.title&&t.push({type:"section",text:{type:"mrkdwn",text:`*${s.title}*`}}),s.kind){case"trend":{let o=Math.max(...s.values),a=s.labels.map((c,d)=>{let l=s.values[d],u=Rt(l,o),m=(s.highlight==="last"&&d===s.labels.length-1||s.highlight==="max"&&l===o||s.highlight==="min"&&l===Math.min(...s.values))&&s.severity?` ${C[s.severity]}`:"";return`${et(c,10)} ${Tt(l.toLocaleString(),8)} ${u}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1031
+ `,"utf-8");let y=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(_=>`nodes/${_.replace(/_/g,"-")}.mjs`)];return{workflowDir:Ki(r,o),files:y,className:s,slug:i}}async function Nu(r){let{name:e,description:t,nodes:n,edges:i}=r;if(!e||!zi.test(e.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${e}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!n||n.length===0)return JSON.stringify({error:"At least one node is required."});let s={name:e.toLowerCase(),description:t||`${Wi(e.toLowerCase())} workflow`,nodes:n.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:i||[]};if(s.edges.length===0&&s.nodes.length>0){for(let o=0;o<s.nodes.length-1;o++)s.edges.push({from:s.nodes[o].name,to:s.nodes[o+1].name});s.edges.push({from:s.nodes[s.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:s,message:`Workflow "${s.name}" designed with ${s.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:s.nodes.map(o=>o.name),flow:s.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function Ou(r,e){let{name:t,spec:n}=r,i=(t||n?.name||"").toLowerCase();if(!i||!zi.test(i))return JSON.stringify({error:`Invalid workflow name "${i}".`});if(!n||!n.nodes||n.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let s=A(e,".zibby","workflows",i);if(se(s))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await Vi(n,e),a=vu(e,i,n,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${i}" created at ${a.workflowDir}/`,nextSteps:[`Test locally: zibby start ${i}`,`Deploy to cloud: zibby deploy ${i} --project <project-id>`,`Tail logs: zibby logs --workflow ${i} --project <project-id>`]})}async function Ru(r,e){let{workflowName:t,nodeName:n,description:i,inputFields:s,outputFields:o}=r,a=(t||"").toLowerCase(),c=(n||"").replace(/-/g,"_"),d=A(e,".zibby","workflows",a);if(!se(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:i||`Process ${c}`,inputFields:s||[],outputFields:o||[]}],edges:[]},p=(await Vi(l,e)).nodes?.[c]?.code;if(!p)return JSON.stringify({error:"Failed to generate node code."});let m=A(d,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;Pe(A(m,f),p,"utf-8");let h=A(m,"index.mjs"),y=We(c),_=`export { ${y} } from './${c.replace(/_/g,"-")}.mjs';
1032
+ `,b=se(h)?Ye(h,"utf-8"):"";return b.includes(y)||Pe(h,b+_,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:y,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Tu(r,e){let{name:t,projectId:n}=r,i=(t||"").toLowerCase();if(!i)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let s=A(e,".zibby","workflows",i);if(!se(s))return JSON.stringify({error:`Workflow "${i}" not found at .zibby/workflows/${i}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${A(e,"packages/cli/bin/zibby.js")}" deploy ${i} --project ${n}`,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:a.trim()})}catch{try{let{execSync:a}=await import("child_process"),c=a(`npx zibby deploy ${i} --project ${n}`,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:c.trim()})}catch(a){return JSON.stringify({error:`Deploy failed: ${a.message}`})}}}function Au(r){let e=A(r,".zibby","workflows");if(!se(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=ur(e).filter(i=>{try{return Gi(A(e,i)).isDirectory()}catch{return!1}}).map(i=>{let s=A(e,i,"workflow.json"),o={};try{o=JSON.parse(Ye(s,"utf-8"))}catch{}let a=A(e,i,"nodes"),c=0;try{c=ur(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:c,path:Ki(r,A(e,i))}});return JSON.stringify({workflows:n})}var Qi={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:_u,tools:[{name:"design_workflow",description:"Design a workflow spec (nodes, edges, descriptions) for the user to review before building. Call this after understanding requirements.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name in kebab-case (e.g., ticket-triage)"},description:{type:"string",description:"What the workflow does"},nodes:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Node name in snake_case (e.g., classify_ticket)"},description:{type:"string",description:"What this node does \u2014 be specific about input/output"},inputFields:{type:"array",items:{type:"string"},description:"Key fields this node reads from state"},outputFields:{type:"array",items:{type:"string"},description:"Key fields this node produces"}},required:["name","description"]},description:"Workflow nodes (processing steps)"},edges:{type:"array",items:{type:"object",properties:{from:{type:"string",description:"Source node name"},to:{type:"string",description:'Target node name (or "END")'},condition:{type:"string",description:"JS expression for conditional routing (optional)"}},required:["from","to"]},description:"Edges connecting nodes. If omitted, nodes are wired linearly."}},required:["name","description","nodes"]}},{name:"build_workflow",description:"Generate real workflow code on disk from a design spec. Uses the configured AI agent for high-quality code generation.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name (from design_workflow)"},spec:{type:"object",description:"The full spec object returned by design_workflow",properties:{name:{type:"string"},description:{type:"string"},nodes:{type:"array",items:{type:"object"}},edges:{type:"array",items:{type:"object"}}}}},required:["name","spec"]}},{name:"add_node",description:"Add a new node to an existing workflow. Generates the node file and updates the barrel export.",input_schema:{type:"object",properties:{workflowName:{type:"string",description:"Existing workflow name (kebab-case)"},nodeName:{type:"string",description:"New node name (snake_case)"},description:{type:"string",description:"What this node does"},inputFields:{type:"array",items:{type:"string"},description:"Fields read from state"},outputFields:{type:"array",items:{type:"string"},description:"Fields produced"}},required:["workflowName","nodeName","description"]}},{name:"deploy_workflow",description:"Deploy a workflow to Zibby Cloud. Returns the trigger URL.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name to deploy"},projectId:{type:"string",description:"Target project ID"}},required:["name","projectId"]}},{name:"list_workflows",description:"List all local workflows in .zibby/workflows/.",input_schema:{type:"object",properties:{}}},{name:"explore_framework_docs",description:"Read Zibby framework documentation on demand. Call this before building complex workflows or when you need details on advanced patterns (middleware, conditional routing, skills, deployment, CLI commands).",input_schema:{type:"object",properties:{topic:{type:"string",description:'Doc topic to read (e.g., "workflow", "custom-workflows", "cli-reference", "packages/core", "packages/skills", "integrations/jira"). Call with no topic to list all available docs.'}}}}],async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Nu(e);case"build_workflow":return await Ou(e,n);case"add_node":return await Ru(e,n);case"deploy_workflow":return await Tu(e,n);case"list_workflows":return Au(n);case"explore_framework_docs":{let i=(e.topic||"").trim();if(!i){let o=Fi();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=Zi(i);if(!s){let o=Fi();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 xu}from"@zibby/core/backend-client.js";var fr=Object.freeze({id:"openai_billing",requiresIntegration:N.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),hr=Object.freeze({id:"anthropic_billing",requiresIntegration:N.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),gr=Object.freeze({id:"cursor_admin",requiresIntegration:N.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Xi(r){return Math.floor(r/1e3)}function mr(r){return new Date(r).toISOString().slice(0,10)}function es(r){return new Date(r).toISOString()}async function Ze(r){let e=await xu(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function ts({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let n=await Ze("openai_billing"),i=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.openai.com/v1/organization/costs?${[`start_time=${Xi(r)}`,`end_time=${Xi(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{Authorization:`Bearer ${n}`}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`OpenAI costs API ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){s+=1;let f=mr((m.start_time||0)*1e3);for(let h of m.results||[])i.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Eu(){let r=await Ze("openai_billing"),t=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function rs({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let n=await Ze("anthropic_billing"),i=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(es(r))}`,`ending_at=${encodeURIComponent(es(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,u=await fetch(l,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Anthropic cost_report ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();for(let m of p.data||[]){s+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])i.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!p.has_more||!p.next_page)break;a=p.next_page}return{ok:!0,items:i,rawBuckets:s}}async function $u(){let r=await Ze("anthropic_billing"),t=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function ns({startMs:r,endMs:e}){let t=await Ze("cursor_admin"),n=mr(r),i=mr(e),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${i}`,o=await fetch(s,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${l.slice(0,200)}`)}let a=await o.json(),c=[],d=0;for(let l of a.data||[]){d+=1;let u=l.date;for(let p of l.userMetrics||[]){for(let m of p.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:u,costUsd:Number(m.totalCents??0)/100,userEmail:p.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!p.modelUsage||p.modelUsage.length===0)&&c.push({provider:"cursor",day:u,costUsd:Number(p.totalCents??0)/100,userEmail:p.email})}}return{ok:!0,items:c,rawBuckets:d}}async function Lu({startMs:r,endMs:e}){let[t,n,i]=await Promise.allSettled([ts({startMs:r,endMs:e}),rs({startMs:r,endMs:e}),ns({startMs:r,endMs:e})]),s=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=s(t),a=s(n),c=s(i),d=[{provider:"openai",totalUsd:o.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,u)=>l+(u.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,u)=>l+(u.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function ju(r,e){let t=new Map;for(let n of r){let i=e(n);if(!i)continue;let s=t.get(i)||{key:i,totalUsd:0,count:0};s.totalUsd+=n.costUsd||0,s.count+=1,t.set(i,s)}return[...t.values()].sort((n,i)=>i.totalUsd-n.totalUsd)}function Pu(r){if(!r.length)return{mean:0,stddev:0};let e=r.reduce((n,i)=>n+i,0)/r.length,t=r.reduce((n,i)=>n+(i-e)**2,0)/r.length;return{mean:e,stddev:Math.sqrt(t)}}import{SKILL_IDS as sg}from"@zibby/skill-ids";import{z as k}from"zod";var Ve=["ok","info","warn","critical"],Cu=k.object({primary:k.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:k.object({value:k.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:k.enum(["up","down","flat"]).optional(),severity:k.enum(Ve).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:k.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),Uu=k.object({kind:k.literal("trend"),title:k.string().max(120).optional(),labels:k.array(k.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:k.array(k.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:k.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:k.enum(Ve).optional()}),Du=k.object({kind:k.literal("table"),title:k.string().max(120).optional(),headers:k.array(k.string().max(40)).min(1).max(8),rows:k.array(k.array(k.union([k.string().max(200),k.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),qu=k.object({kind:k.literal("callouts"),title:k.string().max(120).optional(),tone:k.enum(Ve).default("info").optional(),items:k.array(k.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),Ju=k.object({kind:k.literal("breakdown"),title:k.string().max(120).optional(),rows:k.array(k.object({label:k.string().min(1).max(80),value:k.string().min(1).max(80),sub:k.string().max(120).optional(),severity:k.enum(Ve).optional()})).min(1).max(20)}),Bu=k.object({kind:k.literal("paragraph"),title:k.string().max(120).optional(),text:k.string().min(1).max(3e3)}),Mu=k.discriminatedUnion("kind",[Uu,Du,qu,Ju,Bu]),Qe=k.object({title:k.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:k.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:Cu,sections:k.array(Mu).max(20).default([]).superRefine((r,e)=>{r.forEach((t,n)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:k.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(i=>i.length===t.headers.length)&&e.addIssue({code:k.ZodIssueCode.custom,path:[n,"rows"],message:"every row must have headers.length entries"})})}),footer:k.object({viewUrl:k.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:k.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),C=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),Nt=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),Fu=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Ot(r,e,t=12){if(!Number.isFinite(r)||!Number.isFinite(e)||e<=0)return"";let n=Math.max(0,Math.min(1,r/e)),i=Math.round(n*t);return"\u2593".repeat(i)+"\u2591".repeat(t-i)}function Xe(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function Rt(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function os({headers:r,rows:e}){let t=r.map((o,a)=>{let c=Math.max(String(o).length,...e.map(d=>String(d[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>Xe(a,t[c])).join(" "),i=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),i,...e.map(o=>n(o))].join(`
1033
+ `)+"\n```"}function Gu(r){let e=Qe.parse(r),t=[];t.push({type:"header",text:{type:"plain_text",text:e.title.slice(0,150),emoji:!0}}),e.subtitle&&t.push({type:"context",elements:[{type:"mrkdwn",text:e.subtitle}]});let n=[`*${e.headline.primary}*`];if(e.headline.delta){let s=Nt[e.headline.delta.direction]||"",o=e.headline.delta.severity?C[e.headline.delta.severity]:"";n.push(`${s} ${e.headline.delta.value} ${o}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1034
+ `+e.headline.summary),t.push({type:"section",text:{type:"mrkdwn",text:i}});for(let s of e.sections)switch(t.push({type:"divider"}),s.title&&t.push({type:"section",text:{type:"mrkdwn",text:`*${s.title}*`}}),s.kind){case"trend":{let o=Math.max(...s.values),a=s.labels.map((c,d)=>{let l=s.values[d],u=Ot(l,o),m=(s.highlight==="last"&&d===s.labels.length-1||s.highlight==="max"&&l===o||s.highlight==="min"&&l===Math.min(...s.values))&&s.severity?` ${C[s.severity]}`:"";return`${Xe(c,10)} ${Rt(l.toLocaleString(),8)} ${u}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1035
1035
  `)+"\n```"}});break}case"table":{t.push({type:"section",text:{type:"mrkdwn",text:os(s)}});break}case"callouts":{let o=C[s.tone||"info"];t.push({type:"section",text:{type:"mrkdwn",text:s.items.map(a=>`${o} ${a}`).join(`
1036
1036
  `)}});break}case"breakdown":{let o=s.rows.map(a=>({type:"mrkdwn",text:`*${a.label}*
1037
1037
  ${a.value}${a.sub?`
1038
- _${a.sub}_`:""}${a.severity?` ${C[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)t.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{t.push({type:"section",text:{type:"mrkdwn",text:s.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let s=[];e.footer.viewUrl&&s.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:e.footer.viewUrl,style:"primary"}),e.footer.rerunUrl&&s.push({type:"button",text:{type:"plain_text",text:"Run again"},url:e.footer.rerunUrl}),t.push({type:"divider"}),t.push({type:"actions",elements:s})}return t}function Hu(r){let e=Xe.parse(r),t=[],n=[`**${e.headline.primary}**`];if(e.headline.delta){let o=Ot[e.headline.delta.direction]||"",a=e.headline.delta.severity?C[e.headline.delta.severity]:"";n.push(`${o} ${e.headline.delta.value} ${a}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1039
- `+e.headline.summary),t.push({tag:"div",text:{tag:"lark_md",content:i}});for(let o of e.sections)switch(t.push({tag:"hr"}),o.title&&t.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let a=Math.max(...o.values),c=o.labels.map((d,l)=>{let u=o.values[l],p=Rt(u,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&u===a||o.highlight==="min"&&u===Math.min(...o.values))&&o.severity?` ${C[o.severity]}`:"";return`${et(d,10)} ${Tt(u.toLocaleString(),8)} ${p}${f}`});t.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1038
+ _${a.sub}_`:""}${a.severity?` ${C[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)t.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{t.push({type:"section",text:{type:"mrkdwn",text:s.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let s=[];e.footer.viewUrl&&s.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:e.footer.viewUrl,style:"primary"}),e.footer.rerunUrl&&s.push({type:"button",text:{type:"plain_text",text:"Run again"},url:e.footer.rerunUrl}),t.push({type:"divider"}),t.push({type:"actions",elements:s})}return t}function Ku(r){let e=Qe.parse(r),t=[],n=[`**${e.headline.primary}**`];if(e.headline.delta){let o=Nt[e.headline.delta.direction]||"",a=e.headline.delta.severity?C[e.headline.delta.severity]:"";n.push(`${o} ${e.headline.delta.value} ${a}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1039
+ `+e.headline.summary),t.push({tag:"div",text:{tag:"lark_md",content:i}});for(let o of e.sections)switch(t.push({tag:"hr"}),o.title&&t.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let a=Math.max(...o.values),c=o.labels.map((d,l)=>{let u=o.values[l],p=Ot(u,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&u===a||o.highlight==="min"&&u===Math.min(...o.values))&&o.severity?` ${C[o.severity]}`:"";return`${Xe(d,10)} ${Rt(u.toLocaleString(),8)} ${p}${f}`});t.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1040
1040
  `)+"\n```"}});break}case"table":{t.push({tag:"div",text:{tag:"lark_md",content:os(o)}});break}case"callouts":{let a=C[o.tone||"info"];t.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
1041
1041
  `)}});break}case"breakdown":{let a=o.rows.map(c=>{let d=c.severity?` ${C[c.severity]}`:"",l=c.sub?` *${c.sub}*`:"";return`**${c.label}** ${c.value}${l}${d}`});t.push({tag:"div",text:{tag:"lark_md",content:a.join(`
1042
- `)}});break}case"paragraph":{t.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let o=[];e.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:e.footer.viewUrl,type:"primary"}),e.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:e.footer.rerunUrl,type:"default"}),t.push({tag:"hr"}),t.push({tag:"action",actions:o})}let s="blue";return e.headline.delta?.severity&&(s=Gu[e.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:e.title.slice(0,200)},subtitle:e.subtitle?{tag:"plain_text",content:e.subtitle.slice(0,200)}:void 0,template:s},elements:t}}var zu=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),is=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function Se(r,e={}){let t={type:"text",text:{content:String(r).slice(0,2e3)}};return e.annotations&&(t.annotations=e.annotations),[t]}function yr(r,e){let t={object:"block",type:"paragraph",paragraph:{rich_text:Se(r)}};return e&&(t.paragraph.color=e),t}function Wu(r){return{object:"block",type:"code",code:{rich_text:Se(r),language:"plain text"}}}function Yu(r){let e=Xe.parse(r),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:Se(e.title.slice(0,200))}}),e.subtitle&&t.push(yr(e.subtitle,"gray_background"));let n=[{type:"text",text:{content:e.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(e.headline.delta){let s=Ot[e.headline.delta.direction]||"",o=e.headline.delta.severity?C[e.headline.delta.severity]:"",a=` ${s} ${e.headline.delta.value} ${o}`.trimEnd();n.push({type:"text",text:{content:a}})}t.push({object:"block",type:"paragraph",paragraph:{rich_text:n}}),e.headline.summary&&t.push(yr(e.headline.summary));for(let s of e.sections)switch(t.push({object:"block",type:"divider",divider:{}}),s.title&&t.push({object:"block",type:"heading_2",heading_2:{rich_text:Se(s.title)}}),s.kind){case"trend":{let o=Math.max(...s.values),a=Math.min(...s.values),c=s.labels.map((d,l)=>{let u=s.values[l],p=Rt(u,o),f=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&u===o||s.highlight==="min"&&u===a)&&s.severity?` ${C[s.severity]}`:"";return`${et(d,10)} ${Tt(u.toLocaleString(),8)} ${p}${f}`});t.push(Wu(c.join(`
1043
- `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>Se(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>Se(String(d)))}}));t.push({object:"block",type:"table",table:{table_width:s.headers.length,has_column_header:!0,has_row_header:!1,children:[o,...a]}});break}case"callouts":{let o=s.tone||"info",a=is[o],c=zu[o];for(let d of s.items)t.push({object:"block",type:"callout",callout:{rich_text:Se(d),icon:{type:"emoji",emoji:a},color:c}});break}case"breakdown":{for(let o of s.rows){let a=[{type:"text",text:{content:`${o.label}: `},annotations:{bold:!0}},{type:"text",text:{content:String(o.value)}}];o.sub&&a.push({type:"text",text:{content:` (${o.sub})`},annotations:{italic:!0}}),o.severity&&a.push({type:"text",text:{content:` ${C[o.severity]}`}}),t.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{t.push(yr(s.text));break}}e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)&&(t.push({object:"block",type:"divider",divider:{}}),e.footer.viewUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.viewUrl}}),e.footer.rerunUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.rerunUrl}}));let i=e.headline.delta?.severity?is[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:i}}function ss(r){return String(r??"").replace(/\|/g,"\\|")}function Zu(r){let e=Xe.parse(r),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let n=[`**${e.headline.primary}**`];if(e.headline.delta){let i=Ot[e.headline.delta.direction]||"",s=e.headline.delta.severity?C[e.headline.delta.severity]:"";n.push(`${i} ${e.headline.delta.value} ${s}`.trim())}t.push("",n.join(" ")),e.headline.summary&&t.push("",e.headline.summary);for(let i of e.sections)switch(t.push("","---",""),i.title&&t.push(`## ${i.title}`,""),i.kind){case"trend":{let s=Math.max(...i.values),o=Math.min(...i.values),a=i.labels.map((c,d)=>{let l=i.values[d],u=Rt(l,s),m=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&l===s||i.highlight==="min"&&l===o)&&i.severity?` ${C[i.severity]}`:"";return`${et(c,10)} ${Tt(l.toLocaleString(),8)} ${u}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${i.headers.map(ss).join(" | ")} |`),t.push(`| ${i.headers.map(()=>"---").join(" | ")} |`);for(let s of i.rows)t.push(`| ${s.map(ss).join(" | ")} |`);break}case"callouts":{let s=C[i.tone||"info"];for(let o of i.items)t.push(`- ${s} ${o}`);break}case"breakdown":{for(let s of i.rows){let o=s.sub?` _${s.sub}_`:"",a=s.severity?` ${C[s.severity]}`:"";t.push(`- **${s.label}**: ${s.value}${o}${a}`)}break}case"paragraph":{t.push(i.text);break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let i=[];e.footer.viewUrl&&i.push(`[View in Zibby](${e.footer.viewUrl})`),e.footer.rerunUrl&&i.push(`[Run again](${e.footer.rerunUrl})`),t.push("","---","",i.join(" \xB7 "))}return t.join(`
1044
- `)}import{createRequire as Vu}from"module";import{fileURLToPath as Qu}from"url";import{registerHandlers as Xu}from"@zibby/core/function-skill-registry.js";import{registerSkill as ep}from"@zibby/agent-workflow";var tp=Vu(import.meta.url);function rp(){try{return tp.resolve("@zibby/core/function-bridge.js")}catch{return null}}var np=import.meta.url;function ip(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let t=new Error().stack;for(let n=2;n<t.length;n++){let i=t[n].getFileName();if(i&&i!==np&&!i.startsWith("node:"))return i.startsWith("file://")?Qu(i):i}return null}finally{Error.prepareStackTrace=r}}function sp(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let e={},t=[];for(let[n,i]of Object.entries(r))if(typeof i=="string")e[n]={type:i},t.push(n);else{let{required:s,...o}=i;e[n]=o,s!==!1&&t.push(n)}return{type:"object",properties:e,required:t}}function op(r,e,t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n={[r]:t.handler},i=[{name:r,description:t.description||"",input_schema:sp(t.input)}];return Xu(r,n,i),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:t.description||`Function skill: ${r}`,envKeys:[],tools:i,resolve(){let s=rp();return s?{command:"node",args:[s,e,r]}:null}}}function ap(r,e){return{id:r,type:"mcp",serverName:e.serverName||r,allowedTools:e.allowedTools||[`mcp__${e.serverName||r}__*`],description:e.description||`MCP skill: ${r}`,envKeys:e.envKeys||[],tools:e.tools||[],resolve:e.resolve,...e.cursorKey&&{cursorKey:e.cursorKey},...e.sessionEnvKey&&{sessionEnvKey:e.sessionEnvKey}}}function as(r,e){let t;if("handler"in e){if(typeof e.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n=ip();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);t=op(r,n,e)}else if(typeof e.resolve=="function")t=ap(r,e);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return ep(t),t}var cp=as;import{registerSkill as ug,getSkill as pg,hasSkill as mg,getAllSkills as fg,listSkillIds as hg}from"@zibby/agent-workflow";I(kr);I(Ir);I(Oe);I(Re);I(Or);I(Tr);I(Ar);I($r);I(P);I(W);I(Pr);I(Fr);I(zr);I(Qr);I(an);I(cn);I(lt);I(dn);I(jn);I(de);I(Jn);I(pn);I(yn);I(ei);I(ai);I(mi);I(Ii);I(Li);I(Ci);I(Ui);I(Bi);I(Qi);I(fr);I(hr);I(gr);I({...P,id:"slack_notify"});export{N as INTEGRATIONS,bs as INTEGRATION_REGISTRY,Qe as REPORT_SEVERITIES,og as SKILLS,hr as anthropicBillingSkill,kr as browserSkill,Ii as chartRenderSkill,ei as chatMemorySkill,cn as chatNotifySkill,Ci as codeScanSkill,Bi as codebaseMemorySkill,yn as coreToolsSkill,gr as cursorAdminSkill,mi as datasetStoreSkill,Pr as discordSkill,ju as fetchAllProviders,rs as fetchAnthropicCosts,Lu as fetchAnthropicWorkspaces,ns as fetchCursorSpend,ts as fetchOpenAICosts,$u as fetchOpenAIProjects,Or as figmaSkill,cp as functionSkill,fg as getAllSkills,pg as getSkill,de as gitSkill,Jn as gitWriteSkill,Oe as githubSkill,Re as gitlabSkill,Qr as googleDocsSkill,Pu as groupByKey,mg as hasSkill,Ir as jiraSkill,ai as kvMemorySkill,an as larkDocsSkill,W as larkSkill,Tr as linearSkill,zr as linkedinSkill,hg as listSkillIds,Cu as meanStddev,dn as memorySkill,Fr as notionSkill,fr as openaiBillingSkill,$r as opendesignSkill,Ar as planeSkill,ug as registerSkill,Xe as reportObjectSchema,Ku as reportToBlockKit,Hu as reportToLarkCard,Zu as reportToMarkdown,Yu as reportToNotionBlocks,jn as runnerSkill,lt as sentrySkill,as as skill,pn as skillInstallerSkill,P as slackSkill,Li as socialCardSkill,jn as testRunnerSkill,Qi as workflowBuilderSkill};
1042
+ `)}});break}case"paragraph":{t.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let o=[];e.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:e.footer.viewUrl,type:"primary"}),e.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:e.footer.rerunUrl,type:"default"}),t.push({tag:"hr"}),t.push({tag:"action",actions:o})}let s="blue";return e.headline.delta?.severity&&(s=Fu[e.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:e.title.slice(0,200)},subtitle:e.subtitle?{tag:"plain_text",content:e.subtitle.slice(0,200)}:void 0,template:s},elements:t}}var Hu=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),is=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function Se(r,e={}){let t={type:"text",text:{content:String(r).slice(0,2e3)}};return e.annotations&&(t.annotations=e.annotations),[t]}function yr(r,e){let t={object:"block",type:"paragraph",paragraph:{rich_text:Se(r)}};return e&&(t.paragraph.color=e),t}function zu(r){return{object:"block",type:"code",code:{rich_text:Se(r),language:"plain text"}}}function Wu(r){let e=Qe.parse(r),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:Se(e.title.slice(0,200))}}),e.subtitle&&t.push(yr(e.subtitle,"gray_background"));let n=[{type:"text",text:{content:e.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(e.headline.delta){let s=Nt[e.headline.delta.direction]||"",o=e.headline.delta.severity?C[e.headline.delta.severity]:"",a=` ${s} ${e.headline.delta.value} ${o}`.trimEnd();n.push({type:"text",text:{content:a}})}t.push({object:"block",type:"paragraph",paragraph:{rich_text:n}}),e.headline.summary&&t.push(yr(e.headline.summary));for(let s of e.sections)switch(t.push({object:"block",type:"divider",divider:{}}),s.title&&t.push({object:"block",type:"heading_2",heading_2:{rich_text:Se(s.title)}}),s.kind){case"trend":{let o=Math.max(...s.values),a=Math.min(...s.values),c=s.labels.map((d,l)=>{let u=s.values[l],p=Ot(u,o),f=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&u===o||s.highlight==="min"&&u===a)&&s.severity?` ${C[s.severity]}`:"";return`${Xe(d,10)} ${Rt(u.toLocaleString(),8)} ${p}${f}`});t.push(zu(c.join(`
1043
+ `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>Se(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>Se(String(d)))}}));t.push({object:"block",type:"table",table:{table_width:s.headers.length,has_column_header:!0,has_row_header:!1,children:[o,...a]}});break}case"callouts":{let o=s.tone||"info",a=is[o],c=Hu[o];for(let d of s.items)t.push({object:"block",type:"callout",callout:{rich_text:Se(d),icon:{type:"emoji",emoji:a},color:c}});break}case"breakdown":{for(let o of s.rows){let a=[{type:"text",text:{content:`${o.label}: `},annotations:{bold:!0}},{type:"text",text:{content:String(o.value)}}];o.sub&&a.push({type:"text",text:{content:` (${o.sub})`},annotations:{italic:!0}}),o.severity&&a.push({type:"text",text:{content:` ${C[o.severity]}`}}),t.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{t.push(yr(s.text));break}}e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)&&(t.push({object:"block",type:"divider",divider:{}}),e.footer.viewUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.viewUrl}}),e.footer.rerunUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.rerunUrl}}));let i=e.headline.delta?.severity?is[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:i}}function ss(r){return String(r??"").replace(/\|/g,"\\|")}function Yu(r){let e=Qe.parse(r),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let n=[`**${e.headline.primary}**`];if(e.headline.delta){let i=Nt[e.headline.delta.direction]||"",s=e.headline.delta.severity?C[e.headline.delta.severity]:"";n.push(`${i} ${e.headline.delta.value} ${s}`.trim())}t.push("",n.join(" ")),e.headline.summary&&t.push("",e.headline.summary);for(let i of e.sections)switch(t.push("","---",""),i.title&&t.push(`## ${i.title}`,""),i.kind){case"trend":{let s=Math.max(...i.values),o=Math.min(...i.values),a=i.labels.map((c,d)=>{let l=i.values[d],u=Ot(l,s),m=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&l===s||i.highlight==="min"&&l===o)&&i.severity?` ${C[i.severity]}`:"";return`${Xe(c,10)} ${Rt(l.toLocaleString(),8)} ${u}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${i.headers.map(ss).join(" | ")} |`),t.push(`| ${i.headers.map(()=>"---").join(" | ")} |`);for(let s of i.rows)t.push(`| ${s.map(ss).join(" | ")} |`);break}case"callouts":{let s=C[i.tone||"info"];for(let o of i.items)t.push(`- ${s} ${o}`);break}case"breakdown":{for(let s of i.rows){let o=s.sub?` _${s.sub}_`:"",a=s.severity?` ${C[s.severity]}`:"";t.push(`- **${s.label}**: ${s.value}${o}${a}`)}break}case"paragraph":{t.push(i.text);break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let i=[];e.footer.viewUrl&&i.push(`[View in Zibby](${e.footer.viewUrl})`),e.footer.rerunUrl&&i.push(`[Run again](${e.footer.rerunUrl})`),t.push("","---","",i.join(" \xB7 "))}return t.join(`
1044
+ `)}import{createRequire as Zu}from"module";import{fileURLToPath as Vu}from"url";import{registerHandlers as Qu}from"@zibby/core/function-skill-registry.js";import{registerSkill as Xu}from"@zibby/agent-workflow";var ep=Zu(import.meta.url);function tp(){try{return ep.resolve("@zibby/core/function-bridge.js")}catch{return null}}var rp=import.meta.url;function np(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let t=new Error().stack;for(let n=2;n<t.length;n++){let i=t[n].getFileName();if(i&&i!==rp&&!i.startsWith("node:"))return i.startsWith("file://")?Vu(i):i}return null}finally{Error.prepareStackTrace=r}}function ip(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let e={},t=[];for(let[n,i]of Object.entries(r))if(typeof i=="string")e[n]={type:i},t.push(n);else{let{required:s,...o}=i;e[n]=o,s!==!1&&t.push(n)}return{type:"object",properties:e,required:t}}function sp(r,e,t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n={[r]:t.handler},i=[{name:r,description:t.description||"",input_schema:ip(t.input)}];return Qu(r,n,i),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:t.description||`Function skill: ${r}`,envKeys:[],tools:i,resolve(){let s=tp();return s?{command:"node",args:[s,e,r]}:null}}}function op(r,e){return{id:r,type:"mcp",serverName:e.serverName||r,allowedTools:e.allowedTools||[`mcp__${e.serverName||r}__*`],description:e.description||`MCP skill: ${r}`,envKeys:e.envKeys||[],tools:e.tools||[],resolve:e.resolve,...e.cursorKey&&{cursorKey:e.cursorKey},...e.sessionEnvKey&&{sessionEnvKey:e.sessionEnvKey}}}function as(r,e){let t;if("handler"in e){if(typeof e.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n=np();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);t=sp(r,n,e)}else if(typeof e.resolve=="function")t=op(r,e);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return Xu(t),t}var ap=as;import{registerSkill as dg,getSkill as ug,hasSkill as pg,getAllSkills as mg,listSkillIds as fg}from"@zibby/agent-workflow";I(kr);I(Ir);I(Oe);I(Re);I(Or);I(Tr);I(Ar);I($r);I(P);I(W);I(Pr);I(Fr);I(zr);I(Qr);I(an);I(cn);I(ct);I(dn);I(jn);I(de);I(Jn);I(pn);I(yn);I(ei);I(ai);I(mi);I(Ii);I(Li);I(Ci);I(Ui);I(Bi);I(Qi);I(fr);I(hr);I(gr);I({...P,id:"slack_notify"});export{N as INTEGRATIONS,bs as INTEGRATION_REGISTRY,Ve as REPORT_SEVERITIES,sg as SKILLS,hr as anthropicBillingSkill,kr as browserSkill,Ii as chartRenderSkill,ei as chatMemorySkill,cn as chatNotifySkill,Ci as codeScanSkill,Bi as codebaseMemorySkill,yn as coreToolsSkill,gr as cursorAdminSkill,mi as datasetStoreSkill,Pr as discordSkill,Lu as fetchAllProviders,rs as fetchAnthropicCosts,$u as fetchAnthropicWorkspaces,ns as fetchCursorSpend,ts as fetchOpenAICosts,Eu as fetchOpenAIProjects,Or as figmaSkill,ap as functionSkill,mg as getAllSkills,ug as getSkill,de as gitSkill,Jn as gitWriteSkill,Oe as githubSkill,Re as gitlabSkill,Qr as googleDocsSkill,ju as groupByKey,pg as hasSkill,Ir as jiraSkill,ai as kvMemorySkill,an as larkDocsSkill,W as larkSkill,Tr as linearSkill,zr as linkedinSkill,fg as listSkillIds,Pu as meanStddev,dn as memorySkill,Fr as notionSkill,fr as openaiBillingSkill,$r as opendesignSkill,Ar as planeSkill,dg as registerSkill,Qe as reportObjectSchema,Gu as reportToBlockKit,Ku as reportToLarkCard,Yu as reportToMarkdown,Wu as reportToNotionBlocks,jn as runnerSkill,ct as sentrySkill,as as skill,pn as skillInstallerSkill,P as slackSkill,Li as socialCardSkill,jn as testRunnerSkill,Qi as workflowBuilderSkill};