@zibby/skills 2.0.4 → 2.0.6
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/artifact.js +7 -7
- package/dist/chat-notify.js +4 -4
- package/dist/chatProgress.js +4 -4
- package/dist/datasetStore.js +2 -2
- package/dist/discord.js +3 -3
- package/dist/figma.js +2 -2
- package/dist/git-write.js +9 -9
- package/dist/github.js +5 -5
- package/dist/gitlab.js +5 -5
- package/dist/googleDocs.js +9 -9
- package/dist/hubspot.js +1 -1
- package/dist/index.js +179 -181
- package/dist/jira.d.ts +36 -1
- package/dist/jira.js +22 -20
- package/dist/kvMemory.js +2 -2
- package/dist/lark.js +2 -2
- package/dist/larkAttendance.js +1 -1
- package/dist/larkDocs.js +3 -3
- package/dist/lib/http-deadline.d.ts +117 -0
- package/dist/lib/http-deadline.js +1 -0
- package/dist/lib/markup.d.ts +158 -0
- package/dist/lib/markup.js +22 -0
- package/dist/linear.js +15 -15
- package/dist/linkedin.js +2 -2
- package/dist/llm-billing.js +1 -1
- package/dist/notion.js +7 -7
- package/dist/opendesign.js +2 -2
- package/dist/package.json +6 -5
- package/dist/report.d.ts +42 -42
- package/dist/review.js +4 -4
- package/dist/reviewMemoryIo.js +1 -1
- package/dist/sentry.js +2 -2
- package/dist/skill-installer.js +3 -3
- package/dist/slack.js +2 -2
- package/dist/trackers/github-adapter.js +5 -5
- package/dist/trackers/index.js +46 -44
- package/dist/trackers/jira-adapter.js +24 -22
- package/dist/trackers/linear-adapter.js +19 -19
- package/dist/trackers/plane-adapter.js +1 -1
- package/dist/triggerAgent.js +1 -1
- package/dist/vikunja.d.ts +8 -1
- package/dist/vikunja.js +22 -7
- package/docs/templates/catalog-metadata.md +101 -0
- package/docs/templates/composition.md +97 -0
- package/docs/templates/deploy-time-config.md +228 -0
- package/docs/templates/index.md +138 -0
- package/docs/templates/models.md +157 -0
- package/docs/templates/node-declarations.md +149 -0
- package/docs/templates/remote-mcp.md +105 -0
- package/docs/templates/requires.md +183 -0
- package/docs/templates/sidecars.md +163 -0
- package/docs/templates/stores.md +113 -0
- package/docs/templates/surfaces.md +184 -0
- package/docs/templates/update-behavior.md +108 -0
- package/package.json +6 -5
package/dist/index.js
CHANGED
|
@@ -1,27 +1,30 @@
|
|
|
1
|
-
import{registerSkill as
|
|
1
|
+
import{registerSkill as Tb}from"@zibby/agent-workflow";var ts=Object.freeze(["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"]),qt=new WeakMap;function rs(r){if(!r||r.callsBackend!==!0)return r;if(qt.has(r))return qt.get(r);let e=Object.isExtensible(r)&&!Object.isFrozen(r)?r:{...r};if(qt.set(r,e),qt.set(e,e),e.command||Array.isArray(e.envKeys)){let t=Array.isArray(e.envKeys)?[...e.envKeys]:[];for(let n of ts)t.includes(n)||t.push(n);e.envKeys=t}if(typeof e.resolve=="function"){let t=e.resolve;e.resolve=function(...s){let i=t.apply(this,s);if(!i||!i.command)return i;let o={...i.env||{}};for(let a of ts)o[a]===void 0&&process.env[a]&&(o[a]=process.env[a]);return{...i,env:o}}}return e}import{createRequire as uc}from"module";import{join as mc}from"path";var hc=uc(import.meta.url);function fc(){if(process.env.MCP_BROWSER_PATH)return process.env.MCP_BROWSER_PATH;try{return hc.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js")}catch{return null}}var yc="1280x720",gc="1280x720";function bc({headless:r}={}){if(r===!0)return!0;if(r===!1)return!1;let e=process.env.ZIBBY_HEADLESS;return e==="1"||String(e).toLowerCase()==="true"}function _c(r,e){let t=(r||[]).filter(n=>n!=="--headless");return e?[...t,"--headless"]:t}var kc=`Execute this test using the browser tools available to you. You MUST make actual browser tool calls \u2014 do not fabricate results.
|
|
2
2
|
If you DO NOT have access to browser tools \u2192 return {"success": false, "steps": [], "browserClosed": false, "notes": "No browser tools available"}.
|
|
3
|
-
DO NOT return success: true unless you ACTUALLY called browser tools.`;function
|
|
3
|
+
DO NOT return success: true unless you ACTUALLY called browser tools.`;function ns(){return!process.env.PREVIEW_BASE_URL||!process.env.PREVIEW_TOKEN?"":'\n\n## Previewing a server YOU start in this container (dev-server preview)\nThe browser runs in an ISOLATED container: localhost/private URLs are unreachable from it \u2014 NEVER navigate to http://localhost:<port>. To let the browser view a server you start in this run (npm run dev, vite, a mock API \u2014 anything HTTP):\n1. Start the server bound to 0.0.0.0 (e.g. `npm run dev -- --host` or `HOST=0.0.0.0`); a localhost-only bind is unreachable from outside this container.\n2. Build the preview URL from this run\'s injected env (Bash): `echo "$PREVIEW_BASE_URL/<port>/?pvt=$PREVIEW_TOKEN"` \u2014 substitute your server\'s actual port.\n3. Serve your app at its own ROOT and leave the URL prefix alone \u2014 do NOT set a base path for the preview (Vite `base`, Next.js `basePath`, CRA `PUBLIC_URL`). The platform routes this page\'s root-absolute requests (`/assets/\u2026`, `/@vite/client`, XHR) back to your server for you. Setting a base to the preview prefix makes the dev server redirect to it in a LOOP, and re-adding the prefix by hand is never needed.\n4. browser_navigate to that exact URL. The first load does a cookie handshake and redirects; after that, assets, XHR and hot-reload all work \u2014 screenshots and video too.\n5. THE PREVIEW URL IS THE DOOR, NOT A ROUTE. After that first load the browser sits on `.../preview/<id>/<port>/`, which is not a path your app has \u2014 a client-side router (Vue Router, React Router, Next\'s app router) matches nothing there and renders its own 404/"Not found", on a dev server that is working perfectly. To open a specific route, drop the preview prefix and navigate to it at the ORIGIN ROOT: `echo "${PREVIEW_BASE_URL%/preview/*}/<your/route>"` (e.g. `http://host:port/settings`). The handshake cookie routes it to your server with the path UNCHANGED, so the router sees `/settings` and renders it. Do NOT reach for the prefixed `.../preview/<id>/<port>/settings` \u2014 the proxy strips the prefix before your server sees it, but the BROWSER keeps it, which is exactly what the router chokes on.\nThe preview lives only as long as this run. Do not put PREVIEW_TOKEN anywhere except that URL.'}var ss={id:"browser",serverName:"playwright",cursorKey:"playwright-official",allowedTools:["mcp__playwright__*"],sessionEnvKey:"ZIBBY_SESSION_INFO",description:"Playwright Browser MCP Server",envKeys:[],tools:[],promptFragment:()=>kc+ns(),resolve({sessionPath:r,workspace:e,nodeName:t,headless:n}={}){let s=fc(),i=r&&t?mc(r,t):null,o=i||r||e||"test-results",a=bc({headless:n}),c={};if(i&&(c.ZIBBY_NODE_SESSION_PATH=i),r&&(c.ZIBBY_SESSION_PATH=r),!s)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:
|
|
7
|
-
`)
|
|
8
|
-
|
|
9
|
-
`);continue}let s=n.
|
|
10
|
-
${i.join(`
|
|
11
|
-
`)}
|
|
12
|
-
|
|
13
|
-
${
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
${
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
`)
|
|
6
|
+
Override: set MCP_BROWSER_PATH to the path of mcp-browser-zibby.js.`);return{command:"node",args:_c([s,"--isolated",`--save-video=${yc}`,`--viewport-size=${gc}`,`--output-dir=${o}`],a),env:c}}};import{createRequire as Yc}from"module";import{resolveIntegrationToken as Wc,clearTokenCache as Zc}from"@zibby/core/backend-client.js";var I=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),wc=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 Chat",connectPath:"/integrations?provider=lark"},lark_docs:{id:"lark_docs",name:"Lark App",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var Gt={api:{knob:"SKILL_API_TIMEOUT_MS",fallback:3e4},transfer:{knob:"SKILL_TRANSFER_TIMEOUT_MS",fallback:12e4},job:{knob:"SKILL_JOB_TIMEOUT_MS",fallback:3e5}};function Sc(r,e,t=process.env){let n=Number(t?.[r]);return Number.isFinite(n)&&n>0?Math.min(6e5,Math.max(1e3,Math.floor(n))):e}function vc(r="api",e=process.env){let t=Gt[r]||Gt.api;return Sc(t.knob,t.fallback,e)}function Jr(r){return r?.name==="TimeoutError"||r?.name==="AbortError"}function Ic(r){try{return new URL(String(r?.url??r)).host||"unknown host"}catch{return"unknown host"}}function Tc(r,e){if(!r)return e;let t=new AbortController,n=o=>{t.signal.aborted||t.abort(o)},s=()=>n(r.reason),i=()=>n(e.reason);return t.signal.addEventListener("abort",()=>{r.removeEventListener("abort",s),e.removeEventListener("abort",i)},{once:!0}),r.aborted?n(r.reason):e.aborted?n(e.reason):(r.addEventListener("abort",s,{once:!0}),e.addEventListener("abort",i,{once:!0})),t.signal}async function w(r,e={},t={}){let n=t.kind||"api",s=(Gt[n]||Gt.api).knob,i=t.timeoutMs?Math.min(6e5,Math.max(1e3,Math.floor(t.timeoutMs))):vc(n),o=e?.signal;if(o?.aborted)throw o.reason??new DOMException("This operation was aborted","AbortError");let a=AbortSignal.timeout(i),c=Tc(o,a);try{return await fetch(r,{...e,signal:c})}catch(l){throw a.aborted&&Jr(l)?new Error(`${t.what||"request"} TIMED OUT after ${i}ms against ${Ic(r)} (${s})`):l}}var Nc={NOTE:"info",TIP:"success",IMPORTANT:"note",WARNING:"warning",CAUTION:"error"},Ht={info:"NOTE",success:"TIP",note:"IMPORTANT",warning:"WARNING",error:"CAUTION"},Oc=2e5,fs=6,Ac=/^```([A-Za-z0-9_+.-]{0,32})\s*$/,Rc=/^(#{1,6})[ \t]+(.*?)\s*$/,Ec=/^(?:-{3,}|\*{3,}|_{3,})\s*$/,is=/^>(?: ?(.*))?$/,qr=/^[-*][ \t]+\[([ xX])\][ \t]+(.*)$/,os=/^[-*][ \t]+(.*)$/,as=/^(\d{1,3})[.)][ \t]+(.*)$/,cs=/^\|.*\|\s*$/,xc=/^\|?\s*:?-{1,}:?\s*(?:\|\s*:?-{1,}:?\s*)*\|?\s*$/,Lc=/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/i;function ls(r){let e=r.trim().replace(/^\|/,"").replace(/\|$/,""),t=[],n="";for(let s=0;s<e.length;s++){let i=e[s];if(i==="\\"&&e[s+1]==="|"){n+="|",s++;continue}if(i==="|"){t.push(n.trim()),n="";continue}n+=i}return t.push(n.trim()),t}function zt(r){let t=String(r??"").slice(0,Oc).replace(/\r\n?/g,`
|
|
7
|
+
`).split(`
|
|
8
|
+
`);return Fr(t,0)}function Fr(r,e){let t=[],n=0;for(;n<r.length;){let s=r[n];if(s.trim()===""){n++;continue}if(/^[ \t]/.test(s)){t.push({t:"paragraph",c:J(s)}),n++;continue}let i;if(i=Ac.exec(s)){let o=i[1]||"",a=[];for(n++;n<r.length&&!/^```\s*$/.test(r[n]);)a.push(r[n]),n++;n++,t.push({t:"code",lang:o,v:a.join(`
|
|
9
|
+
`)});continue}if(Ec.test(s)){t.push({t:"rule"}),n++;continue}if(i=Rc.exec(s)){let o=Math.min(fs,i[1].length);t.push({t:"heading",level:o,c:J(i[2])}),n++;continue}if(is.test(s)&&e<3){let o=[];for(;n<r.length&&(i=is.exec(r[n]));)o.push(i[1]??""),n++;let a=o.findIndex(l=>l.trim()!==""),c=a>=0?Lc.exec(o[a].trim()):null;if(c){let l=Nc[c[1].toUpperCase()];t.push({t:"panel",kind:l,c:Fr(o.slice(a+1),e+1)})}else t.push({t:"quote",c:Fr(o,e+1)});continue}if(qr.test(s)){let o=[];for(;n<r.length&&(i=qr.exec(r[n]));)o.push({checked:i[1]!==" ",c:J(i[2])}),n++;t.push({t:"task",items:o});continue}if(os.test(s)){let o=[];for(;n<r.length&&!qr.test(r[n])&&(i=os.exec(r[n]));)o.push([{t:"paragraph",c:J(i[1])}]),n++;t.push({t:"bullet",items:o});continue}if(i=as.exec(s)){let o=Math.max(1,parseInt(i[1],10)||1),a=[];for(;n<r.length&&(i=as.exec(r[n]));)a.push([{t:"paragraph",c:J(i[2])}]),n++;t.push({t:"ordered",start:o,items:a});continue}if(cs.test(s)&&n+1<r.length&&xc.test(r[n+1])){let o=ls(s).map(J);n+=2;let a=[];for(;n<r.length&&cs.test(r[n]);)a.push(ls(r[n]).map(J)),n++;t.push({t:"table",header:o,rows:a});continue}t.push({t:"paragraph",c:J(s)}),n++}return t}var $c=/^https?:\/\/[^\s<>()[\]]+/,jc=/^\[([^\]\n]{1,300})\]\((https?:\/\/[^\s)]{1,2000})\)/,Pc=/[.,;:!?'"]+$/;function Cc(r,e){return e<=0?!0:/[\s([{"'“‘>:—–-]/.test(r[e-1])}function Uc(r,e){return e>=r.length?!0:/[\s)\]}"'”’.,;:!?—–-]/.test(r[e])}function Bc(r,e,t){let n=e;for(;n<r.length;){let s=r.indexOf(t,n);if(s<0)return-1;let i=r[s-1],o=r[s+t.length],a=t.length===1&&(i===t||o===t);if(s>e&&i&&!/\s/.test(i)&&!a&&Uc(r,s+t.length))return s;n=s+1}return-1}function J(r){let e=String(r??""),t=[],n="",s=()=>{n&&(t.push({t:"text",v:n}),n="")},i=0;for(;i<e.length;){let o=e[i];if(o==="`"){let a=1;for(;e[i+a]==="`";)a++;let c="`".repeat(a),l=e.indexOf(c,i+a);if(l>i+a-1&&l!==-1){let d=e.slice(i+a,l);if(d.trim()){s(),t.push({t:"code",v:d.length>1&&d.startsWith(" ")&&d.endsWith(" ")?d.slice(1,-1):d}),i=l+a;continue}}n+=c,i+=a;continue}if(o==="["){let a=jc.exec(e.slice(i));if(a){s(),t.push({t:"link",href:a[2],c:J(a[1])}),i+=a[0].length;continue}}if((o==="*"||o==="_"||o==="~")&&Cc(e,i)){let a=e[i+1]===o;if(o==="~"&&!a){n+=o,i++;continue}let c=a?o+o:o,l=i+c.length;if(l<e.length&&!/\s/.test(e[l])){let d=Bc(e,l,c);if(d>l){s();let p=J(e.slice(l,d));t.push(o==="~"?{t:"strike",c:p}:a?{t:"strong",c:p}:{t:"em",c:p}),i=d+c.length;continue}}}if(o==="h"&&(i===0||/[\s(<]/.test(e[i-1]))){let a=$c.exec(e.slice(i));if(a){let c=a[0],l=Pc.exec(c);if(l&&(c=c.slice(0,-l[0].length)),c.length>8){s(),t.push({t:"link",href:c,c:[{t:"text",v:c}]}),i+=c.length;continue}}}n+=o,i++}return s(),t}function $e(r,e=[]){let t=[];for(let n of r)switch(n.t){case"text":n.v&&t.push({type:"text",text:n.v,...e.length?{marks:e}:{}});break;case"br":t.push({type:"hardBreak"});break;case"code":t.push({type:"text",text:n.v,marks:[{type:"code"},...e.filter(s=>s.type==="link")]});break;case"strong":t.push(...$e(n.c,Kt(e,{type:"strong"})));break;case"em":t.push(...$e(n.c,Kt(e,{type:"em"})));break;case"strike":t.push(...$e(n.c,Kt(e,{type:"strike"})));break;case"link":t.push(...$e(n.c,Kt(e,{type:"link",attrs:{href:n.href}})));break}return t}function Kt(r,e){return r.some(t=>t.type===e.type)?r:[...r,e]}var Gr=0;function ds(){return Gr=(Gr+1)%1e6,`m${Date.now().toString(36)}-${Gr}`}var Ye=r=>{let e=$e(r);return e.length?{type:"paragraph",content:e}:{type:"paragraph"}};function xe(r,e){let t=[];for(let n of r)switch(n.t){case"paragraph":t.push(Ye(n.c));break;case"heading":if(e==="quote"||e==="item")t.push(Ye([{t:"strong",c:n.c}]));else{let s=$e(n.c);s.length&&t.push({type:"heading",attrs:{level:n.level},content:s})}break;case"bullet":t.push({type:"bulletList",content:n.items.map(s=>({type:"listItem",content:Ft(xe(s,"item"))}))});break;case"ordered":t.push({type:"orderedList",attrs:{order:n.start},content:n.items.map(s=>({type:"listItem",content:Ft(xe(s,"item"))}))});break;case"task":e==="quote"||e==="item"?t.push({type:"bulletList",content:n.items.map(s=>({type:"listItem",content:[Ye([{t:"text",v:s.checked?"\u2611 ":"\u2610 "},...s.c])]}))}):t.push({type:"taskList",attrs:{localId:ds()},content:n.items.map(s=>({type:"taskItem",attrs:{localId:ds(),state:s.checked?"DONE":"TODO"},content:Dc($e(s.c))}))});break;case"code":t.push({type:"codeBlock",attrs:n.lang?{language:n.lang}:{},...n.v?{content:[{type:"text",text:n.v}]}:{}});break;case"quote":e==="quote"||e==="item"?t.push(...xe(n.c,e)):t.push({type:"blockquote",content:Ft(xe(n.c,"quote"))});break;case"panel":e!=="doc"?t.push(...xe(n.c,e)):t.push({type:"panel",attrs:{panelType:n.kind},content:Ft(xe(n.c,"panel"))});break;case"rule":if(e==="quote"||e==="item")break;t.push({type:"rule"});break;case"table":{if(e!=="doc"){for(let i of[...n.header?[n.header]:[],...n.rows])t.push(Ye(Mc(i)));break}let s=[];n.header&&s.push({type:"tableRow",content:n.header.map(i=>({type:"tableHeader",attrs:{},content:[Ye(i)]}))});for(let i of n.rows)s.push({type:"tableRow",content:i.map(o=>({type:"tableCell",attrs:{},content:[Ye(o)]}))});s.length&&t.push({type:"table",attrs:{isNumberColumnEnabled:!1,layout:"default"},content:s});break}}return t}function Ft(r){return r.length?r:[{type:"paragraph"}]}function Dc(r){return r.length?r:[{type:"text",text:" "}]}function Mc(r){let e=[];return r.forEach((t,n)=>{n&&e.push({t:"text",v:" \xB7 "}),e.push(...t)}),e}function Hr(r){return{type:"doc",version:1,content:String(r??"").split(`
|
|
10
|
+
`).map(e=>({type:"paragraph",...e?{content:[{type:"text",text:e}]}:{}}))}}function ys(r){try{let e=xe(zt(r),"doc");return{type:"doc",version:1,content:e.length?e:[{type:"paragraph"}]}}catch{return Hr(r)}}function je(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function fe(r){let e="";for(let t of r)switch(t.t){case"text":e+=je(t.v);break;case"br":e+="<br>";break;case"code":e+=`<code>${je(t.v)}</code>`;break;case"strong":e+=`<strong>${fe(t.c)}</strong>`;break;case"em":e+=`<em>${fe(t.c)}</em>`;break;case"strike":e+=`<s>${fe(t.c)}</s>`;break;case"link":e+=`<a href="${je(t.href)}" target="_blank" rel="noopener noreferrer">${fe(t.c)}</a>`;break}return e}function Jc(r){return r.length&&r[0].t==="text"&&/^ /.test(r[0].v)?[{t:"text",v:`\xA0${r[0].v.slice(1)}`},...r.slice(1)]:r}function ht(r){let e="";for(let t of r)switch(t.t){case"paragraph":e+=`<p>${fe(Jc(t.c))}</p>`;break;case"heading":e+=`<h${t.level}>${fe(t.c)}</h${t.level}>`;break;case"bullet":e+=`<ul>${t.items.map(n=>`<li>${ht(n)}</li>`).join("")}</ul>`;break;case"ordered":e+=`<ol${t.start!==1?` start="${t.start}"`:""}>${t.items.map(n=>`<li>${ht(n)}</li>`).join("")}</ol>`;break;case"task":e+=`<ul data-type="taskList">${t.items.map(n=>`<li data-type="taskItem" data-checked="${n.checked?"true":"false"}"><label><input type="checkbox"${n.checked?' checked="checked"':""}><span></span></label><div><p>${fe(n.c)}</p></div></li>`).join("")}</ul>`;break;case"code":e+=`<pre><code${t.lang?` class="language-${je(t.lang)}"`:""}>${je(t.v)}</code></pre>`;break;case"quote":e+=`<blockquote>${ht(t.c)}</blockquote>`;break;case"panel":e+=`<blockquote><p><strong>${Ht[t.kind][0]}${Ht[t.kind].slice(1).toLowerCase()}</strong></p>${ht(t.c)}</blockquote>`;break;case"rule":e+="<hr>";break;case"table":{let n="<table><tbody>";t.header&&(n+=`<tr>${t.header.map(s=>`<th><p>${fe(s)}</p></th>`).join("")}</tr>`);for(let s of t.rows)n+=`<tr>${s.map(i=>`<td><p>${fe(i)}</p></td>`).join("")}</tr>`;e+=`${n}</tbody></table>`;break}}return e}function gs(r){try{return ht(zt(r))||`<p>${je(String(r??""))}</p>`}catch{return String(r??"").split(`
|
|
11
|
+
`).map(e=>`<p>${je(e)}</p>`).join("")}}function ve(r){let e="";for(let t of r)switch(t.t){case"text":e+=t.v;break;case"br":e+=`
|
|
12
|
+
`;break;case"code":e+=`\`${t.v}\``;break;case"strong":e+=`**${ve(t.c)}**`;break;case"em":e+=`_${ve(t.c)}_`;break;case"strike":e+=`~~${ve(t.c)}~~`;break;case"link":{let n=ve(t.c);e+=!n||n===t.href?t.href:`[${n}](${t.href})`;break}}return e}function se(r){let e="";for(let t of r)switch(t.t){case"paragraph":e+=`${ve(t.c)}
|
|
13
|
+
`;break;case"heading":e+=`${"#".repeat(Math.max(1,Math.min(fs,t.level)))} ${ve(t.c)}
|
|
14
|
+
`;break;case"bullet":for(let n of t.items)e+=`- ${se(n).trim()}
|
|
15
|
+
`;break;case"ordered":t.items.forEach((n,s)=>{e+=`${t.start+s}. ${se(n).trim()}
|
|
16
|
+
`});break;case"task":for(let n of t.items)e+=`- [${n.checked?"x":" "}] ${ve(n.c)}
|
|
17
|
+
`;break;case"code":e+=`\`\`\`${t.lang}
|
|
18
|
+
${t.v}
|
|
19
|
+
\`\`\`
|
|
20
|
+
`;break;case"quote":e+=ps(se(t.c));break;case"panel":e+=`> [!${Ht[t.kind]}]
|
|
21
|
+
${ps(se(t.c))}`;break;case"rule":e+=`---
|
|
22
|
+
`;break;case"table":{let n=s=>`| ${s.map(i=>ve(i).replace(/\|/g,"\\|")).join(" | ")} |
|
|
23
|
+
`;t.header&&(e+=n(t.header)+`|${t.header.map(()=>" --- |").join("")}
|
|
24
|
+
`);for(let s of t.rows)e+=n(s);break}}return e}function bs(r){return r.replace(/^\n+/,"").replace(/\s+$/,"")}function ps(r){return r.replace(/\n$/,"").split(`
|
|
25
|
+
`).map(e=>e?`> ${e}`:">").join(`
|
|
26
|
+
`)+`
|
|
27
|
+
`}function We(r){let e=[];for(let t of r||[])if(!(!t||typeof t!="object"))switch(t.type){case"text":{let n={t:"text",v:String(t.text??"")},s=Array.isArray(t.marks)?t.marks:[];s.some(i=>i?.type==="code")&&(n={t:"code",v:String(t.text??"")});for(let i of s)!i||i.type==="code"||(i.type==="strong"?n={t:"strong",c:[n]}:i.type==="em"?n={t:"em",c:[n]}:i.type==="strike"?n={t:"strike",c:[n]}:i.type==="link"&&i.attrs?.href&&(n={t:"link",href:String(i.attrs.href),c:[n]}));e.push(n);break}case"hardBreak":e.push({t:"br"});break;case"mention":e.push({t:"text",v:String(t.attrs?.text||(t.attrs?.id?`@${t.attrs.id}`:"@someone"))});break;case"emoji":e.push({t:"text",v:String(t.attrs?.text||t.attrs?.shortName||"")});break;case"status":e.push({t:"text",v:String(t.attrs?.text||"")});break;case"date":e.push({t:"text",v:t.attrs?.timestamp?new Date(Number(t.attrs.timestamp)).toISOString().slice(0,10):""});break;case"inlineCard":{let n=String(t.attrs?.url||"");n&&e.push({t:"link",href:n,c:[{t:"text",v:n}]});break}default:Array.isArray(t.content)?e.push(...We(t.content)):typeof t.text=="string"&&e.push({t:"text",v:t.text})}return e}function ne(r){let e=[];for(let t of r||[])if(!(!t||typeof t!="object"))switch(t.type){case"paragraph":e.push({t:"paragraph",c:We(t.content)});break;case"heading":e.push({t:"heading",level:Number(t.attrs?.level)||1,c:We(t.content)});break;case"bulletList":e.push({t:"bullet",items:(t.content||[]).map(n=>ne(n?.content))});break;case"orderedList":e.push({t:"ordered",start:Number(t.attrs?.order)||1,items:(t.content||[]).map(n=>ne(n?.content))});break;case"taskList":e.push({t:"task",items:(t.content||[]).map(n=>({checked:n?.attrs?.state==="DONE",c:We(n?.content)}))});break;case"decisionList":e.push({t:"bullet",items:(t.content||[]).map(n=>[{t:"paragraph",c:We(n?.content)}])});break;case"codeBlock":e.push({t:"code",lang:String(t.attrs?.language||""),v:(t.content||[]).map(n=>String(n?.text??"")).join("")});break;case"blockquote":e.push({t:"quote",c:ne(t.content)});break;case"panel":{let n=String(t.attrs?.panelType||"info");e.push({t:"panel",kind:n in Ht?n:"info",c:ne(t.content)});break}case"rule":e.push({t:"rule"});break;case"table":{let n=(t.content||[]).filter(a=>a?.type==="tableRow"),s=a=>(a.content||[]).map(c=>{let l=ne(c?.content);return J(se(l).trim().replace(/\n+/g," "))}),i=a=>(a.content||[]).length>0&&(a.content||[]).every(c=>c?.type==="tableHeader"),o=n.length&&i(n[0])?s(n[0]):null;e.push({t:"table",header:o,rows:n.slice(o?1:0).map(s)});break}case"mediaSingle":case"mediaGroup":case"media":case"mediaInline":e.push({t:"paragraph",c:[{t:"text",v:"[attachment]"}]});break;case"expand":case"nestedExpand":{let n=String(t.attrs?.title||"").trim();n&&e.push({t:"paragraph",c:[{t:"strong",c:[{t:"text",v:n}]}]}),e.push(...ne(t.content));break}default:{let n=Array.isArray(t.content)?t.content:[];n.some(s=>s?.type==="text"||s?.type==="hardBreak")?e.push({t:"paragraph",c:We(n)}):n.length?e.push(...ne(n)):typeof t.text=="string"&&t.text&&e.push({t:"paragraph",c:[{t:"text",v:t.text}]})}}return e}function qc(r){try{if(Array.isArray(r))return ne(r);if(r&&typeof r=="object"){let e=r;return e.type==="doc"||!e.type&&Array.isArray(e.content)?ne(e.content):ne([e])}if(typeof r=="string")return zt(r)}catch{}return[]}function zr(r){try{return bs(se(qc(r)))}catch{return""}}var Gc={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",hellip:"\u2026",mdash:"\u2014",ndash:"\u2013",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",copy:"\xA9",reg:"\xAE",trade:"\u2122"};function us(r){return r.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(e,t)=>{if(t[0]==="#"){let s=t[1]==="x"||t[1]==="X"?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Number.isFinite(s)&&s>0&&s<1114112?String.fromCodePoint(s):e}let n=Gc[t.toLowerCase()];return n===void 0?e:n})}function Kc(r){let e=[],t=/<!--[\s\S]*?-->|<\/([A-Za-z][\w:-]*)\s*>|<([A-Za-z][\w:-]*)((?:\s+[^\s=>/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*(\/?)>|([^<]+)|(<)/g,n;for(;n=t.exec(r);)if(n[1])e.push({kind:"close",name:n[1].toLowerCase()});else if(n[2]){let s={},i=/([^\s=>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g,o;for(;o=i.exec(n[3]||"");)s[o[1].toLowerCase()]=us(o[2]??o[3]??o[4]??"");let a=n[2].toLowerCase();e.push({kind:"open",name:a,attrs:s,selfClose:!!n[4]||a==="br"||a==="hr"||a==="img"||a==="input"})}else n[5]!==void 0?e.push({kind:"text",v:us(n[5])}):n[6]&&e.push({kind:"text",v:"<"});return e}var ms=new Set(["p","div","h1","h2","h3","h4","h5","h6","ul","ol","li","blockquote","pre","hr","table","thead","tbody","tfoot","tr","td","th","section","article","header","footer","details","summary","figure","figcaption"]),Fc=new Set(["script","style","label","input","button","svg","head","title"]);function Le(r){let e=[],t=0,n=[],s=[],i=l=>{let d=Hc(n);n=[],d.length&&e.push(l?l(d):{t:"paragraph",c:d})},o=l=>{if(!l)return;let d={t:"text",v:l};for(let p=s.length-1;p>=0;p--){let u=s[p];u==="strong"?d={t:"strong",c:[d]}:u==="em"?d={t:"em",c:[d]}:u==="strike"?d={t:"strike",c:[d]}:d={t:"link",href:u.link,c:[d]}}n.push(d)},a=l=>{let d=[],p=1;for(;t<r.length;){let u=r[t++];if(u.kind==="open"&&u.name===l&&!u.selfClose&&p++,u.kind==="close"&&u.name===l&&(p--,p===0))break;d.push(u)}return d},c=l=>l.filter(d=>d.kind==="text").map(d=>d.v).join("");for(;t<r.length;){let l=r[t++];if(l.kind==="text"){o(l.v.replace(/\s+/g," "));continue}if(l.kind==="close"){if(l.name==="strong"||l.name==="b")Kr(s,"strong");else if(l.name==="em"||l.name==="i")Kr(s,"em");else if(l.name==="s"||l.name==="del"||l.name==="strike")Kr(s,"strike");else if(l.name==="a"){let p=s.map(u=>typeof u=="object").lastIndexOf(!0);p>=0&&s.splice(p,1)}else ms.has(l.name)&&i();continue}let d=l.name;if(Fc.has(d)){l.selfClose||a(d);continue}if(d==="br"){n.push({t:"br"});continue}if(d==="hr"){i(),e.push({t:"rule"});continue}if(d==="strong"||d==="b"){s.push("strong");continue}if(d==="em"||d==="i"){s.push("em");continue}if(d==="s"||d==="del"||d==="strike"){s.push("strike");continue}if(d==="a"){l.attrs.href?s.push({link:l.attrs.href}):s.push({link:""});continue}if(d==="code"){let p=c(a("code"));p&&n.push({t:"code",v:p});continue}if(d==="pre"){i();let p=a("pre"),u=p.find(h=>h.kind==="open"&&h.name==="code"),m=u&&/language-([\w+.-]+)/.exec(u.attrs.class||"")?.[1]||"";e.push({t:"code",lang:m,v:c(p).replace(/\n$/,"")});continue}if(/^h[1-6]$/.test(d)){i();let p=Number(d[1]),u=Le(a(d));e.push({t:"heading",level:p,c:J(se(u).trim().replace(/\n+/g," "))});continue}if(d==="blockquote"){i(),e.push({t:"quote",c:Le(a(d))});continue}if(d==="ul"||d==="ol"){i();let p=a(d),u=(l.attrs["data-type"]||"")==="tasklist",m=[],h=[],y=0;for(;y<p.length;){let f=p[y++];if(f.kind==="open"&&f.name==="li"){let b=[],g=1;for(;y<p.length;){let v=p[y++];if(v.kind==="open"&&v.name==="li"&&!v.selfClose&&g++,v.kind==="close"&&v.name==="li"&&(g--,g===0))break;b.push(v)}m.push(b);let k=(f.attrs["data-checked"]||"")==="true"||b.some(v=>v.kind==="open"&&v.name==="input"&&"checked"in v.attrs);h.push(k)}}u||m.some(f=>f.some(b=>b.kind==="open"&&b.name==="input"&&(b.attrs.type||"")==="checkbox"))?e.push({t:"task",items:m.map((f,b)=>({checked:h[b],c:J(se(Le(f)).trim().replace(/\n+/g," "))}))}):d==="ul"?e.push({t:"bullet",items:m.map(f=>hs(Le(f)))}):e.push({t:"ordered",start:Math.max(1,parseInt(l.attrs.start||"1",10)||1),items:m.map(f=>hs(Le(f)))});continue}if(d==="table"){i();let p=a("table"),u=[],m=[],h=0;for(;h<p.length;){let _=p[h++];if(_.kind==="open"&&_.name==="tr"){let f=[],b=!0,g=1,k=[];for(;h<p.length;){let x=p[h++];if(x.kind==="open"&&x.name==="tr"&&!x.selfClose&&g++,x.kind==="close"&&x.name==="tr"&&(g--,g===0))break;k.push(x)}let v=0;for(;v<k.length;){let x=k[v++];if(x.kind==="open"&&(x.name==="td"||x.name==="th")){x.name!=="th"&&(b=!1);let V=[],R=1;for(;v<k.length;){let A=k[v++];if(A.kind==="open"&&A.name===x.name&&!A.selfClose&&R++,A.kind==="close"&&A.name===x.name&&(R--,R===0))break;V.push(A)}f.push(J(se(Le(V)).trim().replace(/\n+/g," ")))}}f.length&&(u.push(f),m.push(b))}}let y=u.length&&m[0]?u[0]:null;e.push({t:"table",header:y,rows:u.slice(y?1:0)});continue}if(ms.has(d)){i();continue}}return i(),e}function Kr(r,e){let t=r.lastIndexOf(e);t>=0&&r.splice(t,1)}function hs(r){return r.length?r:[{t:"paragraph",c:[]}]}function Hc(r){let e=[...r];for(;e.length&&e[0].t==="text"&&!e[0].v.trim();)e.shift();for(;e.length&&e[e.length-1].t==="text"&&!e[e.length-1].v.trim();)e.pop();e.length&&e[0].t==="text"&&(e[0]={t:"text",v:e[0].v.replace(/^\s+/," ")});let t=e.length-1;return t>=0&&e[t].t==="text"&&(e[t]={t:"text",v:e[t].v.replace(/\s+$/,"")}),e}function zc(r){try{let e=String(r??"");return/<[a-z][\s\S]*>/i.test(e)?Le(Kc(e)):zt(e)}catch{return[]}}function _s(r){try{return bs(se(zc(r)))}catch{return""}}var Vc=Yc(import.meta.url);function Xc(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return Vc.resolve("@zibby/mcp-jira/index.js")}catch{return null}}function Qc(r){return ys(r)}async function Yr(r,e){try{return await r(Qc(e))}catch(t){let n=Number(t?.status);if(!(n>=400&&n<500))throw t;return console.warn(`[jira] rich body rejected (${n}) \u2014 retrying as plain text: ${String(t?.message||t).slice(0,200)}`),await r(Hr(e))}}function Ze(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Wr(r){return Ze(r).replace(/[a-z0-9]+/g,"")}function Yt(r,e){let t=Ze(r),n=Ze(e);if(!t||!n)return 0;if(t===n)return 1;if(t.length===1||n.length===1)return t===n?1:0;let s=d=>{let p=new Map;for(let u=0;u<d.length-1;u++){let m=d.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},i=s(t),o=s(n),a=0,c=0,l=0;for(let d of i.values())c+=d;for(let d of o.values())l+=d;for(let[d,p]of i.entries()){let u=o.get(d)||0;a+=Math.min(p,u)}return 2*a/Math.max(1,c+l)}function Ie(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function el(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),s=n.length>0?n:t,i=Ie(r);if(i){let a=s.find(d=>Ie(d.name)===i);if(a)return{requested:r,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let d of Object.values(c)){if(!d.some(u=>Ie(u)===i))continue;let p=s.find(u=>d.some(m=>Ie(m)===Ie(u.name)));if(p)return{requested:r,resolved:p,strategy:"alias"}}let l=s.map(d=>({t:d,score:Yt(r,d.name)})).sort((d,p)=>p.score-d.score);if(l[0]&&l[0].score>=.5)return{requested:r,resolved:l[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=s.find(l=>Ie(l.name)===a);if(c)return{requested:r||null,resolved:c,strategy:"default-preferred"}}return{requested:r||null,resolved:s[0],strategy:"default-first"}}async function ks(r){let e=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,t=await $(`/rest/api/3/issue/createmeta?${e}`),n=Array.isArray(t?.projects)?t.projects:[],i=n.find(a=>String(a?.key||"").toUpperCase()===String(r||"").toUpperCase())||n[0]||null;return(Array.isArray(i?.issuetypes)?i.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function ws(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`,s=`jql=${encodeURIComponent(n)}&maxResults=100&fields=customfield_10020`,i=await $(`/rest/api/3/search/jql?${s}`),o=new Map;for(let a of i.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let l={active:0,future:1,closed:2},d=(l[a.state]??3)-(l[c.state]??3);return d!==0?d:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function tl(r,{sprintId:e,sprintName:t,target:n}={}){let s=Array.isArray(r)?r:[];if(!s.length)return{sprint:null,selectedBy:"none"};if(e!=null&&String(e).trim()!=="")return{sprint:s.find(a=>String(a.id)===String(e))||null,selectedBy:"id"};if(t&&String(t).trim()){let o=String(t).trim(),a=s.find(l=>String(l.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=s.map(l=>({s:l,score:Yt(o,l.name||"")})).sort((l,d)=>d.score-l.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let i=String(n||"current").trim().toLowerCase();return i==="active"||i==="current"||i==="latest"?{sprint:s[0],selectedBy:i}:{sprint:s[0],selectedBy:"default"}}function rl(r,e){let t=r?.fields?.customfield_10020;return Array.isArray(t)?t.some(n=>String(n?.id)===String(e)):!1}async function nl({issueKey:r,projectKey:e,sprintId:t,attempts:n=3,delayMs:s=450}){let i=[];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`,l=await $(`/rest/api/3/search/jql?${c}`);if(Number(l?.total||0)>0)return i.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:i};let p=await $(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),u=rl(p,t);if(i.push({attempt:o+1,jql:!1,issueField:u}),u)return{ok:!0,method:"issue_field",traces:i}}catch(a){i.push({attempt:o+1,error:String(a?.message||a)})}o<n-1&&await new Promise(a=>setTimeout(a,s))}return{ok:!1,method:"none",traces:i}}async function Zr({issueKey:r,projectKey:e,sprintId:t,sprintName:n,target:s}){if(!r)return{ok:!1,error:"issueKey is required"};let i=e;if(!i&&(i=(await $(`/rest/api/3/issue/${r}?fields=project`))?.fields?.project?.key||null,!i))return{ok:!1,error:`Could not resolve project for ${r}`};let o=await ws(i,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${i}`};let{sprint:a,selectedBy:c}=tl(o,{sprintId:t,sprintName:n,target:s});if(!a)return{ok:!1,error:`No matching sprint found in ${i}`,requested:{sprintId:t??null,sprintName:n??null,target:s??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await $(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let l=await nl({issueKey:r,projectKey:i,sprintId:a.id}),d=l.ok;return{ok:d,issueKey:r,projectKey:i,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:l.method,verified:d,verificationTrace:l.traces,warning:d?null:`Sprint assignment attempted but verification did not find ${r} in sprint ${a.id}`}}async function sl(){let r=process.env.JIRA_API_TOKEN,e=process.env.JIRA_EMAIL,t=process.env.JIRA_BASE_URL;if(r&&e&&t)return{authType:"token",apiToken:r,email:e,baseUrl:t};let n=await Wc("jira");return n?.cloudId?{authType:"oauth",accessToken:n.token,cloudId:n.cloudId}:{authType:"token",apiToken:n?.token,email:e||n?.email||"",baseUrl:t||n?.instanceUrl||n?.baseUrl||process.env.ATLASSIAN_INSTANCE_URL||""}}function il(r,e,t={}){let n=r||{},s={Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers};if(n.authType==="token"){let i=String(n.baseUrl||n.instanceUrl||"").trim().replace(/\/+$/,""),o=n.apiToken||n.accessToken||"";if(!i)throw new Error("Jira token connection has no base URL \u2014 reconnect Jira with its instance URL, or set JIRA_BASE_URL.");if(!n.email)throw new Error("Jira token connection has no account email \u2014 reconnect Jira with the account email, or set JIRA_EMAIL.");if(!o)throw new Error("Jira token connection has no API token \u2014 reconnect Jira, or set JIRA_API_TOKEN.");return{url:`${i}${e}`,headers:{Authorization:"Basic "+Buffer.from(`${n.email}:${o}`).toString("base64"),...s}}}if(typeof n.accessToken!="string"||!n.accessToken)throw new Error(`Invalid jira token type: ${typeof n.accessToken}`);if(!n.cloudId)throw new Error("Invalid jira cloudId: missing");return{url:`https://api.atlassian.com/ex/jira/${n.cloudId}${e}`,headers:{Authorization:`Bearer ${n.accessToken}`,...s}}}async function $(r,e={}){let t=async()=>{let n=await sl(),{url:s,headers:i}=il(n,r,e),o=await w(s,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0,signal:e.signal},{kind:/\/search\b/.test(String(r))?"job":"api",what:`Jira ${e.method||"GET"} ${r}`}),a=()=>o.text().catch(l=>{if(Jr(l)||e.signal?.aborted)throw l;return""});if(!o.ok){let l=await a(),d=new Error(`Jira API ${o.status}: ${l.slice(0,300)}`);throw d.status=o.status,d}let c=await a();if(!c||!c.trim())return{};try{return JSON.parse(c)}catch{return{raw:c}}};try{return await t()}catch(n){if(e.signal?.aborted)throw n;let s=String(n?.message||n||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("403")||s.includes("substring")))throw n;return Zc("jira"),t()}}var Ss={id:"jira",callsBackend:!0,serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:I.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira
|
|
25
28
|
You have direct access to the user's Jira. Use these tools proactively:
|
|
26
29
|
|
|
27
30
|
### Issue tools
|
|
@@ -71,7 +74,7 @@ When user asks to move/transition ticket status:
|
|
|
71
74
|
3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
|
|
72
75
|
4. Call jira_get_issue(issueKey) to verify final status before claiming success.
|
|
73
76
|
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=Da();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);process.env.ATLASSIAN_INSTANCE_URL&&(t.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let e of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[e]&&(t[e]=process.env[e]);return{command:"node",args:[r],env:t,description:this.description}},async handleToolCall(r,t){try{switch(r){case"jira_list_projects":{let e=await L("/rest/api/3/project"),n=(Array.isArray(e)?e:[]).map(s=>({id:s.id,key:s.key,name:s.name,style:s.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:e}=t||{};if(e){let i=await L(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(i)?i:[],a=new Map;for(let l of o)for(let d of l.statuses||[])d?.id&&(a.has(d.id)||a.set(d.id,{id:d.id,name:d.name,category:d.statusCategory?.name||null}));let c=[...a.values()].sort((l,d)=>String(l.name).localeCompare(String(d.name)));return JSON.stringify({scope:"project",projectKey:e,count:c.length,statuses:c})}let n=await L("/rest/api/3/status"),s=(Array.isArray(n)?n:[]).map(i=>({id:i.id,name:i.name,category:i.statusCategory?.name||null})).sort((i,o)=>String(i.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:s.length,statuses:s})}case"jira_list_issue_types":{let{projectKey:e}=t||{};if(!e)return JSON.stringify({error:"projectKey is required"});let n=await jn(e);return JSON.stringify({projectKey:e,count:n.length,issueTypes:n})}case"jira_search":{let e=t.jql||"",n=t.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let i=`jql=${encodeURIComponent(e)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await L(`/rest/api/3/search/jql?${i}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let e=t.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let n=await L(`/rest/api/3/issue/${e}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name,labels:n.fields?.labels,created:n.fields?.created,updated:n.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:n,issueType:s,description:i,priority:o,labels:a,assigneeId:c,moveToSprint:l,moveToActiveSprint:d,sprintId:p,sprintName:u,target:m}=t;if(!e||!n)return JSON.stringify({error:"projectKey and summary are required"});let h={requested:s||null,resolved:null,strategy:"none"},f=[];try{f=await jn(e),h=qa(s,f)}catch{}let b={project:{key:e},summary:n,issuetype:h?.resolved?.id?{id:h.resolved.id}:{name:s||"Task"}};i&&(b.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:i}]}]}),o&&(b.priority={name:o}),a?.length&&(b.labels=a),c&&(b.assignee={id:c});let y=await L("/rest/api/3/issue",{method:"POST",body:{fields:b}}),_={ok:!0,key:y.key,id:y.id,self:y.self};return h?.resolved&&(_.issueType=h.resolved.name,_.issueTypeResolution=h.strategy,h.strategy!=="exact"&&h.requested&&_e(h.requested)!==_e(h.resolved.name)&&(_.issueTypeWarning=`Requested "${h.requested}" is not available in ${e}; used "${h.resolved.name}" instead.`)),f.length>0&&(_.availableIssueTypes=f.map(g=>g.name)),(l||d)&&(_.sprintMove=await Nr({issueKey:y.key,projectKey:e,sprintId:p,sprintName:u,target:m})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:e,state:n}=t,s=await $n(e,n);return JSON.stringify({count:s.length,sprints:s})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:n,sprintId:s,sprintName:i,target:o}=t||{},a=await Nr({issueKey:e,projectKey:n,sprintId:s,sprintName:i,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:n,sprintId:s,sprintName:i,target:o}=t||{},a=await Nr({issueKey:e,projectKey:n,sprintId:s,sprintName:i,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:n,projectKey:s,status:i,maxResults:o}=t;if(!e&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${e}"`,l=s?`project = ${s} AND `:"",d=i?` AND status = "${i}"`:"",p=`${l}${c}${d} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await L(`/rest/api/3/search/jql?${u}`),h=(m.issues||[]).map(b=>({key:b.key,project:b.fields?.project?.key,summary:b.fields?.summary,status:b.fields?.status?.name,assignee:b.fields?.assignee?.displayName||"Unassigned",priority:b.fields?.priority?.name,type:b.fields?.issuetype?.name})),f={};for(let b of h)f[b.status]=(f[b.status]||0)+1;return JSON.stringify({count:h.length,total:m.total||h.length,statusCounts:f,issues:h})}case"jira_get_comments":{let{issueKey:e,maxResults:n}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let i=await L(`/rest/api/3/issue/${e}/comment?maxResults=${n||50}&orderBy=-created`),o=(i.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:i.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:n}=t;return!e||!n?JSON.stringify({error:"issueKey and body are required"}):(await L(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:n}=t;return!e||!n?JSON.stringify({error:"issueKey and fields are required"}):(await L(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:n,toStatus:s,statusName:i,status:o}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(s||i||o||"").trim();if(!n&&!a){let p=((await L(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:p})}let c=n;if(!c){let p=(await L(`/rest/api/3/issue/${e}/transitions`)).transitions||[],u=Be(a),m=p.find(h=>Be(h?.name||"")===u||Be(h?.to?.name||"")===u);if(!m){let h=Ir(a);h.length>=2&&(m=p.find(f=>{let b=Ir(f?.name||""),y=Ir(f?.to?.name||""),_=b.length>=2&&(b.includes(h)||h.includes(b)),g=y.length>=2&&(y.includes(h)||h.includes(y));return _||g}))}if(!m){let h=p.map(_=>{let g=xt(a,_?.name||""),k=xt(a,_?.to?.name||"");return{t:_,score:Math.max(g,k)}}).sort((_,g)=>g.score-_.score),f=h[0],b=h[1];f&&f.score>=.45&&(!b||f.score-b.score>=.12)&&(m=f.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:e,availableTransitions:p.map(h=>({id:h.id,name:h.name,to:h.to?.name}))});c=m.id}await L(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let l=await L(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:l?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as cc}from"fs";import{fileURLToPath as lc}from"url";import{dirname as dc,resolve as pc}from"path";import{resolveIntegrationToken as Mn}from"@zibby/core/backend-client.js";import{spawn as za,execSync as Wa}from"child_process";import{existsSync as ee,mkdirSync as Za,readdirSync as Bn,statSync as Va,readFileSync as Xa}from"fs";import{resolve as Tr,join as te,basename as Qa}from"path";var Or=".zibby/repos";function Cn(r,t){try{let e=new URL(r);return e.protocol==="https:"&&e.host.toLowerCase()===t.toLowerCase()}catch{return!1}}function Un(r,t,e){let n=new URL(r);return n.username=encodeURIComponent(t),n.password=encodeURIComponent(e),n.toString()}function ec(r){let t=String(r??"");for(let e of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])e&&(t=t.split(e).join("***"));return t.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,e=>e.replace(/:[^@\s]+@/,":***@"))}function rt(r,t,e,n,s="clone"){try{r(`git -C "${t}" remote set-url origin "${e}"`,{stdio:"pipe"})}catch(i){let o=String(i?.message||i);n&&(o=o.split(n).join("***")),console.error(`[${s}] WARNING: failed to strip token from .git/config: ${o}`)}}function Lt(r,t,e={}){return new Promise((n,s)=>{let i=za(r,{cwd:t,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),o="",a="";i.stdout.on("data",c=>{o+=c.toString()}),i.stderr.on("data",c=>{a+=c.toString()}),i.on("close",c=>{c!==0?s(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),i.on("error",c=>s(c))})}var be={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],inProcessOnly:!0,promptFragment:`## Git Repositories
|
|
77
|
+
6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=Xc();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);process.env.ATLASSIAN_INSTANCE_URL&&(e.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let t of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[t]&&(e[t]=process.env[t]);return{command:"node",args:[r],env:e,description:this.description}},async handleToolCall(r,e){try{switch(r){case"jira_list_projects":{let t=await $("/rest/api/3/project"),n=(Array.isArray(t)?t:[]).map(s=>({id:s.id,key:s.key,name:s.name,style:s.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let i=await $(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(i)?i:[],a=new Map;for(let l of o)for(let d of l.statuses||[])d?.id&&(a.has(d.id)||a.set(d.id,{id:d.id,name:d.name,category:d.statusCategory?.name||null}));let c=[...a.values()].sort((l,d)=>String(l.name).localeCompare(String(d.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let n=await $("/rest/api/3/status"),s=(Array.isArray(n)?n:[]).map(i=>({id:i.id,name:i.name,category:i.statusCategory?.name||null})).sort((i,o)=>String(i.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:s.length,statuses:s})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let n=await ks(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 i=`jql=${encodeURIComponent(t)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await $(`/rest/api/3/search/jql?${i}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let n=await $(`/rest/api/3/issue/${t}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description?zr(n.fields.description):n.fields?.description??null,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:s,description:i,priority:o,labels:a,assigneeId:c,moveToSprint:l,moveToActiveSprint:d,sprintId:p,sprintName:u,target:m}=e;if(!t||!n)return JSON.stringify({error:"projectKey and summary are required"});let h={requested:s||null,resolved:null,strategy:"none"},y=[];try{y=await ks(t),h=el(s,y)}catch{}let _={project:{key:t},summary:n,issuetype:h?.resolved?.id?{id:h.resolved.id}:{name:s||"Task"}};o&&(_.priority={name:o}),a?.length&&(_.labels=a),c&&(_.assignee={id:c});let f=i?await Yr(g=>$("/rest/api/3/issue",{method:"POST",body:{fields:{..._,description:g}}}),i):await $("/rest/api/3/issue",{method:"POST",body:{fields:_}}),b={ok:!0,key:f.key,id:f.id,self:f.self};return h?.resolved&&(b.issueType=h.resolved.name,b.issueTypeResolution=h.strategy,h.strategy!=="exact"&&h.requested&&Ie(h.requested)!==Ie(h.resolved.name)&&(b.issueTypeWarning=`Requested "${h.requested}" is not available in ${t}; used "${h.resolved.name}" instead.`)),y.length>0&&(b.availableIssueTypes=y.map(g=>g.name)),(l||d)&&(b.sprintMove=await Zr({issueKey:f.key,projectKey:t,sprintId:p,sprintName:u,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,s=await ws(t,n);return JSON.stringify({count:s.length,sprints:s})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:n,sprintId:s,sprintName:i,target:o}=e||{},a=await Zr({issueKey:t,projectKey:n,sprintId:s,sprintName:i,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:n,sprintId:s,sprintName:i,target:o}=e||{},a=await Zr({issueKey:t,projectKey:n,sprintId:s,sprintName:i,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:n,projectKey:s,status:i,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}"`,l=s?`project = ${s} AND `:"",d=i?` AND status = "${i}"`:"",p=`${l}${c}${d} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await $(`/rest/api/3/search/jql?${u}`),h=(m.issues||[]).map(_=>({key:_.key,project:_.fields?.project?.key,summary:_.fields?.summary,status:_.fields?.status?.name,assignee:_.fields?.assignee?.displayName||"Unassigned",priority:_.fields?.priority?.name,type:_.fields?.issuetype?.name})),y={};for(let _ of h)y[_.status]=(y[_.status]||0)+1;return JSON.stringify({count:h.length,total:m.total||h.length,statusCounts:y,issues:h})}case"jira_get_comments":{let{issueKey:t,maxResults:n}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let i=await $(`/rest/api/3/issue/${t}/comment?maxResults=${n||50}&orderBy=-created`),o=(i.comments||[]).map(a=>{let c=a.body?.content?zr(a.body):"";return{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:i.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:n}=e;return!t||!n?JSON.stringify({error:"issueKey and body are required"}):(await Yr(s=>$(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:s}}),n),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:n}=e;if(!t||!n)return JSON.stringify({error:"issueKey and fields are required"});if(typeof n.description=="string"){let{description:s,...i}=n;await Yr(o=>$(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:{...i,description:o}}}),s)}else await $(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:n}});return JSON.stringify({ok:!0,issueKey:t})}case"jira_transition_issue":{let{issueKey:t,transitionId:n,toStatus:s,statusName:i,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(s||i||o||"").trim();if(!n&&!a){let p=((await $(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:p})}let c=n;if(!c){let p=(await $(`/rest/api/3/issue/${t}/transitions`)).transitions||[],u=Ze(a),m=p.find(h=>Ze(h?.name||"")===u||Ze(h?.to?.name||"")===u);if(!m){let h=Wr(a);h.length>=2&&(m=p.find(y=>{let _=Wr(y?.name||""),f=Wr(y?.to?.name||""),b=_.length>=2&&(_.includes(h)||h.includes(_)),g=f.length>=2&&(f.includes(h)||h.includes(f));return b||g}))}if(!m){let h=p.map(b=>{let g=Yt(a,b?.name||""),k=Yt(a,b?.to?.name||"");return{t:b,score:Math.max(g,k)}}).sort((b,g)=>g.score-b.score),y=h[0],_=h[1];y&&y.score>=.45&&(!_||y.score-_.score>=.12)&&(m=y.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:p.map(h=>({id:h.id,name:h.name,to:h.to?.name}))});c=m.id}await $(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let l=await $(`/rest/api/3/issue/${t}?fields=status`);return JSON.stringify({ok:!0,issueKey:t,transitionId:c,statusAfter:l?.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. Markdown is rendered (headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes, > [!NOTE]/[!TIP]/[!WARNING]/[!CAUTION] panels)."},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. Markdown is rendered: headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes, > [!NOTE]/[!TIP]/[!WARNING]/[!CAUTION] panels."}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, description, story points, labels, priority). A string `description` is Markdown and is rendered.",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 kl}from"fs";import{fileURLToPath as wl}from"url";import{dirname as Sl,resolve as vl}from"path";import{resolveIntegrationToken as As}from"@zibby/core/backend-client.js";import{spawn as ol,execSync as al}from"child_process";import{existsSync as ie,mkdirSync as cl,readdirSync as Ts,statSync as ll,readFileSync as dl}from"fs";import{resolve as Vr,join as oe,basename as pl}from"path";var Xr=".zibby/repos";function vs(r,e){try{let t=new URL(r);return t.protocol==="https:"&&t.host.toLowerCase()===e.toLowerCase()}catch{return!1}}function Is(r,e,t){let n=new URL(r);return n.username=encodeURIComponent(e),n.password=encodeURIComponent(t),n.toString()}function ul(r){let e=String(r??"");for(let t of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])t&&(e=e.split(t).join("***"));return e.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,t=>t.replace(/:[^@\s]+@/,":***@"))}function ft(r,e,t,n,s="clone"){try{r(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(i){let o=String(i?.message||i);n&&(o=o.split(n).join("***")),console.error(`[${s}] WARNING: failed to strip token from .git/config: ${o}`)}}function Wt(r,e,t={}){return new Promise((n,s)=>{let i=ol(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";i.stdout.on("data",c=>{o+=c.toString()}),i.stderr.on("data",c=>{a+=c.toString()}),i.on("close",c=>{c!==0?s(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),i.on("error",c=>s(c))})}var Te={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],inProcessOnly:!0,promptFragment:`## Git Repositories
|
|
75
78
|
You can clone and explore git repositories locally for codebase analysis:
|
|
76
79
|
- git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
|
|
77
80
|
- git_list_repos: List locally cloned repos
|
|
@@ -81,11 +84,11 @@ When your task needs repository context you don't have yet:
|
|
|
81
84
|
1. Clone the relevant repo with git_checkout
|
|
82
85
|
2. Use git_explore to understand the project structure
|
|
83
86
|
3. Use shell commands (grep, cat) to read specific files for deeper understanding
|
|
84
|
-
4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(r,t
|
|
87
|
+
4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await ml(e,n);case"git_list_repos":return hl(e,n);case"git_explore":return fl(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(s){return JSON.stringify({error:ul(s.message)})}},tools:[{name:"git_checkout",description:"Clone a git repository locally (or pull latest if already cloned). Auto-authenticates with GitHub/GitLab tokens if available.",input_schema:{type:"object",properties:{url:{type:"string",description:'Repository URL (e.g. "https://github.com/org/repo" or "org/repo" shorthand for GitHub)'},branch:{type:"string",description:"Branch to checkout (default: repo default branch)"},shallow:{type:"boolean",description:"Shallow clone with depth 1 (default: true, faster)"},name:{type:"string",description:"Local directory name override (default: repo name from URL)"}},required:["url"]}},{name:"git_list_repos",description:"List locally cloned repositories",input_schema:{type:"object",properties:{}}},{name:"git_explore",description:"Quick structural overview of a cloned repo: key files, package.json info, directory tree (top 2 levels), detected framework/language",input_schema:{type:"object",properties:{repo:{type:"string",description:"Repo name (as listed by git_list_repos)"},depth:{type:"number",description:"Directory tree depth (default: 2)"}},required:["repo"]}}]};async function ml(r,e){let{url:t,branch:n,shallow:s=!0,name:i}=r;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=i||pl(t.replace(/\.git$/,"")),a=Vr(e,Xr);cl(a,{recursive:!0});let c=oe(a,o),l=t,d=process.env.GITHUB_TOKEN,p=process.env.GITLAB_TOKEN,u=process.env.GITLAB_URL;if(vs(t,"github.com")&&d)l=Is(t,"x-access-token",d);else if(p&&u)try{let y=new URL(u).host;vs(t,y)&&(l=Is(t,"oauth2",p))}catch{}if(ie(oe(c,".git"))){let y=n?`git -C "${c}" fetch "${l}" ${n} && git -C "${c}" checkout ${n} && git -C "${c}" merge --ff-only FETCH_HEAD`:`git -C "${c}" pull "${l}"`;await Wt(y,e);let _=await Wt(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:n||"default",head:_})}let m=["git","clone"];s&&m.push("--depth","1"),n&&m.push("--branch",n),m.push(`"${l}"`,`"${c}"`),await Wt(m.join(" "),e),ft(al,c,t,d||p,"git_checkout");let h=await Wt(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:n||"default",shallow:s,head:h})}function hl(r,e){let t=Vr(e,Xr);if(!ie(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let s of Ts(t,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=oe(t,s.name);if(!ie(oe(i,".git")))continue;let o=ll(i);n.push({name:s.name,path:i,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:t})}function fl(r,e){let{repo:t,depth:n=2}=r,s=Vr(e,Xr,t);if(!ie(s))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let i={repo:t,path:s},o=oe(s,"package.json");if(ie(o))try{let m=JSON.parse(dl(o,"utf-8"));i.packageJson={name:m.name,version:m.version,scripts:m.scripts?Object.keys(m.scripts):[],dependencies:m.dependencies?Object.keys(m.dependencies).slice(0,30):[],devDependencies:m.devDependencies?Object.keys(m.devDependencies).slice(0,20):[]},m.dependencies?.react?i.framework="React":m.dependencies?.next?i.framework="Next.js":m.dependencies?.vue?i.framework="Vue":m.dependencies?.angular?i.framework="Angular":m.dependencies?.express?i.framework="Express":m.dependencies?.fastify&&(i.framework="Fastify")}catch{}let a=oe(s,"pyproject.toml");ie(a)&&(i.language="Python");let c=oe(s,"go.mod");ie(c)&&(i.language="Go");let l=oe(s,"Cargo.toml");ie(l)&&(i.language="Rust"),ie(o)&&(i.language=i.language||"JavaScript/TypeScript");let d=[];function p(m,h,y){if(y>n)return;let _;try{_=Ts(m,{withFileTypes:!0})}catch{return}let f=_.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 f){let g=b.isDirectory();d.push(`${h}${g?"\u{1F4C1}":"\u{1F4C4}"} ${b.name}`),g&&y<n&&p(oe(m,b.name),`${h} `,y+1)}}p(s,"",1),i.tree=d.slice(0,80),d.length>80&&(i.treeTruncated=!0);let u=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return i.keyFilesFound=u.filter(m=>ie(oe(s,m))),JSON.stringify(i)}import yl from"crypto";var Ns=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,Os=/<!--\s*zbreview-summary\s*-->/i;function gl(r){return String(r||"").replace(Ns,"").replace(Os,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function bl(r,e){return yl.createHash("sha256").update(`${String(r||"")}\0${gl(e)}`).digest("hex").slice(0,12)}function _l(r){return`
|
|
85
88
|
|
|
86
|
-
<!-- zbfp:${r} -->`}var
|
|
89
|
+
<!-- zbfp:${r} -->`}var Zt=`
|
|
87
90
|
|
|
88
|
-
<!-- zbreview-summary -->`;function
|
|
91
|
+
<!-- zbreview-summary -->`;function Vt(r){let e=Ns.exec(String(r||""));return e?e[1].toLowerCase():null}function Xt(r){return Os.test(String(r||""))}function Qt(r,e){let t=new Set([...e||[]].map(i=>String(i).toLowerCase())),n=[],s=0;for(let i of Array.isArray(r)?r:[]){if(!i||!i.body)continue;let o=bl(i.path,i.body);if(t.has(o)){s+=1;continue}t.add(o),n.push({...i,_fp:o,body:`${String(i.body)}${_l(o)}`})}return{toPost:n,skipped:s}}function Il(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Sl(wl(import.meta.url)),e=vl(r,"..","bin","mcp-skill.mjs");return kl(e)?e:null}async function O(r,e={}){let{token:t}=await As("github"),n=r.startsWith("https://")?r:`https://api.github.com${r}`,s={Authorization:`Bearer ${t}`,Accept:e.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...e.body?{"Content-Type":"application/json"}:{}},i=await w(n,{method:e.method||"GET",headers:s,body:e.body?JSON.stringify(e.body):void 0},{kind:"api",what:`GitHub ${e.method||"GET"} ${r}`});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`GitHub API ${i.status}: ${o.slice(0,300)}`)}return e.raw?i.text():i.json()}var Ve={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:I.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
|
|
89
92
|
You have access to the user's GitHub repositories. Available tools:
|
|
90
93
|
|
|
91
94
|
### Discovery
|
|
@@ -128,11 +131,11 @@ When user says "check out repo-name" or "clone repo-name":
|
|
|
128
131
|
3. STOP. Do not offer to inspect files or ask what to do next.
|
|
129
132
|
|
|
130
133
|
When user just wants to "look at" or "read" files (not clone):
|
|
131
|
-
- Use github_get_file to read individual files via API`,resolve(){let r=uc();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/github.js","githubSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"github_search_issues":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let n=await N(`/search/issues?q=${encodeURIComponent(e)}&per_page=${t.limit||20}`),s=(n.items||[]).map(i=>({number:i.number,title:i.title,state:i.state,repo:i.repository_url?.split("/").slice(-2).join("/"),url:i.html_url,user:i.user?.login,isPR:!!i.pull_request,labels:(i.labels||[]).map(o=>o.name),createdAt:i.created_at}));return JSON.stringify({total:n.total_count,items:s})}case"github_search_code":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let n=t.repo?`+repo:${t.repo}`:"",s=t.language?`+language:${t.language}`:"",i=await N(`/search/code?q=${encodeURIComponent(e)}${n}${s}&per_page=${t.limit||15}`),o=(i.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:i.total_count,items:o})}case"github_get_pr":{let{owner:e,repo:n,number:s}=t;if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await N(`/repos/${e}/${n}/pulls/${s}`);return JSON.stringify({number:i.number,title:i.title,state:i.state,merged:i.merged,body:i.body?.slice(0,5e3),user:i.user?.login,branch:i.head?.ref,headSha:i.head?.sha,base:i.base?.ref,changedFiles:i.changed_files,additions:i.additions,deletions:i.deletions,createdAt:i.created_at,mergedAt:i.merged_at,url:i.html_url,labels:(i.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:e,repo:n,number:s}=t;if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await N(`/repos/${e}/${n}/pulls/${s}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=i.length>15e3;return JSON.stringify({number:s,diff:o?i.slice(0,15e3):i,truncated:o,totalLength:i.length})}case"github_list_pr_files":{let{owner:e,repo:n,number:s}=t;if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await N(`/repos/${e}/${n}/pulls/${s}/files?per_page=100`);return JSON.stringify({total:i.length,files:i.map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:e,repo:n,number:s}=t;if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await N(`/repos/${e}/${n}/pulls/${s}/comments?per_page=50`),o=await N(`/repos/${e}/${n}/issues/${s}/comments?per_page=50`),a=[...i.map(c=>({type:"review",user:c.user?.login,body:c.body?.slice(0,1e3),path:c.path,line:c.line,createdAt:c.created_at})),...o.map(c=>({type:"issue",user:c.user?.login,body:c.body?.slice(0,1e3),createdAt:c.created_at}))].sort((c,l)=>new Date(c.createdAt)-new Date(l.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:n,number:s,commentId:i}=t||{};if(!e||!n||!s||!i)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await N(`/repos/${e}/${n}/pulls/comments/${i}`),a=o.in_reply_to_id||o.id,c=[];try{c=await N(`/repos/${e}/${n}/pulls/${s}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let l=c.filter(u=>u.id===a||u.in_reply_to_id===a).sort((u,m)=>new Date(u.created_at)-new Date(m.created_at)),d=l.length?l:[o],p=d.find(u=>u.id===a)||d[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:d.map(u=>({id:u.id,user:u.user?.login,body:(u.body||"").slice(0,4e3),createdAt:u.created_at,isRoot:u.id===a,url:u.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:n,number:s,commentId:i,body:o}=t||{};if(!e||!n||!s||!i||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await N(`/repos/${e}/${n}/pulls/${s}/comments/${i}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:e,repo:n,number:s,body:i}=t||{};if(!e||!n||!s||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${e}/${n}/issues/${s}/comments`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:e,repo:n,number:s,body:i,event:o,comments:a}=t||{};if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let c=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(c))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let l=Array.isArray(a)?a.filter(_=>_&&_.path&&_.body&&(_.line!=null||_.position!=null)).map(_=>{let g={path:_.path,body:String(_.body)};return _.line!=null?(g.line=Number(_.line),g.side=_.side==="LEFT"?"LEFT":"RIGHT"):g.position=Number(_.position),g}):[];if(c!=="APPROVE"&&!i&&l.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let d=new Set,p=null;try{for(let _=1;_<=20;_+=1){let g=await N(`/repos/${e}/${n}/pulls/${s}/comments?per_page=100&page=${_}`);if(!Array.isArray(g)||g.length===0)break;for(let k of g){let T=$t(k.body);T&&d.add(T)}if(g.length<100)break}for(let _=1;_<=20&&p==null;_+=1){let g=await N(`/repos/${e}/${n}/issues/${s}/comments?per_page=100&page=${_}`);if(!Array.isArray(g)||g.length===0)break;for(let k of g)if(Pt(k.body)){p=k.id;break}if(g.length<100)break}}catch{}let u=!1,m=!1;if(i){let _=`${String(i)}${jt}`;try{p!=null?(await N(`/repos/${e}/${n}/issues/comments/${p}`,{method:"PATCH",body:{body:_}}),u=!0):await N(`/repos/${e}/${n}/issues/${s}/comments`,{method:"POST",body:{body:_}}),m=!0}catch{}}let{toPost:h,skipped:f}=Ct(l,d),b=h.map(({_fp:_,...g})=>g),y=null;if(b.length>0||c==="APPROVE"||c==="REQUEST_CHANGES"){let _={event:c};b.length>0&&(_.comments=b),b.length===0&&c==="REQUEST_CHANGES"&&(_.body="Changes requested \u2014 see the review summary comment."),y=await N(`/repos/${e}/${n}/pulls/${s}/reviews`,{method:"POST",body:_})}return JSON.stringify({ok:!0,id:y?y.id:void 0,state:y?y.state:void 0,event:c,notePosted:m,summaryUpdated:u,commentsPosted:b.length,inlineSkipped:f||void 0,url:y?y.html_url:void 0})}case"github_list_commits":{let{owner:e,repo:n,branch:s,path:i,limit:o,since:a,until:c,page:l}=t;if(!e||!n)return JSON.stringify({error:"owner and repo are required"});let d=Math.min(Number(o)||20,100),p=`/repos/${e}/${n}/commits?per_page=${d}&page=${Number(l)||1}`;s&&(p+=`&sha=${encodeURIComponent(s)}`),i&&(p+=`&path=${encodeURIComponent(i)}`),a&&(p+=`&since=${encodeURIComponent(a)}`),c&&(p+=`&until=${encodeURIComponent(c)}`);let u=await N(p);return JSON.stringify({total:u.length,page:Number(l)||1,hasMore:u.length>=d,commits:u.map(m=>({sha:m.sha?.slice(0,8),fullSha:m.sha,message:m.commit?.message?.slice(0,300),author:m.commit?.author?.name,authorEmail:m.commit?.author?.email,date:m.commit?.author?.date,url:m.html_url}))})}case"github_get_commit":{let{owner:e,repo:n,sha:s,includePrs:i}=t;if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and sha are required"});let o=await N(`/repos/${e}/${n}/commits/${s}`),a;if(i)try{let c=await N(`/repos/${e}/${n}/commits/${s}/pulls`);a=(Array.isArray(c)?c:[]).map(l=>({number:l.number,title:l.title,state:l.state,merged:!!l.merged_at,webUrl:l.html_url}))}catch{a=[]}return JSON.stringify({sha:o.sha?.slice(0,8),message:o.commit?.message,author:o.commit?.author?.name,date:o.commit?.author?.date,stats:o.stats,files:(o.files||[]).map(c=>({filename:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:e,repo:n,path:s,ref:i}=t;if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${n}/contents/${encodeURIComponent(s)}`;i&&(o+=`?ref=${encodeURIComponent(i)}`);let a=await N(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:s,entries:a.map(d=>({name:d.name,type:d.type,size:d.size,path:d.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),l=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:l?c.slice(0,2e4):c,truncated:l})}case"github_get_user":try{let e=await N("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let n=e.repositories[0],s=n.owner.login,i=n.owner.type,o=i==="Organization"?`/orgs/${s}`:`/users/${s}`,a=await N(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:i,isOrg:i==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(e){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${e.message})`})}case"github_list_orgs":try{let n=(await N("/installation/repositories?per_page=100")).repositories||[],s=new Map;for(let o of n)o.owner.type==="Organization"&&(s.has(o.owner.login)||s.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let i=Array.from(s.values());return JSON.stringify({count:i.length,orgs:i,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(e){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${e.message}`})}case"github_clone":{let h=function(_){let g=_.replace(/^~(?=$|\/|\\)/,m);return a(g)},{owner:e,repo:n,destination:s}=t;if(!e||!n)return JSON.stringify({error:"owner and repo are required"});let{execSync:i}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:l}=await import("fs"),{homedir:d,platform:p}=await import("os"),{token:u}=await Mn("github"),m=d(),f=s?h(s):o(m,"zibby-repos"),b=o(f,n);if(l(f,{recursive:!0}),c(b))return JSON.stringify({error:`Directory ${b} already exists. Remove it first or use a different destination.`,existingPath:b});let y=`https://x-access-token:${u}@github.com/${e}/${n}.git`;try{i(`git clone ${y} "${b}"`,{stdio:"pipe"});let _=`https://github.com/${e}/${n}.git`;rt(i,b,_,u,"github_clone");let g=p()==="win32",k;return g?k=i(`dir "${b}"`,{encoding:"utf-8",shell:"cmd.exe"}):k=i(`ls -la "${b}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:b,message:`Cloned ${e}/${n} to ${b}`,contents:k.split(`
|
|
134
|
+
- Use github_get_file to read individual files via API`,resolve(){let r=Il();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/github.js","githubSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"github_search_issues":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let n=await O(`/search/issues?q=${encodeURIComponent(t)}&per_page=${e.limit||20}`),s=(n.items||[]).map(i=>({number:i.number,title:i.title,state:i.state,repo:i.repository_url?.split("/").slice(-2).join("/"),url:i.html_url,user:i.user?.login,isPR:!!i.pull_request,labels:(i.labels||[]).map(o=>o.name),createdAt:i.created_at}));return JSON.stringify({total:n.total_count,items:s})}case"github_search_code":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let n=e.repo?`+repo:${e.repo}`:"",s=e.language?`+language:${e.language}`:"",i=await O(`/search/code?q=${encodeURIComponent(t)}${n}${s}&per_page=${e.limit||15}`),o=(i.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:i.total_count,items:o})}case"github_get_pr":{let{owner:t,repo:n,number:s}=e;if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await O(`/repos/${t}/${n}/pulls/${s}`);return JSON.stringify({number:i.number,title:i.title,state:i.state,merged:i.merged,body:i.body?.slice(0,5e3),user:i.user?.login,branch:i.head?.ref,headSha:i.head?.sha,base:i.base?.ref,changedFiles:i.changed_files,additions:i.additions,deletions:i.deletions,createdAt:i.created_at,mergedAt:i.merged_at,url:i.html_url,labels:(i.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:t,repo:n,number:s}=e;if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await O(`/repos/${t}/${n}/pulls/${s}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=i.length>15e3;return JSON.stringify({number:s,diff:o?i.slice(0,15e3):i,truncated:o,totalLength:i.length})}case"github_list_pr_files":{let{owner:t,repo:n,number:s}=e;if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await O(`/repos/${t}/${n}/pulls/${s}/files?per_page=100`);return JSON.stringify({total:i.length,files:i.map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:n,number:s}=e;if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await O(`/repos/${t}/${n}/pulls/${s}/comments?per_page=50`),o=await O(`/repos/${t}/${n}/issues/${s}/comments?per_page=50`),a=[...i.map(c=>({type:"review",user:c.user?.login,body:c.body?.slice(0,1e3),path:c.path,line:c.line,createdAt:c.created_at})),...o.map(c=>({type:"issue",user:c.user?.login,body:c.body?.slice(0,1e3),createdAt:c.created_at}))].sort((c,l)=>new Date(c.createdAt)-new Date(l.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:t,repo:n,number:s,commentId:i}=e||{};if(!t||!n||!s||!i)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await O(`/repos/${t}/${n}/pulls/comments/${i}`),a=o.in_reply_to_id||o.id,c=[];try{c=await O(`/repos/${t}/${n}/pulls/${s}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let l=c.filter(u=>u.id===a||u.in_reply_to_id===a).sort((u,m)=>new Date(u.created_at)-new Date(m.created_at)),d=l.length?l:[o],p=d.find(u=>u.id===a)||d[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:d.map(u=>({id:u.id,user:u.user?.login,body:(u.body||"").slice(0,4e3),createdAt:u.created_at,isRoot:u.id===a,url:u.html_url}))})}case"github_reply_review_thread":{let{owner:t,repo:n,number:s,commentId:i,body:o}=e||{};if(!t||!n||!s||!i||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await O(`/repos/${t}/${n}/pulls/${s}/comments/${i}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:t,repo:n,number:s,body:i}=e||{};if(!t||!n||!s||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await O(`/repos/${t}/${n}/issues/${s}/comments`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:t,repo:n,number:s,body:i,event:o,comments:a}=e||{};if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let c=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(c))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let l=Array.isArray(a)?a.filter(b=>b&&b.path&&b.body&&(b.line!=null||b.position!=null)).map(b=>{let g={path:b.path,body:String(b.body)};return b.line!=null?(g.line=Number(b.line),g.side=b.side==="LEFT"?"LEFT":"RIGHT"):g.position=Number(b.position),g}):[];if(c!=="APPROVE"&&!i&&l.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let d=new Set,p=null;try{for(let b=1;b<=20;b+=1){let g=await O(`/repos/${t}/${n}/pulls/${s}/comments?per_page=100&page=${b}`);if(!Array.isArray(g)||g.length===0)break;for(let k of g){let v=Vt(k.body);v&&d.add(v)}if(g.length<100)break}for(let b=1;b<=20&&p==null;b+=1){let g=await O(`/repos/${t}/${n}/issues/${s}/comments?per_page=100&page=${b}`);if(!Array.isArray(g)||g.length===0)break;for(let k of g)if(Xt(k.body)){p=k.id;break}if(g.length<100)break}}catch{}let u=!1,m=!1;if(i){let b=`${String(i)}${Zt}`;try{p!=null?(await O(`/repos/${t}/${n}/issues/comments/${p}`,{method:"PATCH",body:{body:b}}),u=!0):await O(`/repos/${t}/${n}/issues/${s}/comments`,{method:"POST",body:{body:b}}),m=!0}catch{}}let{toPost:h,skipped:y}=Qt(l,d),_=h.map(({_fp:b,...g})=>g),f=null;if(_.length>0||c==="APPROVE"||c==="REQUEST_CHANGES"){let b={event:c};_.length>0&&(b.comments=_),_.length===0&&c==="REQUEST_CHANGES"&&(b.body="Changes requested \u2014 see the review summary comment."),f=await O(`/repos/${t}/${n}/pulls/${s}/reviews`,{method:"POST",body:b})}return JSON.stringify({ok:!0,id:f?f.id:void 0,state:f?f.state:void 0,event:c,notePosted:m,summaryUpdated:u,commentsPosted:_.length,inlineSkipped:y||void 0,url:f?f.html_url:void 0})}case"github_list_commits":{let{owner:t,repo:n,branch:s,path:i,limit:o,since:a,until:c,page:l}=e;if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let d=Math.min(Number(o)||20,100),p=`/repos/${t}/${n}/commits?per_page=${d}&page=${Number(l)||1}`;s&&(p+=`&sha=${encodeURIComponent(s)}`),i&&(p+=`&path=${encodeURIComponent(i)}`),a&&(p+=`&since=${encodeURIComponent(a)}`),c&&(p+=`&until=${encodeURIComponent(c)}`);let u=await O(p);return JSON.stringify({total:u.length,page:Number(l)||1,hasMore:u.length>=d,commits:u.map(m=>({sha:m.sha?.slice(0,8),fullSha:m.sha,message:m.commit?.message?.slice(0,300),author:m.commit?.author?.name,authorEmail:m.commit?.author?.email,date:m.commit?.author?.date,url:m.html_url}))})}case"github_get_commit":{let{owner:t,repo:n,sha:s,includePrs:i}=e;if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and sha are required"});let o=await O(`/repos/${t}/${n}/commits/${s}`),a;if(i)try{let c=await O(`/repos/${t}/${n}/commits/${s}/pulls`);a=(Array.isArray(c)?c:[]).map(l=>({number:l.number,title:l.title,state:l.state,merged:!!l.merged_at,webUrl:l.html_url}))}catch{a=[]}return JSON.stringify({sha:o.sha?.slice(0,8),message:o.commit?.message,author:o.commit?.author?.name,date:o.commit?.author?.date,stats:o.stats,files:(o.files||[]).map(c=>({filename:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:t,repo:n,path:s,ref:i}=e;if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${t}/${n}/contents/${encodeURIComponent(s)}`;i&&(o+=`?ref=${encodeURIComponent(i)}`);let a=await O(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:s,entries:a.map(d=>({name:d.name,type:d.type,size:d.size,path:d.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),l=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:l?c.slice(0,2e4):c,truncated:l})}case"github_get_user":try{let t=await O("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let n=t.repositories[0],s=n.owner.login,i=n.owner.type,o=i==="Organization"?`/orgs/${s}`:`/users/${s}`,a=await O(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:i,isOrg:i==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(t){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${t.message})`})}case"github_list_orgs":try{let n=(await O("/installation/repositories?per_page=100")).repositories||[],s=new Map;for(let o of n)o.owner.type==="Organization"&&(s.has(o.owner.login)||s.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let i=Array.from(s.values());return JSON.stringify({count:i.length,orgs:i,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(t){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${t.message}`})}case"github_clone":{let h=function(b){let g=b.replace(/^~(?=$|\/|\\)/,m);return a(g)},{owner:t,repo:n,destination:s}=e;if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let{execSync:i}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:l}=await import("fs"),{homedir:d,platform:p}=await import("os"),{token:u}=await As("github"),m=d(),y=s?h(s):o(m,"zibby-repos"),_=o(y,n);if(l(y,{recursive:!0}),c(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});let f=`https://x-access-token:${u}@github.com/${t}/${n}.git`;try{i(`git clone ${f} "${_}"`,{stdio:"pipe"});let b=`https://github.com/${t}/${n}.git`;ft(i,_,b,u,"github_clone");let g=p()==="win32",k;return g?k=i(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):k=i(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${t}/${n} to ${_}`,contents:k.split(`
|
|
132
135
|
`).slice(0,30).join(`
|
|
133
|
-
`),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(_){let k=String(_.message||_).split(u).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${k}`})}}case"github_search_repos":{let{query:e,limit:n}=t;if(!e)return JSON.stringify({error:"query is required"});let s=await this.handleToolCall("github_list_repos",{limit:200},{}),i=JSON.parse(s);if(i.error)return JSON.stringify(i);let o=e.toLowerCase(),a=i.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:e,count:a.length,repos:a.slice(0,n||20)})}case"github_list_repos":{let{owner:e,type:n,sort:s,direction:i,limit:o,query:a}=t,c=100,l=o||200,d=[],p=g=>({name:g.name,fullName:g.full_name,private:g.private,description:g.description,language:g.language,defaultBranch:g.default_branch,updatedAt:g.updated_at,stars:g.stargazers_count,url:g.html_url,fullPath:g.full_name,webUrl:g.html_url,visibility:g.visibility||(g.private?"private":"public")}),u=g=>{if(!a)return!0;let k=String(a).toLowerCase();return g.name&&g.name.toLowerCase().includes(k)||g.fullName&&g.fullName.toLowerCase().includes(k)||g.description&&g.description.toLowerCase().includes(k)};if(!e){let g=1,k=!0;for(;k&&d.length<l;){let q=`/installation/repositories?per_page=${c}&page=${g}`,Ie=(await N(q)).repositories||[];if(Ie.length===0)break;d=d.concat(Ie),k=Ie.length===c,g++}let T=d.map(p).filter(u),M=T.slice(0,l),ye=T.length>M.length,O=M.filter(q=>q.private).length,R=M.filter(q=>!q.private).length;return JSON.stringify({count:M.length,repos:M,truncated:ye,privateCount:O,publicCount:R,message:`Found ${O} private and ${R} public repos`})}let m=await N(`/orgs/${e}`).then(()=>!0).catch(()=>!1),h=1,f=!0;for(;f&&d.length<l;){let g;m?g=`/orgs/${e}/repos?per_page=${c}&page=${h}&type=${n||"all"}&sort=${s||"updated"}&direction=${i||"desc"}`:g=`/users/${e}/repos?per_page=${c}&page=${h}&type=${n||"all"}&sort=${s||"updated"}&direction=${i||"desc"}`;let k=await N(g),T=Array.isArray(k)?k:[];if(T.length===0)break;d=d.concat(T),f=T.length===c,h++}let b=d.map(p).filter(u),y=b.slice(0,l),_=b.length>y.length;return JSON.stringify({count:y.length,repos:y,truncated:_})}case"github_create_pr":{let{owner:e,repo:n,head:s,title:i}=t||{};if(!e||!n||!s||!i)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=t.base;if(!o)try{o=(await N(`/repos/${e}/${n}`)).default_branch||"main"}catch{o="main"}let a={title:String(i),head:String(s),base:String(o),body:t.body?String(t.body):"",draft:!!t.draft};try{let c=await N(`/repos/${e}/${n}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:s,base:o,repo:`${e}/${n}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let l=String(c.message||c);if(/GitHub API 422/.test(l))return JSON.stringify({success:!1,branch:s,base:o,repo:`${e}/${n}`,provider:"github",skippedReason:l});throw c}}case"github_merge_pr":{let{owner:e,repo:n,number:s}=t||{};if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=t.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(i))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${i})`});let o={merge_method:i};t.commitTitle&&(o.commit_title=String(t.commitTitle)),t.commitMessage&&(o.commit_message=String(t.commitMessage));try{let a=await N(`/repos/${e}/${n}/pulls/${s}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:s,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:s,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:e,repo:n,title:s,body:i}=t;if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and title are required"});let o=await N(`/repos/${e}/${n}/issues`,{method:"POST",body:{title:s,body:i||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:e,repo:n,state:s,labels:i,since:o,assignee:a,sort:c,direction:l,limit:d}=t||{};if(!e||!n)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",s||"open"),p.set("per_page",String(d||30)),p.set("sort",c||"updated"),p.set("direction",l||"desc"),i&&p.set("labels",Array.isArray(i)?i.join(","):i),o&&p.set("since",o),a&&p.set("assignee",a);let u=await N(`/repos/${e}/${n}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).filter(h=>!h.pull_request).map(h=>({number:h.number,title:h.title,state:h.state,labels:(h.labels||[]).map(f=>typeof f=="string"?f:f.name),assignee:h.assignee?.login||null,assignees:(h.assignees||[]).map(f=>f.login),user:h.user?.login,comments:h.comments,url:h.html_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:e,repo:n,number:s}=t||{};if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await N(`/repos/${e}/${n}/issues/${s}`);return i.pull_request?JSON.stringify({error:`#${s} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:i.number,title:i.title,body:i.body||"",state:i.state,stateReason:i.state_reason||null,labels:(i.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:i.assignee?.login||null,assignees:(i.assignees||[]).map(o=>o.login),user:i.user?.login,milestone:i.milestone?.title||null,comments:i.comments,url:i.html_url,createdAt:i.created_at,updatedAt:i.updated_at,closedAt:i.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:n,number:s,limit:i}=t||{};if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let o=await N(`/repos/${e}/${n}/issues/${s}/comments?per_page=${i||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:e,repo:n,number:s,body:i}=t||{};if(!e||!n||!s||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await N(`/repos/${e}/${n}/issues/${s}/comments`,{method:"POST",body:{body:i}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:e,repo:n,number:s,stateReason:i}=t||{};if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};i&&(o.state_reason=i);let a=await N(`/repos/${e}/${n}/issues/${s}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:e,repo:n,number:s}=t||{};if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await N(`/repos/${e}/${n}/issues/${s}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:i.number,state:i.state,url:i.html_url})}case"github_label_issue":{let{owner:e,repo:n,number:s,labels:i,mode:o}=t||{};if(!e||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(i)?i:i?[i]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let d=await N(`/repos/${e}/${n}/issues/${s}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await N(`/repos/${e}/${n}/issues/${s}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let d=await N(`/repos/${e}/${n}/issues/${s}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let l=await N(`/repos/${e}/${n}/issues/${s}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:s,labels:(Array.isArray(l)?l:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};import{existsSync as mc}from"fs";import{AsyncLocalStorage as hc}from"async_hooks";import{fileURLToPath as fc}from"url";import{dirname as yc,resolve as gc}from"path";function _c(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=yc(fc(import.meta.url)),t=gc(r,"..","bin","mcp-skill.mjs");return mc(t)?t:null}function nt(r){return String(r??"").trim().replace(/^\/+|\/+$/g,"").toLowerCase()}var Ut=null;function bc(r){let t;try{t=JSON.parse(r)}catch{throw new Error("GITLAB_INSTANCES is set but is not valid JSON. Expected an array of { host, token, repos: [...] }.")}if(!Array.isArray(t)||t.length===0)throw new Error("GITLAB_INSTANCES must be a non-empty JSON array of { host, token, repos: [...] }.");let e=[],n=new Map;return t.forEach((s,i)=>{let o=s&&typeof s.host=="string"?s.host.trim().replace(/\/+$/,""):"",a=s&&typeof s.token=="string"?s.token.trim():"",c=s&&Array.isArray(s.repos)?s.repos:null;if(!o)throw new Error(`GITLAB_INSTANCES[${i}] is missing "host".`);if(!a)throw new Error(`GITLAB_INSTANCES[${i}] (${o}) is missing "token".`);if(!c||c.length===0)throw new Error(`GITLAB_INSTANCES[${i}] (${o}) declares no "repos" \u2014 an entry that routes nothing is a config error, not an empty selection.`);let l=o.replace(/\/api\/v\d+$/,""),d=new Set;for(let p of c){let u=nt(p);if(!u)continue;let m=n.get(u);if(m!==void 0&&m!==i)throw new Error(`GITLAB_INSTANCES claims "${u}" on more than one server (${e[m].webHost} and ${l}). A repo path must name exactly one server.`);n.set(u,i),d.add(u)}if(d.size===0)throw new Error(`GITLAB_INSTANCES[${i}] (${o}) declares no usable "repos".`);e.push({webHost:l,apiBase:/\/api\/v\d+$/.test(o)?o:`${l}/api/v4`,token:a,repos:d})}),e}function Bt(){let r=process.env.GITLAB_INSTANCES;if(typeof r!="string"||!r.trim())return null;if(Ut&&Ut.raw===r)return Ut.value;let t=bc(r);return Ut={raw:r,value:t},t}var Dt=new hc,kc="GitLab: this call was not routed to a connected server. With GITLAB_INSTANCES set, every call must name a project one of the declared servers owns.";function Jt(){let r=Dt.getStore();if(r)return r;if(Bt())throw new Error(kc);return null}function qn(){let r=Jt();if(r)return r.apiBase;let t=process.env.GITLAB_API_URL;if(t)return t.replace(/\/+$/,"");let e=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(e)?e:`${e}/api/v4`}function wc(){let r=Jt();if(r)return{"PRIVATE-TOKEN":r.token};if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let t=process.env.GITLAB_TOKEN;if(!t)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":t}}async function A(r,t={}){let e=/^https?:\/\//.test(r)?r:`${qn()}${r}`,n={Accept:"application/json","User-Agent":"Zibby-App",...wc(),...t.body?{"Content-Type":"application/json"}:{}},s=await fetch(e,{method:t.method||"GET",headers:n,body:t.body?JSON.stringify(t.body):void 0});if(!s.ok){let i=await s.text().catch(()=>""),o=`GitLab API ${s.status} @ ${qn()}`;throw new Error(`${o}: ${i.slice(0,300)}`)}return t.raw?s.text():s.json()}function Fn(){let r=Jt();if(r)return r.webHost;let t=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(t?t.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Sc(){let r=Jt();return r?r.token:process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function j(r){let t=String(r);return/^\d+$/.test(t)?t:encodeURIComponent(t)}function Hn(){let r=Bt();if(r){let n=new Set;for(let s of r)for(let i of s.repos)n.add(i);return n}let t=process.env.GITLAB_ALLOWED_REPOS;if(typeof t!="string"||!t.trim())return null;let e=new Set(t.split(",").map(nt).filter(Boolean));return e.size?e:null}function Yn(r,t){if(!r)return!0;let e=nt(t);return e!==""&&r.has(e)}function vc(r){if(!r||typeof r!="object")return null;for(let t of["projectPath","projectId","project","repo","repoPath"]){let e=r[t];if(e!=null&&String(e).trim()!=="")return String(e).trim()}return null}async function Kn(r){if(!/^\d+$/.test(r))return r;try{let t=await A(`/projects/${j(r)}`);return t&&t.path_with_namespace||null}catch{return null}}async function Ic(r,t){if(!t)return{path:await Kn(r),instance:null};if(!/^\d+$/.test(r)){let n=nt(r);return{path:r,instance:t.find(s=>s.repos.has(n))||null}}let e=null;for(let n of t){let s=await Dt.run(n,()=>Kn(r));if(s&&(e===null&&(e=s),n.repos.has(nt(s))))return{path:s,instance:n}}return{path:e,instance:null}}async function Gn(r,t){switch(r){case"gitlab_clone":{let{projectPath:e,projectId:n,destination:s,branch:i}=t||{},o=e&&String(e).trim();if(!o&&n!=null&&(/^\d+$/.test(String(n))?o=(await A(`/projects/${j(n)}`))?.path_with_namespace:o=String(n).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=Sc();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:l,resolve:d}=await import("path"),{existsSync:p,mkdirSync:u}=await import("fs"),m=s?d(s):d(process.cwd(),".zibby","repos"),h=o.split("/").filter(Boolean).pop(),f=l(m,h);if(u(m,{recursive:!0}),p(f))return JSON.stringify({success:!0,path:f,message:`Already cloned at ${f}`,alreadyCloned:!0});let b=Fn().replace(/^https?:\/\//,""),y=Fn().startsWith("http://")?"http":"https",_=`${y}://oauth2:${a}@${b}/${o}.git`,g=i?`--branch "${String(i).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${g}${_} "${f}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let k=`${y}://${b}/${o}.git`;rt(c,f,k,a,"gitlab_clone");let T=c(`ls -la "${f}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:f,message:`Cloned ${o} to ${f}`,contents:T.split(`
|
|
136
|
+
`),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(b){let k=String(b.message||b).split(u).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${k}`})}}case"github_search_repos":{let{query:t,limit:n}=e;if(!t)return JSON.stringify({error:"query is required"});let s=await this.handleToolCall("github_list_repos",{limit:200},{}),i=JSON.parse(s);if(i.error)return JSON.stringify(i);let o=t.toLowerCase(),a=i.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:t,count:a.length,repos:a.slice(0,n||20)})}case"github_list_repos":{let{owner:t,type:n,sort:s,direction:i,limit:o,query:a}=e,c=100,l=o||200,d=[],p=g=>({name:g.name,fullName:g.full_name,private:g.private,description:g.description,language:g.language,defaultBranch:g.default_branch,updatedAt:g.updated_at,stars:g.stargazers_count,url:g.html_url,fullPath:g.full_name,webUrl:g.html_url,visibility:g.visibility||(g.private?"private":"public")}),u=g=>{if(!a)return!0;let k=String(a).toLowerCase();return g.name&&g.name.toLowerCase().includes(k)||g.fullName&&g.fullName.toLowerCase().includes(k)||g.description&&g.description.toLowerCase().includes(k)};if(!t){let g=1,k=!0;for(;k&&d.length<l;){let K=`/installation/repositories?per_page=${c}&page=${g}`,Ee=(await O(K)).repositories||[];if(Ee.length===0)break;d=d.concat(Ee),k=Ee.length===c,g++}let v=d.map(p).filter(u),x=v.slice(0,l),V=v.length>x.length,R=x.filter(K=>K.private).length,A=x.filter(K=>!K.private).length;return JSON.stringify({count:x.length,repos:x,truncated:V,privateCount:R,publicCount:A,message:`Found ${R} private and ${A} public repos`})}let m=await O(`/orgs/${t}`).then(()=>!0).catch(()=>!1),h=1,y=!0;for(;y&&d.length<l;){let g;m?g=`/orgs/${t}/repos?per_page=${c}&page=${h}&type=${n||"all"}&sort=${s||"updated"}&direction=${i||"desc"}`:g=`/users/${t}/repos?per_page=${c}&page=${h}&type=${n||"all"}&sort=${s||"updated"}&direction=${i||"desc"}`;let k=await O(g),v=Array.isArray(k)?k:[];if(v.length===0)break;d=d.concat(v),y=v.length===c,h++}let _=d.map(p).filter(u),f=_.slice(0,l),b=_.length>f.length;return JSON.stringify({count:f.length,repos:f,truncated:b})}case"github_create_pr":{let{owner:t,repo:n,head:s,title:i}=e||{};if(!t||!n||!s||!i)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=e.base;if(!o)try{o=(await O(`/repos/${t}/${n}`)).default_branch||"main"}catch{o="main"}let a={title:String(i),head:String(s),base:String(o),body:e.body?String(e.body):"",draft:!!e.draft};try{let c=await O(`/repos/${t}/${n}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:s,base:o,repo:`${t}/${n}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let l=String(c.message||c);if(/GitHub API 422/.test(l))return JSON.stringify({success:!1,branch:s,base:o,repo:`${t}/${n}`,provider:"github",skippedReason:l});throw c}}case"github_merge_pr":{let{owner:t,repo:n,number:s}=e||{};if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=e.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(i))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${i})`});let o={merge_method:i};e.commitTitle&&(o.commit_title=String(e.commitTitle)),e.commitMessage&&(o.commit_message=String(e.commitMessage));try{let a=await O(`/repos/${t}/${n}/pulls/${s}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:s,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:s,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:t,repo:n,title:s,body:i}=e;if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and title are required"});let o=await O(`/repos/${t}/${n}/issues`,{method:"POST",body:{title:s,body:i||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:t,repo:n,state:s,labels:i,since:o,assignee:a,sort:c,direction:l,limit:d}=e||{};if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",s||"open"),p.set("per_page",String(d||30)),p.set("sort",c||"updated"),p.set("direction",l||"desc"),i&&p.set("labels",Array.isArray(i)?i.join(","):i),o&&p.set("since",o),a&&p.set("assignee",a);let u=await O(`/repos/${t}/${n}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).filter(h=>!h.pull_request).map(h=>({number:h.number,title:h.title,state:h.state,labels:(h.labels||[]).map(y=>typeof y=="string"?y:y.name),assignee:h.assignee?.login||null,assignees:(h.assignees||[]).map(y=>y.login),user:h.user?.login,comments:h.comments,url:h.html_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:t,repo:n,number:s}=e||{};if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await O(`/repos/${t}/${n}/issues/${s}`);return i.pull_request?JSON.stringify({error:`#${s} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:i.number,title:i.title,body:i.body||"",state:i.state,stateReason:i.state_reason||null,labels:(i.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:i.assignee?.login||null,assignees:(i.assignees||[]).map(o=>o.login),user:i.user?.login,milestone:i.milestone?.title||null,comments:i.comments,url:i.html_url,createdAt:i.created_at,updatedAt:i.updated_at,closedAt:i.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:n,number:s,limit:i}=e||{};if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let o=await O(`/repos/${t}/${n}/issues/${s}/comments?per_page=${i||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:t,repo:n,number:s,body:i}=e||{};if(!t||!n||!s||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await O(`/repos/${t}/${n}/issues/${s}/comments`,{method:"POST",body:{body:i}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:t,repo:n,number:s,stateReason:i}=e||{};if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};i&&(o.state_reason=i);let a=await O(`/repos/${t}/${n}/issues/${s}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:t,repo:n,number:s}=e||{};if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let i=await O(`/repos/${t}/${n}/issues/${s}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:i.number,state:i.state,url:i.html_url})}case"github_label_issue":{let{owner:t,repo:n,number:s,labels:i,mode:o}=e||{};if(!t||!n||!s)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(i)?i:i?[i]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let d=await O(`/repos/${t}/${n}/issues/${s}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await O(`/repos/${t}/${n}/issues/${s}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let d=await O(`/repos/${t}/${n}/issues/${s}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let l=await O(`/repos/${t}/${n}/issues/${s}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:s,labels:(Array.isArray(l)?l:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};import{existsSync as Tl}from"fs";import{AsyncLocalStorage as Nl}from"async_hooks";import{fileURLToPath as Ol}from"url";import{dirname as Al,resolve as Rl}from"path";function El(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Al(Ol(import.meta.url)),e=Rl(r,"..","bin","mcp-skill.mjs");return Tl(e)?e:null}function yt(r){return String(r??"").trim().replace(/^\/+|\/+$/g,"").toLowerCase()}var er=null;function xl(r){let e;try{e=JSON.parse(r)}catch{throw new Error("GITLAB_INSTANCES is set but is not valid JSON. Expected an array of { host, token, repos: [...] }.")}if(!Array.isArray(e)||e.length===0)throw new Error("GITLAB_INSTANCES must be a non-empty JSON array of { host, token, repos: [...] }.");let t=[],n=new Map;return e.forEach((s,i)=>{let o=s&&typeof s.host=="string"?s.host.trim().replace(/\/+$/,""):"",a=s&&typeof s.token=="string"?s.token.trim():"",c=s&&Array.isArray(s.repos)?s.repos:null;if(!o)throw new Error(`GITLAB_INSTANCES[${i}] is missing "host".`);if(!a)throw new Error(`GITLAB_INSTANCES[${i}] (${o}) is missing "token".`);if(!c||c.length===0)throw new Error(`GITLAB_INSTANCES[${i}] (${o}) declares no "repos" \u2014 an entry that routes nothing is a config error, not an empty selection.`);let l=o.replace(/\/api\/v\d+$/,""),d=new Set;for(let p of c){let u=yt(p);if(!u)continue;let m=n.get(u);if(m!==void 0&&m!==i)throw new Error(`GITLAB_INSTANCES claims "${u}" on more than one server (${t[m].webHost} and ${l}). A repo path must name exactly one server.`);n.set(u,i),d.add(u)}if(d.size===0)throw new Error(`GITLAB_INSTANCES[${i}] (${o}) declares no usable "repos".`);t.push({webHost:l,apiBase:/\/api\/v\d+$/.test(o)?o:`${l}/api/v4`,token:a,repos:d})}),t}function tr(){let r=process.env.GITLAB_INSTANCES;if(typeof r!="string"||!r.trim())return null;if(er&&er.raw===r)return er.value;let e=xl(r);return er={raw:r,value:e},e}var rr=new Nl,Ll="GitLab: this call was not routed to a connected server. With GITLAB_INSTANCES set, every call must name a project one of the declared servers owns.";function nr(){let r=rr.getStore();if(r)return r;if(tr())throw new Error(Ll);return null}function Rs(){let r=nr();if(r)return r.apiBase;let e=process.env.GITLAB_API_URL;if(e)return e.replace(/\/+$/,"");let t=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(t)?t:`${t}/api/v4`}function $l(){let r=nr();if(r)return{"PRIVATE-TOKEN":r.token};if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let e=process.env.GITLAB_TOKEN;if(!e)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":e}}async function E(r,e={}){let t=/^https?:\/\//.test(r)?r:`${Rs()}${r}`,n={Accept:"application/json","User-Agent":"Zibby-App",...$l(),...e.body?{"Content-Type":"application/json"}:{}},s=await w(t,{method:e.method||"GET",headers:n,body:e.body?JSON.stringify(e.body):void 0},{kind:"api",what:`GitLab ${e.method||"GET"} ${r}`});if(!s.ok){let i=await s.text().catch(()=>""),o=`GitLab API ${s.status} @ ${Rs()}`;throw new Error(`${o}: ${i.slice(0,300)}`)}return e.raw?s.text():s.json()}function Es(){let r=nr();if(r)return r.webHost;let e=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(e?e.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function jl(){let r=nr();return r?r.token:process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function P(r){let e=String(r);return/^\d+$/.test(e)?e:encodeURIComponent(e)}function $s(){let r=tr();if(r){let n=new Set;for(let s of r)for(let i of s.repos)n.add(i);return n}let e=process.env.GITLAB_ALLOWED_REPOS;if(typeof e!="string"||!e.trim())return null;let t=new Set(e.split(",").map(yt).filter(Boolean));return t.size?t:null}function js(r,e){if(!r)return!0;let t=yt(e);return t!==""&&r.has(t)}function Pl(r){if(!r||typeof r!="object")return null;for(let e of["projectPath","projectId","project","repo","repoPath"]){let t=r[e];if(t!=null&&String(t).trim()!=="")return String(t).trim()}return null}async function xs(r){if(!/^\d+$/.test(r))return r;try{let e=await E(`/projects/${P(r)}`);return e&&e.path_with_namespace||null}catch{return null}}async function Cl(r,e){if(!e)return{path:await xs(r),instance:null};if(!/^\d+$/.test(r)){let n=yt(r);return{path:r,instance:e.find(s=>s.repos.has(n))||null}}let t=null;for(let n of e){let s=await rr.run(n,()=>xs(r));if(s&&(t===null&&(t=s),n.repos.has(yt(s))))return{path:s,instance:n}}return{path:t,instance:null}}async function Ls(r,e){switch(r){case"gitlab_clone":{let{projectPath:t,projectId:n,destination:s,branch:i}=e||{},o=t&&String(t).trim();if(!o&&n!=null&&(/^\d+$/.test(String(n))?o=(await E(`/projects/${P(n)}`))?.path_with_namespace:o=String(n).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=jl();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:l,resolve:d}=await import("path"),{existsSync:p,mkdirSync:u}=await import("fs"),m=s?d(s):d(process.cwd(),".zibby","repos"),h=o.split("/").filter(Boolean).pop(),y=l(m,h);if(u(m,{recursive:!0}),p(y))return JSON.stringify({success:!0,path:y,message:`Already cloned at ${y}`,alreadyCloned:!0});let _=Es().replace(/^https?:\/\//,""),f=Es().startsWith("http://")?"http":"https",b=`${f}://oauth2:${a}@${_}/${o}.git`,g=i?`--branch "${String(i).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${g}${b} "${y}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let k=`${f}://${_}/${o}.git`;ft(c,y,k,a,"gitlab_clone");let v=c(`ls -la "${y}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:y,message:`Cloned ${o} to ${y}`,contents:v.split(`
|
|
134
137
|
`).slice(0,30).join(`
|
|
135
|
-
`)})}catch(k){let T=String(k.message||k).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${T}`})}}case"gitlab_create_mr":{let e=t?.project??t?.projectId,n=t?.source_branch??t?.sourceBranch,{title:s}=t||{};if(!e||!n||!s)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let i=j(e),o=t?.target_branch??t?.targetBranch;if(!o)try{o=(await A(`/projects/${i}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(n),target_branch:String(o),title:String(s),description:t?.description?String(t.description):""};try{let c=await A(`/projects/${i}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",state:c.state})}catch(c){let l=String(c.message||c);if(/GitLab API (409|400)/.test(l))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",skippedReason:l});throw c}}case"gitlab_accept_mr":{let e=t?.project??t?.projectId,{iid:n}=t||{};if(!e||!n)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let s=j(e),i={};t.squash!=null&&(i.squash=!!t.squash),t.mergeCommitMessage&&(i.merge_commit_message=String(t.mergeCommitMessage)),t.mergeWhenPipelineSucceeds!=null&&(i.merge_when_pipeline_succeeds=!!t.mergeWhenPipelineSucceeds);try{let o=await A(`/projects/${s}/merge_requests/${n}/merge`,{method:"PUT",body:i});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??n,project:String(e),provider:"gitlab",state:o.state})}catch(o){let a=String(o.message||o);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:n,project:String(e),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:e,iid:n}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await A(`/projects/${j(e)}/merge_requests/${n}`);return JSON.stringify({iid:s.iid,projectId:s.project_id,title:s.title,description:(s.description||"").slice(0,5e3),state:s.state,author:s.author?.username,sourceBranch:s.source_branch,targetBranch:s.target_branch,draft:s.draft??s.work_in_progress??!1,mergeStatus:s.merge_status,changesCount:s.changes_count,labels:Array.isArray(s.labels)?s.labels:[],webUrl:s.web_url,createdAt:s.created_at,updatedAt:s.updated_at,mergedAt:s.merged_at,diffRefs:s.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:e,iid:n}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await A(`/projects/${j(e)}/merge_requests/${n}/changes`),i=Array.isArray(s.changes)?s.changes:[];return JSON.stringify({iid:s.iid,total:i.length,diffRefs:s.diff_refs||null,files:i.map(o=>({oldPath:o.old_path,newPath:o.new_path,newFile:!!o.new_file,deletedFile:!!o.deleted_file,renamedFile:!!o.renamed_file,diff:typeof o.diff=="string"?o.diff.slice(0,3e3):""}))})}case"gitlab_list_commits":{let{projectId:e,since:n,until:s,refName:i,page:o,perPage:a,withStats:c}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let l=new URLSearchParams;l.set("per_page",String(Math.min(Number(a)||50,100))),l.set("page",String(Number(o)||1)),n&&l.set("since",n),s&&l.set("until",s),i&&l.set("ref_name",i),c!==!1&&l.set("with_stats","true");let d=await A(`/projects/${j(e)}/repository/commits?${l.toString()}`),p=(Array.isArray(d)?d:[]).map(u=>({id:u.id,shortId:u.short_id,title:u.title,authorName:u.author_name,authorEmail:u.author_email,authoredDate:u.authored_date,committedDate:u.committed_date,parentIds:Array.isArray(u.parent_ids)?u.parent_ids:[],stats:u.stats||null}));return JSON.stringify({page:Number(o)||1,count:p.length,hasMore:p.length>=Math.min(Number(a)||50,100),commits:p})}case"gitlab_get_commit":{let{projectId:e,sha:n,includeDiff:s,includeMrs:i}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and sha are required"});let o=await A(`/projects/${j(e)}/repository/commits/${encodeURIComponent(n)}`),a;if(i)try{let l=await A(`/projects/${j(e)}/repository/commits/${encodeURIComponent(n)}/merge_requests`);a=(Array.isArray(l)?l:[]).map(d=>({iid:d.iid,title:d.title,state:d.state,webUrl:d.web_url}))}catch{a=[]}let c;if(s!==!1){let l=await A(`/projects/${j(e)}/repository/commits/${encodeURIComponent(n)}/diff`);c=(Array.isArray(l)?l:[]).map(d=>({oldPath:d.old_path,newPath:d.new_path,newFile:!!d.new_file,deletedFile:!!d.deleted_file,renamedFile:!!d.renamed_file,diff:typeof d.diff=="string"?d.diff.slice(0,3e3):""}))}return JSON.stringify({id:o.id,shortId:o.short_id,title:o.title,message:typeof o.message=="string"?o.message.slice(0,2e3):"",authorName:o.author_name,authorEmail:o.author_email,authoredDate:o.authored_date,committedDate:o.committed_date,parentIds:Array.isArray(o.parent_ids)?o.parent_ids:[],stats:o.stats||null,webUrl:o.web_url,...c?{filesChanged:c.length,files:c}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:e,state:n,targetBranch:s,sourceBranch:i,authorUsername:o,labels:a,search:c,sort:l,orderBy:d,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||20)),u.set("order_by",d||"updated_at"),u.set("sort",l||"desc"),s&&u.set("target_branch",s),i&&u.set("source_branch",i),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await A(`/projects/${j(e)}/merge_requests?${u.toString()}`),h=(Array.isArray(m)?m:[]).map(f=>({iid:f.iid,title:f.title,state:f.state,author:f.author?.username,sourceBranch:f.source_branch,targetBranch:f.target_branch,draft:f.draft??f.work_in_progress??!1,labels:Array.isArray(f.labels)?f.labels:[],webUrl:f.web_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:h.length,mergeRequests:h})}case"gitlab_list_mr_notes":{let{projectId:e,iid:n,limit:s}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await A(`/projects/${j(e)}/merge_requests/${n}/notes?per_page=${s||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(i)?i.length:0,notes:(Array.isArray(i)?i:[]).map(o=>({id:o.id,author:o.author?.username,body:(o.body||"").slice(0,1e3),system:!!o.system,createdAt:o.created_at}))})}case"gitlab_post_mr_note":{let{projectId:e,iid:n,body:s}=t||{};if(!e||!n||!s)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await A(`/projects/${j(e)}/merge_requests/${n}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}case"gitlab_post_mr_discussion":{let{projectId:e,iid:n,path:s,oldPath:i,newLine:o,oldLine:a,body:c}=t||{};if(!e||!n||!s||!c)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(o==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let l=j(e),d=t.diffRefs||null;if(d||(d=(await A(`/projects/${l}/merge_requests/${n}`)).diff_refs||null),!d||!d.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let p={base_sha:d.base_sha,start_sha:d.start_sha,head_sha:d.head_sha,position_type:"text",new_path:s,old_path:i||s};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await A(`/projects/${l}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(c),position:p}});return JSON.stringify({ok:!0,discussionId:u.id})}catch(u){return JSON.stringify({ok:!1,error:`inline anchor rejected (${u.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:e,iid:n,body:s,comments:i}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let o=j(e),a=Array.isArray(i)?i.filter(y=>y&&y.path&&y.body&&(y.newLine!=null||y.oldLine!=null)):[];if(!s&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=t.diffRefs||null;a.length>0&&!c&&(c=(await A(`/projects/${o}/merge_requests/${n}`)).diff_refs||null);let l=new Set,d=null;try{for(let y=1;y<=20;y+=1){let _=await A(`/projects/${o}/merge_requests/${n}/discussions?per_page=100&page=${y}`);if(!Array.isArray(_)||_.length===0)break;for(let g of _)for(let k of g.notes||[]){let T=$t(k.body);T&&l.add(T),d==null&&Pt(k.body)&&(d=k.id)}if(_.length<100)break}}catch{}let p=!1,u=!1;if(s){let y=`${String(s)}${jt}`;try{d!=null?(await A(`/projects/${o}/merge_requests/${n}/notes/${d}`,{method:"PUT",body:{body:y}}),u=!0):await A(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:y}}),p=!0}catch{await A(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:y}}),p=!0}}let{toPost:m,skipped:h}=Ct(a,l),f=0,b=[];if(m.length>0&&c)for(let y of m){let _={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:y.path,old_path:y.oldPath||y.path};y.newLine!=null&&(_.new_line=Number(y.newLine)),y.oldLine!=null&&(_.old_line=Number(y.oldLine));try{await A(`/projects/${o}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(y.body),position:_}}),f+=1}catch(g){b.push(`${y.path}:${y.newLine??y.oldLine} \u2014 ${g.message}`)}}else m.length>0&&!c&&b.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:p,summaryUpdated:u,inlinePosted:f,inlineSkipped:h||void 0,inlineErrors:b.length?b:void 0})}case"gitlab_get_discussion":{let{projectId:e,iid:n,discussionId:s}=t||{};if(!e||!n||!s)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let i=await A(`/projects/${j(e)}/merge_requests/${n}/discussions/${encodeURIComponent(s)}`),o=Array.isArray(i.notes)?i.notes:[],a=o.find(l=>l.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:i.id,individualNote:!!i.individual_note,path:c&&(c.new_path||c.old_path)||null,newLine:c?c.new_line??null:null,oldLine:c?c.old_line??null:null,diffRefs:c?{base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha}:null,notes:o.map(l=>({id:l.id,author:l.author?.username,body:(l.body||"").slice(0,4e3),system:!!l.system,createdAt:l.created_at}))})}case"gitlab_reply_discussion":{let{projectId:e,iid:n,discussionId:s,body:i}=t||{};if(!e||!n||!s||!i)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await A(`/projects/${j(e)}/merge_requests/${n}/discussions/${encodeURIComponent(s)}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:e,limit:n}=t||{},s=Math.min(Number(n)>0?Number(n):50,200),i=new URLSearchParams;i.set("membership","true"),i.set("simple","true"),i.set("order_by","last_activity_at"),i.set("sort","desc"),i.set("per_page",String(Math.min(s+1,100))),e&&i.set("search",String(e));let o=async()=>{let u=await A(`/projects?${i.toString()}`);return Array.isArray(u)?u:[]},a=Bt(),c=Hn(),l=[];for(let u of a||[null]){let m=u?await Dt.run(u,o):await o();for(let h of m)Yn(u?u.repos:c,h&&h.path_with_namespace)&&l.push({p:h,host:u?u.webHost:null})}let d=l.length>s,p=l.slice(0,s).map(({p:u,host:m})=>({fullPath:u.path_with_namespace,name:u.name,webUrl:u.web_url,defaultBranch:u.default_branch||null,visibility:u.visibility||null,...m?{host:m}:{}}));return JSON.stringify({count:p.length,truncated:d,projects:p})}case"gitlab_list_issues":{let{projectId:e,state:n,labels:s,assigneeUsername:i,authorUsername:o,updatedAfter:a,search:c,sort:l,orderBy:d,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||30)),u.set("order_by",d||"updated_at"),u.set("sort",l||"desc"),s&&u.set("labels",Array.isArray(s)?s.join(","):s),i&&u.set("assignee_username",i),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await A(`/projects/${j(e)}/issues?${u.toString()}`),h=(Array.isArray(m)?m:[]).map(f=>({iid:f.iid,title:f.title,state:f.state,labels:Array.isArray(f.labels)?f.labels:[],author:f.author?.username,assignees:(f.assignees||[]).map(b=>b.username),userNotesCount:f.user_notes_count,webUrl:f.web_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:h.length,issues:h})}case"gitlab_get_issue":{let{projectId:e,iid:n}=t||{};if(!e||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await A(`/projects/${j(e)}/issues/${n}`);return JSON.stringify({iid:s.iid,projectId:s.project_id,title:s.title,description:(s.description||"").slice(0,5e3),state:s.state,labels:Array.isArray(s.labels)?s.labels:[],author:s.author?.username,assignees:(s.assignees||[]).map(i=>i.username),milestone:s.milestone?.title||null,webUrl:s.web_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"gitlab_add_issue_comment":{let{projectId:e,iid:n,body:s}=t||{};if(!e||!n||!s)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await A(`/projects/${j(e)}/issues/${n}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}var Je={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:S.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_URL","GITLAB_INSTANCE_URL","GITLAB_API_URL","GITLAB_ALLOWED_REPOS","GITLAB_INSTANCES","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
|
|
138
|
+
`)})}catch(k){let v=String(k.message||k).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${v}`})}}case"gitlab_create_mr":{let t=e?.project??e?.projectId,n=e?.source_branch??e?.sourceBranch,{title:s}=e||{};if(!t||!n||!s)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let i=P(t),o=e?.target_branch??e?.targetBranch;if(!o)try{o=(await E(`/projects/${i}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(n),target_branch:String(o),title:String(s),description:e?.description?String(e.description):""};try{let c=await E(`/projects/${i}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(t),provider:"gitlab",state:c.state})}catch(c){let l=String(c.message||c);if(/GitLab API (409|400)/.test(l))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(t),provider:"gitlab",skippedReason:l});throw c}}case"gitlab_accept_mr":{let t=e?.project??e?.projectId,{iid:n}=e||{};if(!t||!n)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let s=P(t),i={};e.squash!=null&&(i.squash=!!e.squash),e.mergeCommitMessage&&(i.merge_commit_message=String(e.mergeCommitMessage)),e.mergeWhenPipelineSucceeds!=null&&(i.merge_when_pipeline_succeeds=!!e.mergeWhenPipelineSucceeds);try{let o=await E(`/projects/${s}/merge_requests/${n}/merge`,{method:"PUT",body:i});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??n,project:String(t),provider:"gitlab",state:o.state})}catch(o){let a=String(o.message||o);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:n,project:String(t),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await E(`/projects/${P(t)}/merge_requests/${n}`);return JSON.stringify({iid:s.iid,projectId:s.project_id,title:s.title,description:(s.description||"").slice(0,5e3),state:s.state,author:s.author?.username,sourceBranch:s.source_branch,targetBranch:s.target_branch,draft:s.draft??s.work_in_progress??!1,mergeStatus:s.merge_status,changesCount:s.changes_count,labels:Array.isArray(s.labels)?s.labels:[],webUrl:s.web_url,createdAt:s.created_at,updatedAt:s.updated_at,mergedAt:s.merged_at,diffRefs:s.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await E(`/projects/${P(t)}/merge_requests/${n}/changes`),i=Array.isArray(s.changes)?s.changes:[];return JSON.stringify({iid:s.iid,total:i.length,diffRefs:s.diff_refs||null,files:i.map(o=>({oldPath:o.old_path,newPath:o.new_path,newFile:!!o.new_file,deletedFile:!!o.deleted_file,renamedFile:!!o.renamed_file,diff:typeof o.diff=="string"?o.diff.slice(0,3e3):""}))})}case"gitlab_list_commits":{let{projectId:t,since:n,until:s,refName:i,page:o,perPage:a,withStats:c}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let l=new URLSearchParams;l.set("per_page",String(Math.min(Number(a)||50,100))),l.set("page",String(Number(o)||1)),n&&l.set("since",n),s&&l.set("until",s),i&&l.set("ref_name",i),c!==!1&&l.set("with_stats","true");let d=await E(`/projects/${P(t)}/repository/commits?${l.toString()}`),p=(Array.isArray(d)?d:[]).map(u=>({id:u.id,shortId:u.short_id,title:u.title,authorName:u.author_name,authorEmail:u.author_email,authoredDate:u.authored_date,committedDate:u.committed_date,parentIds:Array.isArray(u.parent_ids)?u.parent_ids:[],stats:u.stats||null}));return JSON.stringify({page:Number(o)||1,count:p.length,hasMore:p.length>=Math.min(Number(a)||50,100),commits:p})}case"gitlab_get_commit":{let{projectId:t,sha:n,includeDiff:s,includeMrs:i}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and sha are required"});let o=await E(`/projects/${P(t)}/repository/commits/${encodeURIComponent(n)}`),a;if(i)try{let l=await E(`/projects/${P(t)}/repository/commits/${encodeURIComponent(n)}/merge_requests`);a=(Array.isArray(l)?l:[]).map(d=>({iid:d.iid,title:d.title,state:d.state,webUrl:d.web_url}))}catch{a=[]}let c;if(s!==!1){let l=await E(`/projects/${P(t)}/repository/commits/${encodeURIComponent(n)}/diff`);c=(Array.isArray(l)?l:[]).map(d=>({oldPath:d.old_path,newPath:d.new_path,newFile:!!d.new_file,deletedFile:!!d.deleted_file,renamedFile:!!d.renamed_file,diff:typeof d.diff=="string"?d.diff.slice(0,3e3):""}))}return JSON.stringify({id:o.id,shortId:o.short_id,title:o.title,message:typeof o.message=="string"?o.message.slice(0,2e3):"",authorName:o.author_name,authorEmail:o.author_email,authoredDate:o.authored_date,committedDate:o.committed_date,parentIds:Array.isArray(o.parent_ids)?o.parent_ids:[],stats:o.stats||null,webUrl:o.web_url,...c?{filesChanged:c.length,files:c}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:t,state:n,targetBranch:s,sourceBranch:i,authorUsername:o,labels:a,search:c,sort:l,orderBy:d,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||20)),u.set("order_by",d||"updated_at"),u.set("sort",l||"desc"),s&&u.set("target_branch",s),i&&u.set("source_branch",i),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await E(`/projects/${P(t)}/merge_requests?${u.toString()}`),h=(Array.isArray(m)?m:[]).map(y=>({iid:y.iid,title:y.title,state:y.state,author:y.author?.username,sourceBranch:y.source_branch,targetBranch:y.target_branch,draft:y.draft??y.work_in_progress??!1,labels:Array.isArray(y.labels)?y.labels:[],webUrl:y.web_url,createdAt:y.created_at,updatedAt:y.updated_at}));return JSON.stringify({count:h.length,mergeRequests:h})}case"gitlab_list_mr_notes":{let{projectId:t,iid:n,limit:s}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let i=await E(`/projects/${P(t)}/merge_requests/${n}/notes?per_page=${s||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(i)?i.length:0,notes:(Array.isArray(i)?i:[]).map(o=>({id:o.id,author:o.author?.username,body:(o.body||"").slice(0,1e3),system:!!o.system,createdAt:o.created_at}))})}case"gitlab_post_mr_note":{let{projectId:t,iid:n,body:s}=e||{};if(!t||!n||!s)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await E(`/projects/${P(t)}/merge_requests/${n}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:n,path:s,oldPath:i,newLine:o,oldLine:a,body:c}=e||{};if(!t||!n||!s||!c)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(o==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let l=P(t),d=e.diffRefs||null;if(d||(d=(await E(`/projects/${l}/merge_requests/${n}`)).diff_refs||null),!d||!d.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let p={base_sha:d.base_sha,start_sha:d.start_sha,head_sha:d.head_sha,position_type:"text",new_path:s,old_path:i||s};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await E(`/projects/${l}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(c),position:p}});return JSON.stringify({ok:!0,discussionId:u.id})}catch(u){return JSON.stringify({ok:!1,error:`inline anchor rejected (${u.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:t,iid:n,body:s,comments:i}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let o=P(t),a=Array.isArray(i)?i.filter(f=>f&&f.path&&f.body&&(f.newLine!=null||f.oldLine!=null)):[];if(!s&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=e.diffRefs||null;a.length>0&&!c&&(c=(await E(`/projects/${o}/merge_requests/${n}`)).diff_refs||null);let l=new Set,d=null;try{for(let f=1;f<=20;f+=1){let b=await E(`/projects/${o}/merge_requests/${n}/discussions?per_page=100&page=${f}`);if(!Array.isArray(b)||b.length===0)break;for(let g of b)for(let k of g.notes||[]){let v=Vt(k.body);v&&l.add(v),d==null&&Xt(k.body)&&(d=k.id)}if(b.length<100)break}}catch{}let p=!1,u=!1;if(s){let f=`${String(s)}${Zt}`;try{d!=null?(await E(`/projects/${o}/merge_requests/${n}/notes/${d}`,{method:"PUT",body:{body:f}}),u=!0):await E(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:f}}),p=!0}catch{await E(`/projects/${o}/merge_requests/${n}/notes`,{method:"POST",body:{body:f}}),p=!0}}let{toPost:m,skipped:h}=Qt(a,l),y=0,_=[];if(m.length>0&&c)for(let f of m){let b={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:f.path,old_path:f.oldPath||f.path};f.newLine!=null&&(b.new_line=Number(f.newLine)),f.oldLine!=null&&(b.old_line=Number(f.oldLine));try{await E(`/projects/${o}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(f.body),position:b}}),y+=1}catch(g){_.push(`${f.path}:${f.newLine??f.oldLine} \u2014 ${g.message}`)}}else m.length>0&&!c&&_.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:p,summaryUpdated:u,inlinePosted:y,inlineSkipped:h||void 0,inlineErrors:_.length?_:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:n,discussionId:s}=e||{};if(!t||!n||!s)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let i=await E(`/projects/${P(t)}/merge_requests/${n}/discussions/${encodeURIComponent(s)}`),o=Array.isArray(i.notes)?i.notes:[],a=o.find(l=>l.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:i.id,individualNote:!!i.individual_note,path:c&&(c.new_path||c.old_path)||null,newLine:c?c.new_line??null:null,oldLine:c?c.old_line??null:null,diffRefs:c?{base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha}:null,notes:o.map(l=>({id:l.id,author:l.author?.username,body:(l.body||"").slice(0,4e3),system:!!l.system,createdAt:l.created_at}))})}case"gitlab_reply_discussion":{let{projectId:t,iid:n,discussionId:s,body:i}=e||{};if(!t||!n||!s||!i)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await E(`/projects/${P(t)}/merge_requests/${n}/discussions/${encodeURIComponent(s)}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:t,limit:n}=e||{},s=Math.min(Number(n)>0?Number(n):50,200),i=new URLSearchParams;i.set("membership","true"),i.set("simple","true"),i.set("order_by","last_activity_at"),i.set("sort","desc"),i.set("per_page",String(Math.min(s+1,100))),t&&i.set("search",String(t));let o=async()=>{let u=await E(`/projects?${i.toString()}`);return Array.isArray(u)?u:[]},a=tr(),c=$s(),l=[];for(let u of a||[null]){let m=u?await rr.run(u,o):await o();for(let h of m)js(u?u.repos:c,h&&h.path_with_namespace)&&l.push({p:h,host:u?u.webHost:null})}let d=l.length>s,p=l.slice(0,s).map(({p:u,host:m})=>({fullPath:u.path_with_namespace,name:u.name,webUrl:u.web_url,defaultBranch:u.default_branch||null,visibility:u.visibility||null,...m?{host:m}:{}}));return JSON.stringify({count:p.length,truncated:d,projects:p})}case"gitlab_list_issues":{let{projectId:t,state:n,labels:s,assigneeUsername:i,authorUsername:o,updatedAfter:a,search:c,sort:l,orderBy:d,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",n||"opened"),u.set("per_page",String(p||30)),u.set("order_by",d||"updated_at"),u.set("sort",l||"desc"),s&&u.set("labels",Array.isArray(s)?s.join(","):s),i&&u.set("assignee_username",i),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await E(`/projects/${P(t)}/issues?${u.toString()}`),h=(Array.isArray(m)?m:[]).map(y=>({iid:y.iid,title:y.title,state:y.state,labels:Array.isArray(y.labels)?y.labels:[],author:y.author?.username,assignees:(y.assignees||[]).map(_=>_.username),userNotesCount:y.user_notes_count,webUrl:y.web_url,createdAt:y.created_at,updatedAt:y.updated_at}));return JSON.stringify({count:h.length,issues:h})}case"gitlab_get_issue":{let{projectId:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let s=await E(`/projects/${P(t)}/issues/${n}`);return JSON.stringify({iid:s.iid,projectId:s.project_id,title:s.title,description:(s.description||"").slice(0,5e3),state:s.state,labels:Array.isArray(s.labels)?s.labels:[],author:s.author?.username,assignees:(s.assignees||[]).map(i=>i.username),milestone:s.milestone?.title||null,webUrl:s.web_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"gitlab_add_issue_comment":{let{projectId:t,iid:n,body:s}=e||{};if(!t||!n||!s)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await E(`/projects/${P(t)}/issues/${n}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}var Xe={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:I.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_URL","GITLAB_INSTANCE_URL","GITLAB_API_URL","GITLAB_ALLOWED_REPOS","GITLAB_INSTANCES","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
|
|
136
139
|
You have access to the user's GitLab projects via the REST API (cloud gitlab.com OR self-hosted). A "merge request" (MR) is GitLab's pull request. An MR is addressed by a PROJECT (numeric id OR full path like "group/repo") and an \`iid\` (the per-project MR number shown in the URL). For projects, prefer the full path form ("group/subgroup/repo") \u2014 it's what users have. Available tools:
|
|
137
140
|
|
|
138
141
|
### Discovery
|
|
@@ -158,7 +161,7 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
|
|
|
158
161
|
|
|
159
162
|
### Notes
|
|
160
163
|
- A code-review flow is: gitlab_get_mr (context + diff_refs) \u2192 gitlab_get_mr_changes (the diff) \u2192 gitlab_post_mr_discussion per inline finding \u2192 gitlab_post_mr_note for the summary.
|
|
161
|
-
- If an inline position is rejected by GitLab (bad line anchor), fall back to gitlab_post_mr_note with the file/line in the text.`,resolve(){let r=_c();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/gitlab.js","gitlabSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{let e=Bt(),n=Hn(),s=null;if(n){let i=vc(t);if(i){let{path:o,instance:a}=await Ic(i,e);if(!Yn(n,o)||e&&!a)return JSON.stringify({error:`Repository "${o||i}" is not available to this project. This project's agents may only use: ${[...n].join(", ")}. An owner changes this in Project Settings \u2192 Repository access.`,allowedRepos:[...n]});s=a}}return s?await Dt.run(s,()=>Gn(r,t)):await Gn(r,t)}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_commits",description:"List a project's repository commits (the commit HISTORY \u2014 not MRs), optionally bounded by since/until ISO dates and a ref/branch, with per-commit stats (additions/deletions). Paginated: keep calling with page+1 while hasMore is true. This is the ONLY correct way to enumerate commits in a date window \u2014 gitlab_clone is shallow (depth 1) and its git log shows just one commit.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},since:{type:"string",description:'Only commits after this ISO-8601 date/time (inclusive), e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:'Only commits before this ISO-8601 date/time, e.g. "2026-07-01T00:00:00Z"'},refName:{type:"string",description:"Branch/tag to list (defaults to the default branch)"},page:{type:"number",description:"Page number, 1-based (default 1)"},perPage:{type:"number",description:"Commits per page, max 100 (default 50)"},withStats:{type:"boolean",description:"Include per-commit additions/deletions stats (default true)"}},required:["projectId"]}},{name:"gitlab_get_commit",description:"Get ONE commit's full detail \u2014 message, author, timestamps, stats, and (by default) its per-file diffs (each capped at 3000 chars) \u2014 so you can judge the nature/complexity of the change. Use after gitlab_list_commits.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},sha:{type:"string",description:"The commit sha (full or short)"},includeDiff:{type:"boolean",description:"Include per-file diffs (default true; set false for metadata-only)"},includeMrs:{type:"boolean",description:"Also return the merge request(s) containing this commit ({iid,title,state,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["projectId","sha"]}},{name:"gitlab_list_mrs",description:"List a GitLab project's merge requests, filtered by state and other criteria. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","merged","locked","all"],description:"Filter by state (default: opened)"},targetBranch:{type:"string",description:"Filter by target branch"},sourceBranch:{type:"string",description:"Filter by source branch"},authorUsername:{type:"string",description:"Filter by author username"},labels:{type:"array",items:{type:"string"},description:"Only MRs carrying ALL of these labels"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at","title"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max MRs (default: 20)"}},required:["projectId"]}},{name:"gitlab_list_mr_notes",description:"List the discussion notes on a GitLab merge request (chronological).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},limit:{type:"number",description:"Max notes (default 50)"}},required:["projectId","iid"]}},{name:"gitlab_post_mr_note",description:"Post a general (non-inline) comment on a GitLab merge request. Use for a review summary or a top-level remark.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}},{name:"gitlab_post_mr_discussion",description:"Post an INLINE review comment anchored to a file + line in a GitLab merge request diff. Provide newLine (added/changed line) or oldLine (removed/context line). Pass diffRefs from gitlab_get_mr/gitlab_get_mr_changes, or omit to have the tool fetch them. If the line anchor is rejected, fall back to gitlab_post_mr_note.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr. Omit and the tool fetches them."}},required:["projectId","iid","path","body"]}},{name:"gitlab_create_mr_review",description:"Post a full review on a GitLab merge request in one call: a summary note plus optional inline comments anchored to file/line in the diff. Convenience wrapper over gitlab_post_mr_note + gitlab_post_mr_discussion.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"The review summary (markdown). Posted as a top-level MR note."},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr \u2014 required to anchor inline comments. Omit and the tool fetches them."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line in a file.",items:{type:"object",properties:{path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","body"]}}},required:["projectId","iid"]}},{name:"gitlab_get_discussion",description:"Read a single GitLab merge-request DISCUSSION (thread) by its discussion id: all notes in order plus the diff position (file + line) it is anchored to. Use this to understand a human's reply to a previous review discussion before replying in-thread.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id (from the Note Hook payload or gitlab_list_mr_notes)"}},required:["projectId","iid","discussionId"]}},{name:"gitlab_reply_discussion",description:"Reply IN-THREAD to an existing GitLab merge-request discussion (a conversational reply appended to the SAME thread \u2014 NOT a fresh review). Use after gitlab_get_discussion to answer a human's reply to a review comment.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["projectId","iid","discussionId","body"]}},{name:"gitlab_list_issues",description:"List a GitLab project's issues, filtered by state, labels, and an updatedAfter polling cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","all"],description:"Filter by state (default: opened)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},assigneeUsername:{type:"string",description:"Filter by assignee username"},authorUsername:{type:"string",description:"Filter by author username"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30)"}},required:["projectId"]}},{name:"gitlab_get_issue",description:"Get a single GitLab issue with full detail (title, description, state, labels, assignees, web url).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid (the per-project issue number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_add_issue_comment",description:"Add a comment to a GitLab issue. Also the way to record an MR link on a ticket (post a markdown link).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}}]};import{existsSync as Nc}from"fs";import{fileURLToPath as Tc}from"url";import{dirname as Oc,resolve as Ac}from"path";import{resolveIntegrationToken as Rc}from"@zibby/core/backend-client.js";function Ec(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Oc(Tc(import.meta.url)),t=Ac(r,"..","bin","mcp-skill.mjs");return Nc(t)?t:null}async function Z(r,t={}){let{token:e}=await Rc("figma"),n=r.startsWith("https://")?r:`https://api.figma.com${r}`,s={"X-Figma-Token":e,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},i=await fetch(n,{method:t.method||"GET",headers:s,body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Figma API ${i.status}: ${o.slice(0,300)}`)}return i.json()}function de(r){let t=String(r||"").trim(),e=t.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return e?e[1]:t}function Mt(r){return r==null?void 0:(Array.isArray(r)?r:String(r).split(",")).map(e=>String(e).trim().replace(/-/g,":")).filter(Boolean).join(",")}function xc(r){let t=String(r||"").match(/[?&]node-id=([^&]+)/i);return t?decodeURIComponent(t[1]).replace(/-/g,":"):void 0}var re=r=>typeof r=="number"?Math.round(r*100)/100:r;function Ar(r){if(!r)return null;let t=n=>Math.round((n??0)*255).toString(16).padStart(2,"0"),e={hex:`#${t(r.r)}${t(r.g)}${t(r.b)}`.toUpperCase()};return r.a!=null&&r.a<1&&(e.opacity=re(r.a)),e}function zn(r){return!r||r.visible===!1?null:r.type==="SOLID"?{type:"SOLID",...Ar(r.color),...r.opacity!=null?{opacity:r.opacity}:{}}:{type:r.type,...r.opacity!=null?{opacity:r.opacity}:{},...r.gradientStops?{stops:r.gradientStops.map(t=>({position:re(t.position),...Ar(t.color)}))}:{}}}function Wn(r,t){let e=r.absoluteBoundingBox,n={id:r.id,name:r.name,type:r.type};e&&(n.size={w:re(e.width),h:re(e.height)},n.position={x:re(e.x),y:re(e.y)}),r.opacity!=null&&r.opacity!==1&&(n.opacity=r.opacity),r.cornerRadius!=null&&(n.cornerRadius=r.cornerRadius),Array.isArray(r.rectangleCornerRadii)&&(n.cornerRadii=r.rectangleCornerRadii);let s=(r.fills||[]).map(zn).filter(Boolean);s.length&&(n.fills=s);let i=(r.strokes||[]).map(zn).filter(Boolean);i.length&&(n.strokes=i,r.strokeWeight!=null&&(n.strokeWeight=r.strokeWeight));let o=(r.effects||[]).filter(a=>a.visible!==!1).map(a=>({type:a.type,...a.radius!=null?{radius:a.radius}:{},...a.offset?{offset:{x:re(a.offset.x),y:re(a.offset.y)}}:{},...a.spread?{spread:a.spread}:{},...a.color?Ar(a.color):{}}));if(o.length&&(n.effects=o),r.layoutMode&&r.layoutMode!=="NONE"&&(n.autoLayout={direction:r.layoutMode,padding:{l:r.paddingLeft??0,r:r.paddingRight??0,t:r.paddingTop??0,b:r.paddingBottom??0},gap:r.itemSpacing??0,align:{primary:r.primaryAxisAlignItems,counter:r.counterAxisAlignItems}}),r.type==="TEXT"){let a=r.style||{};n.text=r.characters,n.textStyle={fontFamily:a.fontFamily,fontWeight:a.fontWeight,fontSize:a.fontSize,lineHeightPx:a.lineHeightPx!=null?re(a.lineHeightPx):void 0,letterSpacing:a.letterSpacing!=null?re(a.letterSpacing):void 0,align:a.textAlignHorizontal,case:a.textCase}}return t>0&&Array.isArray(r.children)&&r.children.length&&(n.children=r.children.map(a=>Wn(a,t-1))),n}var Zn={id:"figma",callsBackend:!0,serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:S.FIGMA,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma
|
|
164
|
+
- If an inline position is rejected by GitLab (bad line anchor), fall back to gitlab_post_mr_note with the file/line in the text.`,resolve(){let r=El();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/gitlab.js","gitlabSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{let t=tr(),n=$s(),s=null;if(n){let i=Pl(e);if(i){let{path:o,instance:a}=await Cl(i,t);if(!js(n,o)||t&&!a)return JSON.stringify({error:`Repository "${o||i}" is not available to this project. This project's agents may only use: ${[...n].join(", ")}. An owner changes this in Project Settings \u2192 Repository access.`,allowedRepos:[...n]});s=a}}return s?await rr.run(s,()=>Ls(r,e)):await Ls(r,e)}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_commits",description:"List a project's repository commits (the commit HISTORY \u2014 not MRs), optionally bounded by since/until ISO dates and a ref/branch, with per-commit stats (additions/deletions). Paginated: keep calling with page+1 while hasMore is true. This is the ONLY correct way to enumerate commits in a date window \u2014 gitlab_clone is shallow (depth 1) and its git log shows just one commit.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},since:{type:"string",description:'Only commits after this ISO-8601 date/time (inclusive), e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:'Only commits before this ISO-8601 date/time, e.g. "2026-07-01T00:00:00Z"'},refName:{type:"string",description:"Branch/tag to list (defaults to the default branch)"},page:{type:"number",description:"Page number, 1-based (default 1)"},perPage:{type:"number",description:"Commits per page, max 100 (default 50)"},withStats:{type:"boolean",description:"Include per-commit additions/deletions stats (default true)"}},required:["projectId"]}},{name:"gitlab_get_commit",description:"Get ONE commit's full detail \u2014 message, author, timestamps, stats, and (by default) its per-file diffs (each capped at 3000 chars) \u2014 so you can judge the nature/complexity of the change. Use after gitlab_list_commits.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},sha:{type:"string",description:"The commit sha (full or short)"},includeDiff:{type:"boolean",description:"Include per-file diffs (default true; set false for metadata-only)"},includeMrs:{type:"boolean",description:"Also return the merge request(s) containing this commit ({iid,title,state,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["projectId","sha"]}},{name:"gitlab_list_mrs",description:"List a GitLab project's merge requests, filtered by state and other criteria. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","merged","locked","all"],description:"Filter by state (default: opened)"},targetBranch:{type:"string",description:"Filter by target branch"},sourceBranch:{type:"string",description:"Filter by source branch"},authorUsername:{type:"string",description:"Filter by author username"},labels:{type:"array",items:{type:"string"},description:"Only MRs carrying ALL of these labels"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at","title"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max MRs (default: 20)"}},required:["projectId"]}},{name:"gitlab_list_mr_notes",description:"List the discussion notes on a GitLab merge request (chronological).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},limit:{type:"number",description:"Max notes (default 50)"}},required:["projectId","iid"]}},{name:"gitlab_post_mr_note",description:"Post a general (non-inline) comment on a GitLab merge request. Use for a review summary or a top-level remark.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}},{name:"gitlab_post_mr_discussion",description:"Post an INLINE review comment anchored to a file + line in a GitLab merge request diff. Provide newLine (added/changed line) or oldLine (removed/context line). Pass diffRefs from gitlab_get_mr/gitlab_get_mr_changes, or omit to have the tool fetch them. If the line anchor is rejected, fall back to gitlab_post_mr_note.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr. Omit and the tool fetches them."}},required:["projectId","iid","path","body"]}},{name:"gitlab_create_mr_review",description:"Post a full review on a GitLab merge request in one call: a summary note plus optional inline comments anchored to file/line in the diff. Convenience wrapper over gitlab_post_mr_note + gitlab_post_mr_discussion.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"The review summary (markdown). Posted as a top-level MR note."},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr \u2014 required to anchor inline comments. Omit and the tool fetches them."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line in a file.",items:{type:"object",properties:{path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","body"]}}},required:["projectId","iid"]}},{name:"gitlab_get_discussion",description:"Read a single GitLab merge-request DISCUSSION (thread) by its discussion id: all notes in order plus the diff position (file + line) it is anchored to. Use this to understand a human's reply to a previous review discussion before replying in-thread.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id (from the Note Hook payload or gitlab_list_mr_notes)"}},required:["projectId","iid","discussionId"]}},{name:"gitlab_reply_discussion",description:"Reply IN-THREAD to an existing GitLab merge-request discussion (a conversational reply appended to the SAME thread \u2014 NOT a fresh review). Use after gitlab_get_discussion to answer a human's reply to a review comment.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["projectId","iid","discussionId","body"]}},{name:"gitlab_list_issues",description:"List a GitLab project's issues, filtered by state, labels, and an updatedAfter polling cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","all"],description:"Filter by state (default: opened)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},assigneeUsername:{type:"string",description:"Filter by assignee username"},authorUsername:{type:"string",description:"Filter by author username"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30)"}},required:["projectId"]}},{name:"gitlab_get_issue",description:"Get a single GitLab issue with full detail (title, description, state, labels, assignees, web url).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid (the per-project issue number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_add_issue_comment",description:"Add a comment to a GitLab issue. Also the way to record an MR link on a ticket (post a markdown link).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}}]};import{existsSync as Ul}from"fs";import{fileURLToPath as Bl}from"url";import{dirname as Dl,resolve as Ml}from"path";import{resolveIntegrationToken as Jl}from"@zibby/core/backend-client.js";function ql(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Dl(Bl(import.meta.url)),e=Ml(r,"..","bin","mcp-skill.mjs");return Ul(e)?e:null}async function Q(r,e={}){let{token:t}=await Jl("figma"),n=r.startsWith("https://")?r:`https://api.figma.com${r}`,s={"X-Figma-Token":t,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},i=await w(n,{method:e.method||"GET",headers:s,body:e.body?JSON.stringify(e.body):void 0},{kind:"api",what:`Figma ${e.method||"GET"} ${r}`});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Figma API ${i.status}: ${o.slice(0,300)}`)}return i.json()}function ye(r){let e=String(r||"").trim(),t=e.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return t?t[1]:e}function sr(r){return r==null?void 0:(Array.isArray(r)?r:String(r).split(",")).map(t=>String(t).trim().replace(/-/g,":")).filter(Boolean).join(",")}function Gl(r){let e=String(r||"").match(/[?&]node-id=([^&]+)/i);return e?decodeURIComponent(e[1]).replace(/-/g,":"):void 0}var ae=r=>typeof r=="number"?Math.round(r*100)/100:r;function Qr(r){if(!r)return null;let e=n=>Math.round((n??0)*255).toString(16).padStart(2,"0"),t={hex:`#${e(r.r)}${e(r.g)}${e(r.b)}`.toUpperCase()};return r.a!=null&&r.a<1&&(t.opacity=ae(r.a)),t}function Ps(r){return!r||r.visible===!1?null:r.type==="SOLID"?{type:"SOLID",...Qr(r.color),...r.opacity!=null?{opacity:r.opacity}:{}}:{type:r.type,...r.opacity!=null?{opacity:r.opacity}:{},...r.gradientStops?{stops:r.gradientStops.map(e=>({position:ae(e.position),...Qr(e.color)}))}:{}}}function Cs(r,e){let t=r.absoluteBoundingBox,n={id:r.id,name:r.name,type:r.type};t&&(n.size={w:ae(t.width),h:ae(t.height)},n.position={x:ae(t.x),y:ae(t.y)}),r.opacity!=null&&r.opacity!==1&&(n.opacity=r.opacity),r.cornerRadius!=null&&(n.cornerRadius=r.cornerRadius),Array.isArray(r.rectangleCornerRadii)&&(n.cornerRadii=r.rectangleCornerRadii);let s=(r.fills||[]).map(Ps).filter(Boolean);s.length&&(n.fills=s);let i=(r.strokes||[]).map(Ps).filter(Boolean);i.length&&(n.strokes=i,r.strokeWeight!=null&&(n.strokeWeight=r.strokeWeight));let o=(r.effects||[]).filter(a=>a.visible!==!1).map(a=>({type:a.type,...a.radius!=null?{radius:a.radius}:{},...a.offset?{offset:{x:ae(a.offset.x),y:ae(a.offset.y)}}:{},...a.spread?{spread:a.spread}:{},...a.color?Qr(a.color):{}}));if(o.length&&(n.effects=o),r.layoutMode&&r.layoutMode!=="NONE"&&(n.autoLayout={direction:r.layoutMode,padding:{l:r.paddingLeft??0,r:r.paddingRight??0,t:r.paddingTop??0,b:r.paddingBottom??0},gap:r.itemSpacing??0,align:{primary:r.primaryAxisAlignItems,counter:r.counterAxisAlignItems}}),r.type==="TEXT"){let a=r.style||{};n.text=r.characters,n.textStyle={fontFamily:a.fontFamily,fontWeight:a.fontWeight,fontSize:a.fontSize,lineHeightPx:a.lineHeightPx!=null?ae(a.lineHeightPx):void 0,letterSpacing:a.letterSpacing!=null?ae(a.letterSpacing):void 0,align:a.textAlignHorizontal,case:a.textCase}}return e>0&&Array.isArray(r.children)&&r.children.length&&(n.children=r.children.map(a=>Cs(a,e-1))),n}var Us={id:"figma",callsBackend:!0,serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:I.FIGMA,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma
|
|
162
165
|
You have access to the user's Figma files via the Figma REST API. Every tool that takes a file accepts EITHER the raw file key OR a full figma.com URL (figma.com/file|design/<key>/...). Node ids accept URL form \`1-23\` or API form \`1:23\` interchangeably. Tools:
|
|
163
166
|
|
|
164
167
|
### Identity
|
|
@@ -189,7 +192,7 @@ You have access to the user's Figma files via the Figma REST API. Every tool tha
|
|
|
189
192
|
|
|
190
193
|
### Notes
|
|
191
194
|
- The file key is NOT the file name \u2014 it's the opaque id segment in the URL (or just paste the URL).
|
|
192
|
-
- Node ids look like "1:23" and come from figma_get_file / figma_get_nodes / figma_parse_url output.`,resolve(){let r=Ec();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/figma.js","figmaSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"figma_get_me":{let e=await Z("/v1/me");return JSON.stringify({id:e.id,handle:e.handle,email:e.email,imgUrl:e.img_url})}case"figma_get_file":{let e=de((t||{}).fileKey),{depth:n}=t||{};if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=`/v1/files/${encodeURIComponent(e)}`;if(n!=null){let a=Number(n);!Number.isNaN(a)&&a>0&&(s+=`?depth=${a}`)}let i=await Z(s),o=(i.document?.children||[]).map(a=>({id:a.id,name:a.name,type:a.type,childCount:Array.isArray(a.children)?a.children.length:0,children:(a.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:i.name,lastModified:i.lastModified,version:i.version,editorType:i.editorType,role:i.role,pages:o})}case"figma_get_nodes":{let e=de((t||{}).fileKey),{ids:n,depth:s}=t||{};if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=Mt(n);if(!i)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=new URLSearchParams;if(o.set("ids",i),s!=null){let l=Number(s);!Number.isNaN(l)&&l>0&&o.set("depth",String(l))}let a=await Z(`/v1/files/${encodeURIComponent(e)}/nodes?${o.toString()}`),c={};for(let[l,d]of Object.entries(a.nodes||{}))c[l]=d?.document?{id:d.document.id,name:d.document.name,type:d.document.type,document:d.document}:d;return JSON.stringify({name:a.name,nodes:c})}case"figma_get_node_specs":{let e=de((t||{}).file),{ids:n,depth:s}=t||{};if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let i=Mt(n);if(!i)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=Number(s);Number.isNaN(o)&&(o=2),o=Math.min(6,Math.max(0,Math.trunc(o)));let a=new URLSearchParams;a.set("ids",i),a.set("depth",String(o));let c=await Z(`/v1/files/${encodeURIComponent(e)}/nodes?${a.toString()}`),l={};for(let[d,p]of Object.entries(c.nodes||{}))l[d]=p&&p.document?Wn(p.document,o):null;return JSON.stringify(l)}case"figma_render_png":{let e=de((t||{}).fileKey??(t||{}).file),{ids:n,scale:s,format:i,svg_include_id:o,version:a}=t||{};if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let c=Mt(n);if(!c)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let l=["png","jpg","svg","pdf"].includes(String(i||"").toLowerCase())?String(i).toLowerCase():"png",d=new URLSearchParams;d.set("ids",c),d.set("format",l);let p;(l==="png"||l==="jpg")&&(p=Number(s),(Number.isNaN(p)||p<=0)&&(p=1),p=Math.min(4,Math.max(.01,p)),d.set("scale",String(p))),l==="svg"&&o!=null&&d.set("svg_include_id",String(!!o)),a&&d.set("version",String(a));let u=await Z(`/v1/images/${encodeURIComponent(e)}?${d.toString()}`);return u.err?JSON.stringify({error:`Figma render error: ${u.err}`}):JSON.stringify({format:l,...p!=null?{scale:p}:{},images:u.images||{}})}case"figma_get_image_fills":{let e=de((t||{}).file);if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let n=await Z(`/v1/files/${encodeURIComponent(e)}/images`);return JSON.stringify({images:n.meta?.images??n.images??{}})}case"figma_get_file_versions":{let e=de((t||{}).file);if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let s=((await Z(`/v1/files/${encodeURIComponent(e)}/versions`)).versions||[]).map(i=>({id:i.id,label:i.label,description:i.description,createdAt:i.created_at,user:i.user?.handle}));return JSON.stringify({count:s.length,versions:s})}case"figma_get_comments":{let e=de((t||{}).fileKey);if(!e)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=((await Z(`/v1/files/${encodeURIComponent(e)}/comments`)).comments||[]).map(i=>({id:i.id,message:i.message,user:i.user?.handle,createdAt:i.created_at,resolvedAt:i.resolved_at||null,parentId:i.parent_id||null}));return JSON.stringify({count:s.length,comments:s})}case"figma_post_comment":{let e=de((t||{}).file),{message:n,comment_id:s,node_id:i,x:o,y:a}=t||{};if(!e)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});if(!n)return JSON.stringify({error:"message is required"});let c={message:n};s&&(c.comment_id=s),i?c.client_meta={node_id:Mt(i),node_offset:{x:o??0,y:a??0}}:(o!=null||a!=null)&&(c.client_meta={x:o??0,y:a??0});let l=await Z(`/v1/files/${encodeURIComponent(e)}/comments`,{method:"POST",body:c});return JSON.stringify({id:l.id,message:l.message,fileKey:e,createdAt:l.created_at,parentId:l.parent_id||null})}case"figma_get_team_projects":{let{team_id:e}=t||{};if(!e)return JSON.stringify({error:"team_id is required"});let n=await Z(`/v1/teams/${encodeURIComponent(e)}/projects`);return JSON.stringify({name:n.name,projects:n.projects||[]})}case"figma_get_project_files":{let{project_id:e,branch_data:n}=t||{};if(!e)return JSON.stringify({error:"project_id is required"});let s=new URLSearchParams;n&&s.set("branch_data","true");let i=s.toString(),o=await Z(`/v1/projects/${encodeURIComponent(e)}/files${i?`?${i}`:""}`);return JSON.stringify({name:o.name,files:o.files||[]})}case"figma_parse_url":{let{url:e}=t||{};return JSON.stringify({file_key:de(e),node_id:xc(e)??null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree. Accepts a file key OR a figma.com URL (figma.com/file|design/<key>/... \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes or figma_get_node_specs to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'A file key OR a figma.com URL (e.g. "aBcD1234" or figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch. Accepts URL form ["1-23"] or API form ["1:23"]. A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_get_node_specs",description:"Dev-Mode-style inspection computed from the REST tree: for the given nodes and their children returns size, position, colors (hex), fonts/text-style, spacing/auto-layout, corner radius, strokes and effects \u2014 a compact spec for reproducing a design in code. Prefer this over figma_get_nodes when your job is to build UI from a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to inspect (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},depth:{type:"number",description:"How many levels of children to walk (0-6, default 2)."}},required:["file","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to an image and return the URLs (a map of nodeId \u2192 URL). Despite the name it renders PNG/JPG/SVG/PDF (default png). Use to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},format:{type:"string",enum:["png","jpg","svg","pdf"],description:"Output format (default png)."},scale:{type:"number",description:"Render scale, 0.01\u20134 (raster formats only; default 1). 2 for retina/hi-dpi."},svg_include_id:{type:"boolean",description:"For SVG: include element ids as attributes."},version:{type:"string",description:"Render a specific file version id (from figma_get_file_versions)."}},required:["fileKey","ids"]}},{name:"figma_get_image_fills",description:"Get a map of imageRef \u2192 download URL for every image fill used in a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_file_versions",description:"List a Figma file's saved version history (version id, label, created_at, user). A version id can be passed to figma_render_png to render a past version.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"}},required:["fileKey"]}},{name:"figma_post_comment",description:"Post a comment on a Figma file (WRITE \u2014 needs a PAT with comment-write scope). Optionally reply to a comment (comment_id), pin it to a node (node_id, with optional x/y offset), or pin to a canvas point (x/y).",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},message:{type:"string",description:"The comment text."},comment_id:{type:"string",description:"Optional: reply to this parent comment id."},node_id:{type:"string",description:'Optional: pin the comment to this node ("1-23" or "1:23").'},x:{type:"number",description:"Optional: x position (node offset if node_id given, else canvas point)."},y:{type:"number",description:"Optional: y position (node offset if node_id given, else canvas point)."}},required:["file","message"]}},{name:"figma_get_team_projects",description:"List the projects in a Figma team. Get team_id from a Figma team URL (\u2026/files/team/<TEAM_ID>/\u2026).",input_schema:{type:"object",properties:{team_id:{type:"string",description:"The Figma team id."}},required:["team_id"]}},{name:"figma_get_project_files",description:"List the files in a Figma project (from figma_get_team_projects). Returns file key, name, thumbnail, last_modified.",input_schema:{type:"object",properties:{project_id:{type:"string",description:"The Figma project id."},branch_data:{type:"boolean",description:"Optional: include branch metadata for each file."}},required:["project_id"]}},{name:"figma_parse_url",description:"Local helper (no API call): extract the file key and node id (colon form) from a figma.com file/design URL. Returns { file_key, node_id }.",input_schema:{type:"object",properties:{url:{type:"string",description:"A full figma.com file/design URL."}},required:["url"]}}]};import{existsSync as Lc}from"fs";import{fileURLToPath as jc}from"url";import{dirname as $c,resolve as Pc}from"path";import{resolveIntegrationToken as Cc}from"@zibby/core/backend-client.js";function Uc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=$c(jc(import.meta.url)),t=Pc(r,"..","bin","mcp-skill.mjs");return Lc(t)?t:null}async function ne(r,t={}){let{token:e}=await Cc("hubspot");if(!e)throw new Error("HubSpot not connected \u2014 Connect HubSpot in Integrations.");let n=r.startsWith("https://")?r:`https://api.hubapi.com${r}`,s={Authorization:`Bearer ${e}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},i=await fetch(n,{method:t.method||"GET",headers:s,body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let a=await i.text().catch(()=>""),c=i.status===401||i.status===403?" \u2014 token invalid/expired or missing the required Private App scope for this object":"";throw new Error(`HubSpot API ${i.status}${c}: ${a.slice(0,300)}`)}let o=await i.text().catch(()=>"");if(!o)return{};try{return JSON.parse(o)}catch{return{raw:o}}}function ke(r){return typeof r!="string"?null:r.trim()||null}function Vn(r,t={}){let e=new URLSearchParams;if(r!=null){let s=Array.isArray(r)?r.join(","):String(r);s&&e.set("properties",s)}for(let[s,i]of Object.entries(t))i!=null&&i!==""&&e.set(s,String(i));let n=e.toString();return n?`?${n}`:""}var Me="The CRM object type \u2014 one of the common values `contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions` (customer feedback: NPS/CSAT/CES), or any custom object name/id.",Xn={id:"hubspot",callsBackend:!0,serverName:"hubspot",allowedTools:["mcp__hubspot__*"],requiresIntegration:S.HUBSPOT,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"HubSpot CRM \u2014 search/read/create/update contacts, companies, deals, tickets, notes and feedback submissions via the HubSpot REST API.",promptFragment:"## HubSpot CRM\nYou have access to the user's HubSpot CRM via the HubSpot REST API (OAuth \u2014 the user connects HubSpot in Integrations; the token is resolved and auto-refreshed for you). The connected app grants the CRM scopes for the objects you touch.\n\nHubSpot's object model is **uniform** \u2014 nearly every tool takes an `objectType` (`contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions`, or a custom object). Records are `{ id, properties }`; you set/read named properties.\n\n**Before you create/update/search, call `hubspot_list_properties` to learn the valid property names for that object type** (they're not guessable). `feedback_submissions` is where NPS/CSAT/CES customer-feedback survey responses live.\n\n### Identity\n- hubspot_whoami: Confirm the token works \u2014 returns the portal (hub) id, account type, time zone, UI domain.\n\n### Schema\n- hubspot_list_properties: List the defined properties (name, label, type, fieldType) for an objectType. Do this first so you use real property names.\n\n### Read\n- hubspot_search: Search an objectType by full-text `query` OR structured `filters` (array of {propertyName, operator, value}). Returns { total, results:[{id, properties}] }.\n- hubspot_get_object: Fetch one record by id (optionally selecting specific properties).\n- hubspot_list_objects: Page through all records of an objectType (limit + after cursor).\n\n### Write\n- hubspot_create_object: Create a record from a `properties` object.\n- hubspot_update_object: Patch a record's `properties` by id.\n- hubspot_create_note: Convenience \u2014 log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket.\n- hubspot_associate: Associate two records (fromType/fromId \u2194 toType/toId) with the default association type.",resolve(){let r=Uc();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/hubspot.js","hubspotSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{let e=t||{};switch(r){case"hubspot_whoami":{let n=await ne("/account-info/v3/details");return JSON.stringify({portalId:n.portalId,accountType:n.accountType,timeZone:n.timeZone,uiDomain:n.uiDomain,companyCurrency:n.companyCurrency})}case"hubspot_list_properties":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required (e.g. contacts, companies, deals, tickets, feedback_submissions)"});let i=((await ne(`/crm/v3/properties/${encodeURIComponent(n)}`)).results||[]).map(o=>({name:o.name,label:o.label,type:o.type,fieldType:o.fieldType}));return JSON.stringify({objectType:n,count:i.length,properties:i})}case"hubspot_search":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let i={limit:Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20};e.query&&(i.query=String(e.query)),Array.isArray(e.filters)&&e.filters.length&&(i.filterGroups=[{filters:e.filters}]),e.properties!=null&&(i.properties=Array.isArray(e.properties)?e.properties:String(e.properties).split(",").map(a=>a.trim()).filter(Boolean));let o=await ne(`/crm/v3/objects/${encodeURIComponent(n)}/search`,{method:"POST",body:i});return JSON.stringify({total:o.total??(o.results?o.results.length:0),results:(o.results||[]).map(a=>({id:a.id,properties:a.properties}))})}case"hubspot_get_object":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});let s=Vn(e.properties,{associations:e.associations}),i=await ne(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(e.id)}${s}`);return JSON.stringify({id:i.id,properties:i.properties,...i.associations?{associations:i.associations}:{}})}case"hubspot_list_objects":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let s=Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20,i=Vn(e.properties,{limit:s,after:e.after}),o=await ne(`/crm/v3/objects/${encodeURIComponent(n)}${i}`);return JSON.stringify({results:(o.results||[]).map(a=>({id:a.id,properties:a.properties})),paging:o.paging||null})}case"hubspot_create_object":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value } \u2014 call hubspot_list_properties first for valid names)"});let s=await ne(`/crm/v3/objects/${encodeURIComponent(n)}`,{method:"POST",body:{properties:e.properties}});return JSON.stringify({id:s.id,properties:s.properties})}case"hubspot_update_object":{let n=ke(e.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value })"});let s=await ne(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(e.id)}`,{method:"PATCH",body:{properties:e.properties}});return JSON.stringify({id:s.id,properties:s.properties})}case"hubspot_create_note":{if(!e.body||typeof e.body!="string")return JSON.stringify({error:"body is required (the note text)"});let n=typeof e.timestamp=="string"&&e.timestamp?e.timestamp:null;if(!n)try{n=new Date().toISOString()}catch{n=null}if(!n)return JSON.stringify({error:"timestamp is required (pass an ISO 8601 string, e.g. 2026-01-01T00:00:00.000Z)"});let s=await ne("/crm/v3/objects/notes",{method:"POST",body:{properties:{hs_note_body:e.body,hs_timestamp:n}}}),i=s.id,o=[["contacts",e.contactId],["companies",e.companyId],["deals",e.dealId],["tickets",e.ticketId]].filter(([,c])=>c!=null&&c!==""),a=[];for(let[c,l]of o)try{await ne(`/crm/v4/objects/notes/${encodeURIComponent(i)}/associations/default/${c}/${encodeURIComponent(l)}`,{method:"PUT"}),a.push({toType:c,toId:String(l)})}catch(d){a.push({toType:c,toId:String(l),error:d.message})}return JSON.stringify({id:i,properties:s.properties,associatedTo:a})}case"hubspot_associate":{let n=ke(e.fromType),s=ke(e.toType);return!n||!e.fromId||!s||!e.toId?JSON.stringify({error:"fromType, fromId, toType and toId are all required"}):(await ne(`/crm/v4/objects/${encodeURIComponent(n)}/${encodeURIComponent(e.fromId)}/associations/default/${encodeURIComponent(s)}/${encodeURIComponent(e.toId)}`,{method:"PUT"}),JSON.stringify({ok:!0}))}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"hubspot_whoami",description:"Confirm the HubSpot token works: returns the portal (hub) id, account type, time zone and UI domain.",input_schema:{type:"object",properties:{}}},{name:"hubspot_list_properties",description:"List the defined properties (name, label, type, fieldType) for a CRM object type. Call this FIRST so you use valid property names when creating/updating/searching.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Me}},required:["objectType"]}},{name:"hubspot_search",description:"Search a CRM object type. Pass a full-text `query` OR structured `filters` (array of {propertyName, operator, value}, e.g. operator EQ/CONTAINS_TOKEN/GT/\u2026). Returns { total, results:[{id, properties}] }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Me},query:{type:"string",description:"Optional full-text search string."},filters:{type:"array",description:"Optional structured filters (ANDed). Each: { propertyName, operator, value }. Operators: EQ, NEQ, LT, LTE, GT, GTE, CONTAINS_TOKEN, HAS_PROPERTY, IN, \u2026",items:{type:"object",properties:{propertyName:{type:"string"},operator:{type:"string"},value:{type:"string"}}}},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each result."},limit:{type:"number",description:"Max results (default 20)."}},required:["objectType"]}},{name:"hubspot_get_object",description:"Fetch one CRM record by id. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Me},id:{type:"string",description:"The record id."},properties:{type:"array",items:{type:"string"},description:"Optional: specific property names to return."},associations:{type:"string",description:'Optional: comma-separated object types to also return associations for (e.g. "companies,deals").'}},required:["objectType","id"]}},{name:"hubspot_list_objects",description:"Page through records of a CRM object type. Returns { results, paging } \u2014 pass paging.next.after back as `after` for the next page.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Me},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each record."},limit:{type:"number",description:"Page size (default 20)."},after:{type:"string",description:"Optional paging cursor from a previous response (paging.next.after)."}},required:["objectType"]}},{name:"hubspot_create_object",description:"Create a CRM record. Pass `properties` as an object of { propertyName: value } (call hubspot_list_properties first for valid names). Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Me},properties:{type:"object",description:"Object of { propertyName: value } to set on the new record."}},required:["objectType","properties"]}},{name:"hubspot_update_object",description:"Update (PATCH) a CRM record by id. Pass `properties` as an object of { propertyName: value }. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Me},id:{type:"string",description:"The record id to update."},properties:{type:"object",description:"Object of { propertyName: value } to change."}},required:["objectType","id","properties"]}},{name:"hubspot_create_note",description:"Log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket. Returns { id, associatedTo }.",input_schema:{type:"object",properties:{body:{type:"string",description:"The note text (stored as hs_note_body)."},contactId:{type:"string",description:"Optional: associate the note to this contact id."},companyId:{type:"string",description:"Optional: associate the note to this company id."},dealId:{type:"string",description:"Optional: associate the note to this deal id."},ticketId:{type:"string",description:"Optional: associate the note to this ticket id."},timestamp:{type:"string",description:"Optional ISO 8601 timestamp for the note (defaults to now)."}},required:["body"]}},{name:"hubspot_associate",description:"Associate two CRM records with the default association type (e.g. a contact to a company). Returns { ok:true }.",input_schema:{type:"object",properties:{fromType:{type:"string",description:"Source object type (e.g. contacts)."},fromId:{type:"string",description:"Source record id."},toType:{type:"string",description:"Target object type (e.g. companies)."},toId:{type:"string",description:"Target record id."}},required:["fromType","fromId","toType","toId"]}}]};import{existsSync as Bc}from"fs";import{fileURLToPath as Dc}from"url";import{dirname as Jc,resolve as Mc}from"path";function qc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Jc(Dc(import.meta.url)),t=Mc(r,"..","bin","mcp-skill.mjs");return Bc(t)?t:null}var Fc=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Kc(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let r=process.env.LINEAR_API_KEY;if(!r)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return r}async function V(r,t={}){let e=await fetch(Fc,{method:"POST",headers:{Authorization:Kc(),"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:t})});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Linear API ${e.status}: ${s.slice(0,300)}`)}let n=await e.json().catch(()=>null);if(!n)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(n.errors)&&n.errors.length){let s=n.errors.map(i=>i?.message||String(i)).join("; ");throw new Error(`Linear GraphQL error: ${s.slice(0,300)}`)}return n.data}function it(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Gc(r,t){let e=it(r),n=it(t);if(!e||!n)return 0;if(e===n)return 1;if(e.length===1||n.length===1)return e===n?1:0;let s=d=>{let p=new Map;for(let u=0;u<d.length-1;u++){let m=d.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},i=s(e),o=s(n),a=0,c=0,l=0;for(let d of i.values())c+=d;for(let d of o.values())l+=d;for(let[d,p]of i.entries())a+=Math.min(p,o.get(d)||0);return 2*a/Math.max(1,c+l)}function Hc(r,t){let e=Array.isArray(r)?r:[];if(!e.length)return{state:null,strategy:"no-states"};let n=it(t);if(!n)return{state:null,strategy:"no-target"};let s=e.find(a=>it(a.name)===n);if(s)return{state:s,strategy:"exact"};let i={backlog:["backlog"],unstarted:["todo","unstarted","open"],started:["inprogress","started","doing","wip"],completed:["done","completed","closed","resolved","fixed"],canceled:["canceled","cancelled","wontfix","won'tfix"],triage:["triage"]};for(let[a,c]of Object.entries(i)){if(!c.some(d=>it(d)===n))continue;let l=e.find(d=>d.type===a);if(l)return{state:l,strategy:"type-alias"}}let o=e.map(a=>({s:a,score:Gc(t,a.name)})).sort((a,c)=>c.score-a.score);return o[0]&&o[0].score>=.5?{state:o[0].s,strategy:"fuzzy"}:{state:null,strategy:"no-match"}}var Yc=`
|
|
195
|
+
- Node ids look like "1:23" and come from figma_get_file / figma_get_nodes / figma_parse_url output.`,resolve(){let r=ql();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/figma.js","figmaSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"figma_get_me":{let t=await Q("/v1/me");return JSON.stringify({id:t.id,handle:t.handle,email:t.email,imgUrl:t.img_url})}case"figma_get_file":{let t=ye((e||{}).fileKey),{depth:n}=e||{};if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=`/v1/files/${encodeURIComponent(t)}`;if(n!=null){let a=Number(n);!Number.isNaN(a)&&a>0&&(s+=`?depth=${a}`)}let i=await Q(s),o=(i.document?.children||[]).map(a=>({id:a.id,name:a.name,type:a.type,childCount:Array.isArray(a.children)?a.children.length:0,children:(a.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:i.name,lastModified:i.lastModified,version:i.version,editorType:i.editorType,role:i.role,pages:o})}case"figma_get_nodes":{let t=ye((e||{}).fileKey),{ids:n,depth:s}=e||{};if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let i=sr(n);if(!i)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=new URLSearchParams;if(o.set("ids",i),s!=null){let l=Number(s);!Number.isNaN(l)&&l>0&&o.set("depth",String(l))}let a=await Q(`/v1/files/${encodeURIComponent(t)}/nodes?${o.toString()}`),c={};for(let[l,d]of Object.entries(a.nodes||{}))c[l]=d?.document?{id:d.document.id,name:d.document.name,type:d.document.type,document:d.document}:d;return JSON.stringify({name:a.name,nodes:c})}case"figma_get_node_specs":{let t=ye((e||{}).file),{ids:n,depth:s}=e||{};if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let i=sr(n);if(!i)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let o=Number(s);Number.isNaN(o)&&(o=2),o=Math.min(6,Math.max(0,Math.trunc(o)));let a=new URLSearchParams;a.set("ids",i),a.set("depth",String(o));let c=await Q(`/v1/files/${encodeURIComponent(t)}/nodes?${a.toString()}`),l={};for(let[d,p]of Object.entries(c.nodes||{}))l[d]=p&&p.document?Cs(p.document,o):null;return JSON.stringify(l)}case"figma_render_png":{let t=ye((e||{}).fileKey??(e||{}).file),{ids:n,scale:s,format:i,svg_include_id:o,version:a}=e||{};if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let c=sr(n);if(!c)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let l=["png","jpg","svg","pdf"].includes(String(i||"").toLowerCase())?String(i).toLowerCase():"png",d=new URLSearchParams;d.set("ids",c),d.set("format",l);let p;(l==="png"||l==="jpg")&&(p=Number(s),(Number.isNaN(p)||p<=0)&&(p=1),p=Math.min(4,Math.max(.01,p)),d.set("scale",String(p))),l==="svg"&&o!=null&&d.set("svg_include_id",String(!!o)),a&&d.set("version",String(a));let u=await Q(`/v1/images/${encodeURIComponent(t)}?${d.toString()}`);return u.err?JSON.stringify({error:`Figma render error: ${u.err}`}):JSON.stringify({format:l,...p!=null?{scale:p}:{},images:u.images||{}})}case"figma_get_image_fills":{let t=ye((e||{}).file);if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let n=await Q(`/v1/files/${encodeURIComponent(t)}/images`);return JSON.stringify({images:n.meta?.images??n.images??{}})}case"figma_get_file_versions":{let t=ye((e||{}).file);if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let s=((await Q(`/v1/files/${encodeURIComponent(t)}/versions`)).versions||[]).map(i=>({id:i.id,label:i.label,description:i.description,createdAt:i.created_at,user:i.user?.handle}));return JSON.stringify({count:s.length,versions:s})}case"figma_get_comments":{let t=ye((e||{}).fileKey);if(!t)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=((await Q(`/v1/files/${encodeURIComponent(t)}/comments`)).comments||[]).map(i=>({id:i.id,message:i.message,user:i.user?.handle,createdAt:i.created_at,resolvedAt:i.resolved_at||null,parentId:i.parent_id||null}));return JSON.stringify({count:s.length,comments:s})}case"figma_post_comment":{let t=ye((e||{}).file),{message:n,comment_id:s,node_id:i,x:o,y:a}=e||{};if(!t)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});if(!n)return JSON.stringify({error:"message is required"});let c={message:n};s&&(c.comment_id=s),i?c.client_meta={node_id:sr(i),node_offset:{x:o??0,y:a??0}}:(o!=null||a!=null)&&(c.client_meta={x:o??0,y:a??0});let l=await Q(`/v1/files/${encodeURIComponent(t)}/comments`,{method:"POST",body:c});return JSON.stringify({id:l.id,message:l.message,fileKey:t,createdAt:l.created_at,parentId:l.parent_id||null})}case"figma_get_team_projects":{let{team_id:t}=e||{};if(!t)return JSON.stringify({error:"team_id is required"});let n=await Q(`/v1/teams/${encodeURIComponent(t)}/projects`);return JSON.stringify({name:n.name,projects:n.projects||[]})}case"figma_get_project_files":{let{project_id:t,branch_data:n}=e||{};if(!t)return JSON.stringify({error:"project_id is required"});let s=new URLSearchParams;n&&s.set("branch_data","true");let i=s.toString(),o=await Q(`/v1/projects/${encodeURIComponent(t)}/files${i?`?${i}`:""}`);return JSON.stringify({name:o.name,files:o.files||[]})}case"figma_parse_url":{let{url:t}=e||{};return JSON.stringify({file_key:ye(t),node_id:Gl(t)??null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree. Accepts a file key OR a figma.com URL (figma.com/file|design/<key>/... \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes or figma_get_node_specs to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'A file key OR a figma.com URL (e.g. "aBcD1234" or figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch. Accepts URL form ["1-23"] or API form ["1:23"]. A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_get_node_specs",description:"Dev-Mode-style inspection computed from the REST tree: for the given nodes and their children returns size, position, colors (hex), fonts/text-style, spacing/auto-layout, corner radius, strokes and effects \u2014 a compact spec for reproducing a design in code. Prefer this over figma_get_nodes when your job is to build UI from a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to inspect (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},depth:{type:"number",description:"How many levels of children to walk (0-6, default 2)."}},required:["file","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to an image and return the URLs (a map of nodeId \u2192 URL). Despite the name it renders PNG/JPG/SVG/PDF (default png). Use to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},format:{type:"string",enum:["png","jpg","svg","pdf"],description:"Output format (default png)."},scale:{type:"number",description:"Render scale, 0.01\u20134 (raster formats only; default 1). 2 for retina/hi-dpi."},svg_include_id:{type:"boolean",description:"For SVG: include element ids as attributes."},version:{type:"string",description:"Render a specific file version id (from figma_get_file_versions)."}},required:["fileKey","ids"]}},{name:"figma_get_image_fills",description:"Get a map of imageRef \u2192 download URL for every image fill used in a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_file_versions",description:"List a Figma file's saved version history (version id, label, created_at, user). A version id can be passed to figma_render_png to render a past version.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"}},required:["fileKey"]}},{name:"figma_post_comment",description:"Post a comment on a Figma file (WRITE \u2014 needs a PAT with comment-write scope). Optionally reply to a comment (comment_id), pin it to a node (node_id, with optional x/y offset), or pin to a canvas point (x/y).",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},message:{type:"string",description:"The comment text."},comment_id:{type:"string",description:"Optional: reply to this parent comment id."},node_id:{type:"string",description:'Optional: pin the comment to this node ("1-23" or "1:23").'},x:{type:"number",description:"Optional: x position (node offset if node_id given, else canvas point)."},y:{type:"number",description:"Optional: y position (node offset if node_id given, else canvas point)."}},required:["file","message"]}},{name:"figma_get_team_projects",description:"List the projects in a Figma team. Get team_id from a Figma team URL (\u2026/files/team/<TEAM_ID>/\u2026).",input_schema:{type:"object",properties:{team_id:{type:"string",description:"The Figma team id."}},required:["team_id"]}},{name:"figma_get_project_files",description:"List the files in a Figma project (from figma_get_team_projects). Returns file key, name, thumbnail, last_modified.",input_schema:{type:"object",properties:{project_id:{type:"string",description:"The Figma project id."},branch_data:{type:"boolean",description:"Optional: include branch metadata for each file."}},required:["project_id"]}},{name:"figma_parse_url",description:"Local helper (no API call): extract the file key and node id (colon form) from a figma.com file/design URL. Returns { file_key, node_id }.",input_schema:{type:"object",properties:{url:{type:"string",description:"A full figma.com file/design URL."}},required:["url"]}}]};import{existsSync as Kl}from"fs";import{fileURLToPath as Fl}from"url";import{dirname as Hl,resolve as zl}from"path";import{resolveIntegrationToken as Yl}from"@zibby/core/backend-client.js";function Wl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Hl(Fl(import.meta.url)),e=zl(r,"..","bin","mcp-skill.mjs");return Kl(e)?e:null}async function ce(r,e={}){let{token:t}=await Yl("hubspot");if(!t)throw new Error("HubSpot not connected \u2014 Connect HubSpot in Integrations.");let n=r.startsWith("https://")?r:`https://api.hubapi.com${r}`,s={Authorization:`Bearer ${t}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},i=await w(n,{method:e.method||"GET",headers:s,body:e.body?JSON.stringify(e.body):void 0},{kind:"api",what:`HubSpot ${e.method||"GET"} ${r}`});if(!i.ok){let a=await i.text().catch(()=>""),c=i.status===401||i.status===403?" \u2014 token invalid/expired or missing the required Private App scope for this object":"";throw new Error(`HubSpot API ${i.status}${c}: ${a.slice(0,300)}`)}let o=await i.text().catch(()=>"");if(!o)return{};try{return JSON.parse(o)}catch{return{raw:o}}}function Ne(r){return typeof r!="string"?null:r.trim()||null}function Bs(r,e={}){let t=new URLSearchParams;if(r!=null){let s=Array.isArray(r)?r.join(","):String(r);s&&t.set("properties",s)}for(let[s,i]of Object.entries(e))i!=null&&i!==""&&t.set(s,String(i));let n=t.toString();return n?`?${n}`:""}var Qe="The CRM object type \u2014 one of the common values `contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions` (customer feedback: NPS/CSAT/CES), or any custom object name/id.",Ds={id:"hubspot",callsBackend:!0,serverName:"hubspot",allowedTools:["mcp__hubspot__*"],requiresIntegration:I.HUBSPOT,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"HubSpot CRM \u2014 search/read/create/update contacts, companies, deals, tickets, notes and feedback submissions via the HubSpot REST API.",promptFragment:"## HubSpot CRM\nYou have access to the user's HubSpot CRM via the HubSpot REST API (OAuth \u2014 the user connects HubSpot in Integrations; the token is resolved and auto-refreshed for you). The connected app grants the CRM scopes for the objects you touch.\n\nHubSpot's object model is **uniform** \u2014 nearly every tool takes an `objectType` (`contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions`, or a custom object). Records are `{ id, properties }`; you set/read named properties.\n\n**Before you create/update/search, call `hubspot_list_properties` to learn the valid property names for that object type** (they're not guessable). `feedback_submissions` is where NPS/CSAT/CES customer-feedback survey responses live.\n\n### Identity\n- hubspot_whoami: Confirm the token works \u2014 returns the portal (hub) id, account type, time zone, UI domain.\n\n### Schema\n- hubspot_list_properties: List the defined properties (name, label, type, fieldType) for an objectType. Do this first so you use real property names.\n\n### Read\n- hubspot_search: Search an objectType by full-text `query` OR structured `filters` (array of {propertyName, operator, value}). Returns { total, results:[{id, properties}] }.\n- hubspot_get_object: Fetch one record by id (optionally selecting specific properties).\n- hubspot_list_objects: Page through all records of an objectType (limit + after cursor).\n\n### Write\n- hubspot_create_object: Create a record from a `properties` object.\n- hubspot_update_object: Patch a record's `properties` by id.\n- hubspot_create_note: Convenience \u2014 log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket.\n- hubspot_associate: Associate two records (fromType/fromId \u2194 toType/toId) with the default association type.",resolve(){let r=Wl();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/hubspot.js","hubspotSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{let t=e||{};switch(r){case"hubspot_whoami":{let n=await ce("/account-info/v3/details");return JSON.stringify({portalId:n.portalId,accountType:n.accountType,timeZone:n.timeZone,uiDomain:n.uiDomain,companyCurrency:n.companyCurrency})}case"hubspot_list_properties":{let n=Ne(t.objectType);if(!n)return JSON.stringify({error:"objectType is required (e.g. contacts, companies, deals, tickets, feedback_submissions)"});let i=((await ce(`/crm/v3/properties/${encodeURIComponent(n)}`)).results||[]).map(o=>({name:o.name,label:o.label,type:o.type,fieldType:o.fieldType}));return JSON.stringify({objectType:n,count:i.length,properties:i})}case"hubspot_search":{let n=Ne(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let i={limit:Number.isFinite(Number(t.limit))&&Number(t.limit)>0?Math.trunc(Number(t.limit)):20};t.query&&(i.query=String(t.query)),Array.isArray(t.filters)&&t.filters.length&&(i.filterGroups=[{filters:t.filters}]),t.properties!=null&&(i.properties=Array.isArray(t.properties)?t.properties:String(t.properties).split(",").map(a=>a.trim()).filter(Boolean));let o=await ce(`/crm/v3/objects/${encodeURIComponent(n)}/search`,{method:"POST",body:i});return JSON.stringify({total:o.total??(o.results?o.results.length:0),results:(o.results||[]).map(a=>({id:a.id,properties:a.properties}))})}case"hubspot_get_object":{let n=Ne(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!t.id)return JSON.stringify({error:"id is required"});let s=Bs(t.properties,{associations:t.associations}),i=await ce(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(t.id)}${s}`);return JSON.stringify({id:i.id,properties:i.properties,...i.associations?{associations:i.associations}:{}})}case"hubspot_list_objects":{let n=Ne(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});let s=Number.isFinite(Number(t.limit))&&Number(t.limit)>0?Math.trunc(Number(t.limit)):20,i=Bs(t.properties,{limit:s,after:t.after}),o=await ce(`/crm/v3/objects/${encodeURIComponent(n)}${i}`);return JSON.stringify({results:(o.results||[]).map(a=>({id:a.id,properties:a.properties})),paging:o.paging||null})}case"hubspot_create_object":{let n=Ne(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!t.properties||typeof t.properties!="object"||Array.isArray(t.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value } \u2014 call hubspot_list_properties first for valid names)"});let s=await ce(`/crm/v3/objects/${encodeURIComponent(n)}`,{method:"POST",body:{properties:t.properties}});return JSON.stringify({id:s.id,properties:s.properties})}case"hubspot_update_object":{let n=Ne(t.objectType);if(!n)return JSON.stringify({error:"objectType is required"});if(!t.id)return JSON.stringify({error:"id is required"});if(!t.properties||typeof t.properties!="object"||Array.isArray(t.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value })"});let s=await ce(`/crm/v3/objects/${encodeURIComponent(n)}/${encodeURIComponent(t.id)}`,{method:"PATCH",body:{properties:t.properties}});return JSON.stringify({id:s.id,properties:s.properties})}case"hubspot_create_note":{if(!t.body||typeof t.body!="string")return JSON.stringify({error:"body is required (the note text)"});let n=typeof t.timestamp=="string"&&t.timestamp?t.timestamp:null;if(!n)try{n=new Date().toISOString()}catch{n=null}if(!n)return JSON.stringify({error:"timestamp is required (pass an ISO 8601 string, e.g. 2026-01-01T00:00:00.000Z)"});let s=await ce("/crm/v3/objects/notes",{method:"POST",body:{properties:{hs_note_body:t.body,hs_timestamp:n}}}),i=s.id,o=[["contacts",t.contactId],["companies",t.companyId],["deals",t.dealId],["tickets",t.ticketId]].filter(([,c])=>c!=null&&c!==""),a=[];for(let[c,l]of o)try{await ce(`/crm/v4/objects/notes/${encodeURIComponent(i)}/associations/default/${c}/${encodeURIComponent(l)}`,{method:"PUT"}),a.push({toType:c,toId:String(l)})}catch(d){a.push({toType:c,toId:String(l),error:d.message})}return JSON.stringify({id:i,properties:s.properties,associatedTo:a})}case"hubspot_associate":{let n=Ne(t.fromType),s=Ne(t.toType);return!n||!t.fromId||!s||!t.toId?JSON.stringify({error:"fromType, fromId, toType and toId are all required"}):(await ce(`/crm/v4/objects/${encodeURIComponent(n)}/${encodeURIComponent(t.fromId)}/associations/default/${encodeURIComponent(s)}/${encodeURIComponent(t.toId)}`,{method:"PUT"}),JSON.stringify({ok:!0}))}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"hubspot_whoami",description:"Confirm the HubSpot token works: returns the portal (hub) id, account type, time zone and UI domain.",input_schema:{type:"object",properties:{}}},{name:"hubspot_list_properties",description:"List the defined properties (name, label, type, fieldType) for a CRM object type. Call this FIRST so you use valid property names when creating/updating/searching.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Qe}},required:["objectType"]}},{name:"hubspot_search",description:"Search a CRM object type. Pass a full-text `query` OR structured `filters` (array of {propertyName, operator, value}, e.g. operator EQ/CONTAINS_TOKEN/GT/\u2026). Returns { total, results:[{id, properties}] }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Qe},query:{type:"string",description:"Optional full-text search string."},filters:{type:"array",description:"Optional structured filters (ANDed). Each: { propertyName, operator, value }. Operators: EQ, NEQ, LT, LTE, GT, GTE, CONTAINS_TOKEN, HAS_PROPERTY, IN, \u2026",items:{type:"object",properties:{propertyName:{type:"string"},operator:{type:"string"},value:{type:"string"}}}},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each result."},limit:{type:"number",description:"Max results (default 20)."}},required:["objectType"]}},{name:"hubspot_get_object",description:"Fetch one CRM record by id. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Qe},id:{type:"string",description:"The record id."},properties:{type:"array",items:{type:"string"},description:"Optional: specific property names to return."},associations:{type:"string",description:'Optional: comma-separated object types to also return associations for (e.g. "companies,deals").'}},required:["objectType","id"]}},{name:"hubspot_list_objects",description:"Page through records of a CRM object type. Returns { results, paging } \u2014 pass paging.next.after back as `after` for the next page.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Qe},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each record."},limit:{type:"number",description:"Page size (default 20)."},after:{type:"string",description:"Optional paging cursor from a previous response (paging.next.after)."}},required:["objectType"]}},{name:"hubspot_create_object",description:"Create a CRM record. Pass `properties` as an object of { propertyName: value } (call hubspot_list_properties first for valid names). Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Qe},properties:{type:"object",description:"Object of { propertyName: value } to set on the new record."}},required:["objectType","properties"]}},{name:"hubspot_update_object",description:"Update (PATCH) a CRM record by id. Pass `properties` as an object of { propertyName: value }. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:Qe},id:{type:"string",description:"The record id to update."},properties:{type:"object",description:"Object of { propertyName: value } to change."}},required:["objectType","id","properties"]}},{name:"hubspot_create_note",description:"Log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket. Returns { id, associatedTo }.",input_schema:{type:"object",properties:{body:{type:"string",description:"The note text (stored as hs_note_body)."},contactId:{type:"string",description:"Optional: associate the note to this contact id."},companyId:{type:"string",description:"Optional: associate the note to this company id."},dealId:{type:"string",description:"Optional: associate the note to this deal id."},ticketId:{type:"string",description:"Optional: associate the note to this ticket id."},timestamp:{type:"string",description:"Optional ISO 8601 timestamp for the note (defaults to now)."}},required:["body"]}},{name:"hubspot_associate",description:"Associate two CRM records with the default association type (e.g. a contact to a company). Returns { ok:true }.",input_schema:{type:"object",properties:{fromType:{type:"string",description:"Source object type (e.g. contacts)."},fromId:{type:"string",description:"Source record id."},toType:{type:"string",description:"Target object type (e.g. companies)."},toId:{type:"string",description:"Target record id."}},required:["fromType","fromId","toType","toId"]}}]};import{existsSync as Zl}from"fs";import{fileURLToPath as Vl}from"url";import{dirname as Xl,resolve as Ql}from"path";function ed(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Xl(Vl(import.meta.url)),e=Ql(r,"..","bin","mcp-skill.mjs");return Zl(e)?e:null}var td=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function rd(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let r=process.env.LINEAR_API_KEY;if(!r)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return r}async function ee(r,e={}){let t=await w(td,{method:"POST",headers:{Authorization:rd(),"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:e})},{kind:"api",what:"Linear GraphQL"});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Linear API ${t.status}: ${s.slice(0,300)}`)}let n=await t.json().catch(()=>null);if(!n)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(n.errors)&&n.errors.length){let s=n.errors.map(i=>i?.message||String(i)).join("; ");throw new Error(`Linear GraphQL error: ${s.slice(0,300)}`)}return n.data}function bt(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function nd(r,e){let t=bt(r),n=bt(e);if(!t||!n)return 0;if(t===n)return 1;if(t.length===1||n.length===1)return t===n?1:0;let s=d=>{let p=new Map;for(let u=0;u<d.length-1;u++){let m=d.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},i=s(t),o=s(n),a=0,c=0,l=0;for(let d of i.values())c+=d;for(let d of o.values())l+=d;for(let[d,p]of i.entries())a+=Math.min(p,o.get(d)||0);return 2*a/Math.max(1,c+l)}function sd(r,e){let t=Array.isArray(r)?r:[];if(!t.length)return{state:null,strategy:"no-states"};let n=bt(e);if(!n)return{state:null,strategy:"no-target"};let s=t.find(a=>bt(a.name)===n);if(s)return{state:s,strategy:"exact"};let i={backlog:["backlog"],unstarted:["todo","unstarted","open"],started:["inprogress","started","doing","wip"],completed:["done","completed","closed","resolved","fixed"],canceled:["canceled","cancelled","wontfix","won'tfix"],triage:["triage"]};for(let[a,c]of Object.entries(i)){if(!c.some(d=>bt(d)===n))continue;let l=t.find(d=>d.type===a);if(l)return{state:l,strategy:"type-alias"}}let o=t.map(a=>({s:a,score:nd(e,a.name)})).sort((a,c)=>c.score-a.score);return o[0]&&o[0].score>=.5?{state:o[0].s,strategy:"fuzzy"}:{state:null,strategy:"no-match"}}var id=`
|
|
193
196
|
id
|
|
194
197
|
identifier
|
|
195
198
|
number
|
|
@@ -203,7 +206,7 @@ You have access to the user's Figma files via the Figma REST API. Every tool tha
|
|
|
203
206
|
assignee { id name displayName email }
|
|
204
207
|
labels { nodes { id name color } }
|
|
205
208
|
team { id key name }
|
|
206
|
-
`,
|
|
209
|
+
`,Js={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:I.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear
|
|
207
210
|
You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
208
211
|
|
|
209
212
|
### Discovery
|
|
@@ -221,32 +224,32 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
|
221
224
|
|
|
222
225
|
### Notes
|
|
223
226
|
- Always resolve a team first when you need states or want to create/move issues by state name \u2014 states only make sense within their team.
|
|
224
|
-
- Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let r={};for(let
|
|
227
|
+
- Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let r={};for(let t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);process.env.LINEAR_API_URL&&(r.LINEAR_API_URL=process.env.LINEAR_API_URL);let e=ed();return e?{type:"stdio",command:"node",args:[e,"../dist/linear.js","linearSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,e){try{switch(r){case"linear_list_teams":{let n=(await ee(`
|
|
225
228
|
query Teams($first: Int) {
|
|
226
229
|
teams(first: $first) {
|
|
227
230
|
nodes { id key name description }
|
|
228
231
|
}
|
|
229
232
|
}
|
|
230
|
-
`,{first:
|
|
233
|
+
`,{first:e?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:n.length,teams:n})}case"linear_list_states":{let{teamId:t,teamKey:n}=e||{},s=t;if(!s&&n&&(s=await Ms(n)),s){let c=(await ee(`
|
|
231
234
|
query States($teamId: String!) {
|
|
232
235
|
team(id: $teamId) {
|
|
233
236
|
id key name
|
|
234
237
|
states { nodes { id name type color position } }
|
|
235
238
|
}
|
|
236
239
|
}
|
|
237
|
-
`,{teamId:s}))?.team,l=(c?.states?.nodes||[]).slice().sort((d,p)=>(d.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:l.length,states:l})}let o=(await
|
|
240
|
+
`,{teamId:s}))?.team,l=(c?.states?.nodes||[]).slice().sort((d,p)=>(d.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:l.length,states:l})}let o=(await ee(`
|
|
238
241
|
query AllStates($first: Int) {
|
|
239
242
|
workflowStates(first: $first) {
|
|
240
243
|
nodes { id name type color team { id key name } }
|
|
241
244
|
}
|
|
242
245
|
}
|
|
243
|
-
`,{first:
|
|
246
|
+
`,{first:e?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:t}=e||{},s=(await ee(`
|
|
244
247
|
query Labels($first: Int, $filter: IssueLabelFilter) {
|
|
245
248
|
issueLabels(first: $first, filter: $filter) {
|
|
246
249
|
nodes { id name color team { id key } }
|
|
247
250
|
}
|
|
248
251
|
}
|
|
249
|
-
`,{first:
|
|
252
|
+
`,{first:e?.limit||100,filter:t?{team:{id:{eq:t}}}:void 0}))?.issueLabels?.nodes||[];return JSON.stringify({count:s.length,labels:s})}case"linear_list_issues":{let{teamId:t,teamKey:n,stateId:s,stateName:i,label:o,assigneeId:a,updatedAfter:c,limit:l}=e||{},d={},p=t;!p&&n&&(p=await Ms(n)),p&&(d.team={id:{eq:p}}),s?d.state={id:{eq:s}}:i&&(d.state={name:{eqIgnoreCase:i}}),o&&(d.labels={name:{eqIgnoreCase:o}}),a&&(d.assignee={id:{eq:a}}),c&&(d.updatedAt={gt:c});let m=((await ee(`
|
|
250
253
|
query Issues($first: Int, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
|
|
251
254
|
issues(first: $first, filter: $filter, orderBy: $orderBy) {
|
|
252
255
|
nodes {
|
|
@@ -258,56 +261,51 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
|
258
261
|
}
|
|
259
262
|
}
|
|
260
263
|
}
|
|
261
|
-
`,{first:l||30,filter:Object.keys(d).length?d:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(h=>({id:h.id,identifier:h.identifier,number:h.number,title:h.title,url:h.url,priority:h.priority,state:h.state?.name,stateType:h.state?.type,assignee:h.assignee?.displayName||null,labels:(h.labels?.nodes||[]).map(
|
|
264
|
+
`,{first:l||30,filter:Object.keys(d).length?d:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(h=>({id:h.id,identifier:h.identifier,number:h.number,title:h.title,url:h.url,priority:h.priority,state:h.state?.name,stateType:h.state?.type,assignee:h.assignee?.displayName||null,labels:(h.labels?.nodes||[]).map(y=>y.name),team:h.team?.key,createdAt:h.createdAt,updatedAt:h.updatedAt}));return JSON.stringify({count:m.length,issues:m})}case"linear_get_issue":{let t=e?.issueId||e?.identifier||e?.issueKey;if(!t)return JSON.stringify({error:"issueId or identifier is required"});let n=await gt(t);return JSON.stringify(n?{id:n.id,identifier:n.identifier,number:n.number,title:n.title,description:n.description||"",url:n.url,priority:n.priority,state:n.state?.name,stateId:n.state?.id,stateType:n.state?.type,assignee:n.assignee?.displayName||n.assignee?.name||null,assigneeId:n.assignee?.id||null,labels:(n.labels?.nodes||[]).map(s=>s.name),team:n.team?{id:n.team.id,key:n.team.key,name:n.team.name}:null,createdAt:n.createdAt,updatedAt:n.updatedAt}:{error:`Issue not found: ${t}`})}case"linear_get_comments":{let t=e?.issueId||e?.identifier||e?.issueKey;if(!t)return JSON.stringify({error:"issueId or identifier is required"});let n=await gt(t,`
|
|
262
265
|
id identifier
|
|
263
|
-
comments(first: ${Number(
|
|
266
|
+
comments(first: ${Number(e?.limit)||50}) {
|
|
264
267
|
nodes { id body createdAt updatedAt user { id name displayName } }
|
|
265
268
|
}
|
|
266
|
-
`);if(!n)return JSON.stringify({error:`Issue not found: ${
|
|
269
|
+
`);if(!n)return JSON.stringify({error:`Issue not found: ${t}`});let s=(n.comments?.nodes||[]).map(i=>({id:i.id,author:i.user?.displayName||i.user?.name||"Unknown",body:i.body||"",createdAt:i.createdAt,updatedAt:i.updatedAt})).sort((i,o)=>String(o.createdAt).localeCompare(String(i.createdAt)));return JSON.stringify({count:s.length,issue:n.identifier,comments:s})}case"linear_add_comment":{let t=e?.issueId||e?.identifier||e?.issueKey,n=e?.body;if(!t||!n)return JSON.stringify({error:"issueId/identifier and body are required"});let s=await gt(t,"id identifier");if(!s)return JSON.stringify({error:`Issue not found: ${t}`});let o=(await ee(`
|
|
267
270
|
mutation AddComment($input: CommentCreateInput!) {
|
|
268
271
|
commentCreate(input: $input) {
|
|
269
272
|
success
|
|
270
273
|
comment { id url createdAt }
|
|
271
274
|
}
|
|
272
275
|
}
|
|
273
|
-
`,{input:{issueId:s.id,body:n}}))?.commentCreate;return JSON.stringify({ok:!!o?.success,commentId:o?.comment?.id,url:o?.comment?.url})}case"linear_update_state":{let e
|
|
276
|
+
`,{input:{issueId:s.id,body:n}}))?.commentCreate;return JSON.stringify({ok:!!o?.success,commentId:o?.comment?.id,url:o?.comment?.url})}case"linear_update_state":{let t=e?.issueId||e?.identifier||e?.issueKey,{stateId:n,stateName:s,toStatus:i,status:o}=e||{};if(!t)return JSON.stringify({error:"issueId or identifier is required"});let a=await gt(t,`
|
|
274
277
|
id identifier
|
|
275
278
|
state { id name type }
|
|
276
279
|
team { id key states { nodes { id name type position } } }
|
|
277
|
-
`);if(!a)return JSON.stringify({error:`Issue not found: ${
|
|
280
|
+
`);if(!a)return JSON.stringify({error:`Issue not found: ${t}`});let c=n,l=n?{strategy:"explicit-id"}:null;if(!c){let u=String(s||i||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((y,_)=>(y.position||0)-(_.position||0));if(!u)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:m.map(y=>({id:y.id,name:y.name,type:y.type}))});let h=sd(m,u);if(!h.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${u}" in team ${a.team?.key}`,issue:a.identifier,availableStates:m.map(y=>({id:y.id,name:y.name,type:y.type}))});c=h.state.id,l={strategy:h.strategy,matchedName:h.state.name}}let p=(await ee(`
|
|
278
281
|
mutation MoveIssue($id: String!, $input: IssueUpdateInput!) {
|
|
279
282
|
issueUpdate(id: $id, input: $input) {
|
|
280
283
|
success
|
|
281
284
|
issue { id identifier state { id name type } }
|
|
282
285
|
}
|
|
283
286
|
}
|
|
284
|
-
`,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!p?.success,issue:p?.issue?.identifier||a.identifier,stateAfter:p?.issue?.state?.name||null,stateTypeAfter:p?.issue?.state?.type||null,resolution:l})}case"linear_link_attachment":{let e
|
|
287
|
+
`,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!p?.success,issue:p?.issue?.identifier||a.identifier,stateAfter:p?.issue?.state?.name||null,stateTypeAfter:p?.issue?.state?.type||null,resolution:l})}case"linear_link_attachment":{let t=e?.issueId||e?.identifier||e?.issueKey,{url:n,title:s,subtitle:i}=e||{};if(!t||!n)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await gt(t,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${t}`});let c=(await ee(`
|
|
285
288
|
mutation LinkAttachment($input: AttachmentCreateInput!) {
|
|
286
289
|
attachmentCreate(input: $input) {
|
|
287
290
|
success
|
|
288
291
|
attachment { id url title }
|
|
289
292
|
}
|
|
290
293
|
}
|
|
291
|
-
`,{input:{issueId:o.id,url:n,title:s||n,subtitle:i||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(
|
|
294
|
+
`,{input:{issueId:o.id,url:n,title:s||n,subtitle:i||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"linear_list_teams",description:"List Linear teams (id, key, name). Needed to scope workflow states and issue queries.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Max teams (default: 50)"}}}},{name:"linear_list_states",description:"List a team's workflow states (id, name, type: backlog|unstarted|started|completed|canceled|triage). Linear states are PER-TEAM. Omit team to list all states across the workspace.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved to an id if teamId omitted"},limit:{type:"number",description:"Max states when listing workspace-wide (default: 200)"}}}},{name:"linear_list_labels",description:"List issue labels, optionally scoped to a team.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Optional team uuid to scope labels"},limit:{type:"number",description:"Max labels (default: 100)"}}}},{name:"linear_list_issues",description:"List/poll Linear issues filtered by team, state, label, assignee, and an updatedAfter cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved if teamId omitted"},stateId:{type:"string",description:"Filter by workflow state uuid"},stateName:{type:"string",description:"Filter by state name (case-insensitive)"},label:{type:"string",description:"Filter by label name (case-insensitive)"},assigneeId:{type:"string",description:"Filter by assignee uuid"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},limit:{type:"number",description:"Max issues (default: 30)"}}}},{name:"linear_get_issue",description:"Get a single Linear issue by identifier (e.g. ENG-123) or internal uuid \u2014 title, description, state, labels, assignee, url.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"}}}},{name:"linear_get_comments",description:"Get comments on a Linear issue (newest first).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},limit:{type:"number",description:"Max comments (default: 50)"}}}},{name:"linear_add_comment",description:"Add a comment to a Linear issue (markdown supported).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},body:{type:"string",description:"Comment body (markdown)"}},required:["body"]}},{name:"linear_update_state",description:"Move a Linear issue to a different workflow state. Pass a state NAME (toStatus/stateName) and the tool resolves it to the issue's team's matching state id (exact -> type-alias -> fuzzy), or pass stateId directly. Linear has no transitions \u2014 this sets the state.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},stateId:{type:"string",description:"Target workflow state uuid (skips name resolution)"},stateName:{type:"string",description:'Target state name (e.g. "In Progress", "Done")'},toStatus:{type:"string",description:"Alias for stateName"}}}},{name:"linear_link_attachment",description:"Attach a URL (e.g. a GitHub PR) to a Linear issue via native attachments. Use this for PR links; fall back to linear_add_comment if it fails.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},url:{type:"string",description:"The URL to attach (e.g. a PR link)"},title:{type:"string",description:"Attachment title (defaults to the URL)"},subtitle:{type:"string",description:"Optional attachment subtitle"}},required:["url"]}}]};async function Ms(r){return(await ee(`
|
|
292
295
|
query TeamByKey($filter: TeamFilter) {
|
|
293
296
|
teams(first: 1, filter: $filter) { nodes { id key } }
|
|
294
297
|
}
|
|
295
|
-
`,{filter:{key:{eq:r}}}))?.teams?.nodes?.[0]?.id||null}async function
|
|
298
|
+
`,{filter:{key:{eq:r}}}))?.teams?.nodes?.[0]?.id||null}async function gt(r,e=id){let t=String(r).trim(),n=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(t);if(n){let i=n[1].toUpperCase(),o=Number(n[2]);return(await ee(`
|
|
296
299
|
query IssueByIdentifier($filter: IssueFilter) {
|
|
297
300
|
issues(first: 1, filter: $filter) {
|
|
298
|
-
nodes { ${
|
|
301
|
+
nodes { ${e} }
|
|
299
302
|
}
|
|
300
303
|
}
|
|
301
|
-
`,{filter:{number:{eq:o},team:{key:{eq:i}}}}))?.issues?.nodes?.[0]||null}return(await
|
|
304
|
+
`,{filter:{number:{eq:o},team:{key:{eq:i}}}}))?.issues?.nodes?.[0]||null}return(await ee(`
|
|
302
305
|
query IssueById($id: String!) {
|
|
303
|
-
issue(id: $id) { ${
|
|
306
|
+
issue(id: $id) { ${e} }
|
|
304
307
|
}
|
|
305
|
-
`,{id:
|
|
306
|
-
`).replace(/<\/p>/gi,`
|
|
307
|
-
|
|
308
|
-
`).replace(/<[^>]+>/g,"").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/\n{3,}/g,`
|
|
309
|
-
|
|
310
|
-
`).trim()}function rs(r){if(r==null||r==="")return null;if(typeof r=="number"&&Number.isFinite(r))return Math.max(0,Math.min(5,Math.round(r)));let t=String(r).trim().toLowerCase(),e={unset:0,none:0,low:1,medium:2,normal:2,high:3,urgent:4,now:5,critical:5,blocker:5,do_now:5,"do now":5};return Object.prototype.hasOwnProperty.call(e,t)?e[t]:null}function qt(r,t){return r?{id:String(r.id),identifier:r.identifier||null,projectId:r.project_id??null,title:r.title||"",description:ss(r.description),done:!!r.done,priority:r.priority??0,labels:(Array.isArray(r.labels)?r.labels:[]).map(e=>e?.title).filter(Boolean),assignees:(Array.isArray(r.assignees)?r.assignees:[]).map(e=>e?.username).filter(Boolean),dueDate:r.due_date&&!String(r.due_date).startsWith("0001-")?r.due_date:null,url:t?`${t}/tasks/${r.id}`:void 0}:null}async function Ft(r,{create:t=!1}={}){let e=String(r||"").trim();if(!e)return null;let n=await $("GET","/labels",{query:{s:e}}),s=(Array.isArray(n)?n:[]).find(o=>(o?.title||"").trim().toLowerCase()===e.toLowerCase());return s?.id?s.id:t?(await $("PUT","/labels",{body:{title:e}}))?.id??null:null}async function ns(r){let t=encodeURIComponent(String(r)),e=await $("GET",`/projects/${t}/views`),n=(Array.isArray(e)?e:[]).find(i=>i?.view_kind==="kanban");if(!n?.id)throw new Error(`Project ${r} has no kanban view \u2014 there are no columns to move between.`);let s=await $("GET",`/projects/${t}/views/${n.id}/buckets`);return{viewId:n.id,buckets:Array.isArray(s)?s:[]}}var is={id:"vikunja",serverName:"vikunja",allowedTools:["mcp__vikunja__*"],requiresIntegration:S.VIKUNJA,callsBackend:!0,envKeys:["VIKUNJA_URL","VIKUNJA_TOKEN"],description:"Vikunja \u2014 kanban board: tasks, columns, labels, comments (API token)",promptFragment:`## Vikunja
|
|
308
|
+
`,{id:t}))?.issue||null}import{existsSync as od}from"fs";import{fileURLToPath as ad}from"url";import{dirname as cd,resolve as ld}from"path";import{resolveIntegrationToken as dd}from"@zibby/core/backend-client.js";function pd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=cd(ad(import.meta.url)),e=ld(r,"..","bin","mcp-skill.mjs");return od(e)?e:null}function qs(r){return String(r||"").trim().replace(/\/+$/,"").replace(/\/api\/v1$/,"")}var et=null;async function _t(){if(et)return et;let r=qs(process.env.VIKUNJA_URL),e=(process.env.VIKUNJA_TOKEN||"").trim();try{let t=await dd("vikunja"),n=String(t?.token||"").trim(),s=qs(t?.instanceUrl);if(n&&s)return et={origin:s,token:n},et;if(n&&!s)throw new Error("The connected Vikunja integration has no instance URL \u2014 reconnect it in Integrations \u2192 Vikunja.")}catch(t){if(!(r&&e))throw t}if(!(r&&e))throw new Error("No Vikunja credentials. Connect the board under Integrations \u2192 Vikunja (instance URL + an API token minted in the board's Settings \u2192 API Tokens).");return et={origin:r,token:e},et}async function C(r,e,t={}){let{origin:n,token:s}=await _t(),i=`${n}/api/v1${e}`;if(t.query&&Object.keys(t.query).length){let c=new URLSearchParams;for(let[d,p]of Object.entries(t.query))p!=null&&p!==""&&c.set(d,String(p));let l=c.toString();l&&(i+=`?${l}`)}let o=await w(i,{method:r,headers:{Authorization:`Bearer ${s}`,...t.body?{"Content-Type":"application/json"}:{}},...t.body?{body:JSON.stringify(t.body)}:{}},{kind:"api",what:`Vikunja ${r} ${e}`}),a=await o.text();if(!o.ok)throw new Error(`Vikunja ${r} ${e} \u2192 ${o.status}: ${a.slice(0,300)}`);if(!a)return null;try{return JSON.parse(a)}catch{return a}}function Fs(r){return typeof r!="string"||!r?"":_s(r)}function en(r){return gs(r)}function Gs(r){if(r==null||r==="")return null;if(typeof r=="number"&&Number.isFinite(r))return Math.max(0,Math.min(5,Math.round(r)));let e=String(r).trim().toLowerCase(),t={unset:0,none:0,low:1,medium:2,normal:2,high:3,urgent:4,now:5,critical:5,blocker:5,do_now:5,"do now":5};return Object.prototype.hasOwnProperty.call(t,e)?t[e]:null}function ir(r,e){return r?{id:String(r.id),identifier:r.identifier||null,projectId:r.project_id??null,title:r.title||"",description:Fs(r.description),done:!!r.done,priority:r.priority??0,labels:(Array.isArray(r.labels)?r.labels:[]).map(t=>t?.title).filter(Boolean),assignees:(Array.isArray(r.assignees)?r.assignees:[]).map(t=>t?.username).filter(Boolean),dueDate:r.due_date&&!String(r.due_date).startsWith("0001-")?r.due_date:null,url:e?`${e}/tasks/${r.id}`:void 0}:null}async function or(r,{create:e=!1}={}){let t=String(r||"").trim();if(!t)return null;let n=await C("GET","/labels",{query:{s:t}}),s=(Array.isArray(n)?n:[]).find(o=>(o?.title||"").trim().toLowerCase()===t.toLowerCase());return s?.id?s.id:e?(await C("PUT","/labels",{body:{title:t}}))?.id??null:null}async function Ks(r){let e=encodeURIComponent(String(r)),t=await C("GET",`/projects/${e}/views`),n=(Array.isArray(t)?t:[]).find(i=>i?.view_kind==="kanban");if(!n?.id)throw new Error(`Project ${r} has no kanban view \u2014 there are no columns to move between.`);let s=await C("GET",`/projects/${e}/views/${n.id}/buckets`);return{viewId:n.id,buckets:Array.isArray(s)?s:[]}}var Hs={id:"vikunja",serverName:"vikunja",allowedTools:["mcp__vikunja__*"],requiresIntegration:I.VIKUNJA,callsBackend:!0,envKeys:["VIKUNJA_URL","VIKUNJA_TOKEN"],description:"Vikunja \u2014 kanban board: tasks, columns, labels, comments (API token)",promptFragment:`## Vikunja
|
|
311
309
|
You can operate the user's Vikunja board directly. Tools:
|
|
312
310
|
|
|
313
311
|
### Discovery
|
|
@@ -328,13 +326,13 @@ You can operate the user's Vikunja board directly. Tools:
|
|
|
328
326
|
### Notes
|
|
329
327
|
- Address tasks by their NUMERIC id. The '#1' identifier shown in the UI is per-project and not unique.
|
|
330
328
|
- Descriptions may come back as plain text converted from HTML \u2014 that is expected.
|
|
331
|
-
- Priority accepts a number 0-5 or a word: low, medium, high, urgent, now.`,resolve(){let r={};for(let
|
|
329
|
+
- Priority accepts a number 0-5 or a word: low, medium, high, urgent, now.`,resolve(){let r={};for(let t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);let e=pd();return e?{type:"stdio",command:"node",args:[e,"../dist/vikunja.js","vikunjaSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,e){try{let t=e||{};switch(r){case"vikunja_list_projects":{let n=await C("GET","/projects"),s=(Array.isArray(n)?n:[]).map(i=>({id:String(i.id),title:i.title||"",description:Fs(i.description)}));return JSON.stringify({count:s.length,projects:s})}case"vikunja_list_buckets":{let{viewId:n,buckets:s}=await Ks(t.projectId);return JSON.stringify({viewId:n,count:s.length,buckets:s.map(i=>({id:i.id,title:i.title,taskCount:i.count??null}))})}case"vikunja_list_labels":{let n=await C("GET","/labels",{query:{s:t.search}}),s=(Array.isArray(n)?n:[]).map(i=>({id:i.id,title:i.title}));return JSON.stringify({count:s.length,labels:s})}case"vikunja_list_tasks":{let{origin:n}=await _t(),s=[];if(t.label){let a=await or(t.label);if(!a)return JSON.stringify({count:0,tasks:[],note:`No label named "${t.label}" exists.`});s.push(`labels in ${a}`)}(t.done===!0||t.done===!1)&&s.push(`done = ${t.done}`);let i=await C("GET",`/projects/${encodeURIComponent(String(t.projectId))}/tasks`,{query:{...s.length?{filter:s.join(" && ")}:{},sort_by:"updated",order_by:"desc",per_page:Math.min(Number(t.limit)||25,50)}}),o=(Array.isArray(i)?i:[]).map(a=>ir(a,n));return JSON.stringify({count:o.length,tasks:o})}case"vikunja_get_task":{let{origin:n}=await _t(),s=await C("GET",`/tasks/${encodeURIComponent(String(t.taskId))}`);return JSON.stringify({task:ir(s,n)})}case"vikunja_create_task":{let{origin:n}=await _t(),s=Gs(t.priority),i=await C("PUT",`/projects/${encodeURIComponent(String(t.projectId))}/tasks`,{body:{title:t.title,...t.description?{description:en(t.description)}:{},...s!==null?{priority:s}:{},...t.dueDate?{due_date:t.dueDate}:{}}});if(!i?.id)throw new Error("Vikunja created no task (no id in the response)");let o=[];for(let c of Array.isArray(t.labels)?t.labels:[])try{let l=await or(c,{create:!0});l&&await C("PUT",`/tasks/${i.id}/labels`,{body:{label_id:l}})}catch(l){o.push(`${c}: ${l?.message||l}`)}let a=await C("GET",`/tasks/${i.id}`);return JSON.stringify({created:ir(a||i,n),...o.length?{labelErrors:o}:{}})}case"vikunja_update_task":{let{origin:n}=await _t(),s=encodeURIComponent(String(t.taskId)),i=await C("GET",`/tasks/${s}`);if(!i?.id)throw new Error(`No task ${t.taskId}`);let o=Gs(t.priority),a=await C("POST",`/tasks/${s}`,{body:{...i,...t.title!==void 0?{title:t.title}:{},...t.description!==void 0?{description:en(t.description)}:{},...o!==null?{priority:o}:{},...t.done!==void 0?{done:!!t.done}:{},...t.dueDate!==void 0?{due_date:t.dueDate}:{}}});return JSON.stringify({updated:ir(a,n)})}case"vikunja_move_task":{let n=await C("GET",`/tasks/${encodeURIComponent(String(t.taskId))}`);if(!n?.id)throw new Error(`No task ${t.taskId}`);let s=t.projectId??n.project_id,i=String(t.column||"").trim().toLowerCase();if(!i)throw new Error("No target column given.");let{viewId:o,buckets:a}=await Ks(s),c=a.find(l=>(l?.title||"").trim().toLowerCase()===i);return c?.id?(await C("POST",`/projects/${encodeURIComponent(String(s))}/views/${o}/buckets/${c.id}/tasks`,{body:{task_id:Number(n.id)}}),JSON.stringify({moved:!0,taskId:String(n.id),column:c.title})):JSON.stringify({moved:!1,error:`No column named "${t.column}".`,availableColumns:a.map(l=>l.title)})}case"vikunja_add_label":{let n=await or(t.label,{create:t.create!==!1});return n?(await C("PUT",`/tasks/${encodeURIComponent(String(t.taskId))}/labels`,{body:{label_id:n}}),JSON.stringify({ok:!0,taskId:String(t.taskId),label:t.label})):JSON.stringify({ok:!1,error:`No label named "${t.label}" and creating it was declined.`})}case"vikunja_remove_label":{let n=await or(t.label);return n?(await C("DELETE",`/tasks/${encodeURIComponent(String(t.taskId))}/labels/${n}`),JSON.stringify({ok:!0,taskId:String(t.taskId),label:t.label})):JSON.stringify({ok:!1,error:`No label named "${t.label}".`})}case"vikunja_add_comment":{let n=await C("PUT",`/tasks/${encodeURIComponent(String(t.taskId))}/comments`,{body:{comment:en(t.comment)}});return JSON.stringify({ok:!0,commentId:n?.id??null})}case"vikunja_assign":{let n=await C("GET","/users",{query:{s:t.username}}),s=(Array.isArray(n)?n:[]).find(i=>(i?.username||"").toLowerCase()===String(t.username||"").toLowerCase());return s?.id?(await C("PUT",`/tasks/${encodeURIComponent(String(t.taskId))}/assignees`,{body:{user_id:s.id}}),JSON.stringify({ok:!0,taskId:String(t.taskId),assignee:s.username})):JSON.stringify({ok:!1,error:`No user "${t.username}".`})}default:return JSON.stringify({error:`Unknown vikunja tool: ${r}`})}}catch(t){return JSON.stringify({error:t?.message||String(t)})}},tools:[{name:"vikunja_list_projects",description:"List Vikunja projects/boards (id, title). Everything else is project-scoped \u2014 start here when you do not already have a project id.",input_schema:{type:"object",properties:{}}},{name:"vikunja_list_buckets",description:"List a project's kanban COLUMNS (bucket id + title). Call this before moving a card so you use a column that exists.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project id"}},required:["projectId"]}},{name:"vikunja_list_labels",description:"List labels (id, title). Optionally narrow with a search string.",input_schema:{type:"object",properties:{search:{type:"string",description:"Optional server-side search on the label title"}}}},{name:"vikunja_list_tasks",description:"List a project's tasks, newest-updated first. Optionally filter by label title and/or done-state.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project id"},label:{type:"string",description:"Only tasks carrying this label title"},done:{type:"boolean",description:"Filter on completion state"},limit:{type:"number",description:"Max tasks (default 25, max 50)"}},required:["projectId"]}},{name:"vikunja_get_task",description:'Get one task by its NUMERIC id (the "#1" identifier shown in the UI is per-project and not unique).',input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"}},required:["taskId"]}},{name:"vikunja_create_task",description:"Create a task in a project. Labels are attached after creation and fail soft \u2014 the task survives a label error.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project id"},title:{type:"string",description:"Task title"},description:{type:"string",description:"Task body. Markdown is rendered (headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes)."},priority:{type:"string",description:"A number 0-5 or a word: low, medium, high, urgent, now"},labels:{type:"array",items:{type:"string"},description:"Label titles; created if missing"},dueDate:{type:"string",description:"RFC3339 timestamp"}},required:["projectId","title"]}},{name:"vikunja_update_task",description:"Change a task's title, description, priority, due date, or done state. To move it to another COLUMN use vikunja_move_task \u2014 a column is not a field on the task.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},title:{type:"string"},description:{type:"string"},priority:{type:"string",description:"A number 0-5 or a word: low, medium, high, urgent, now"},done:{type:"boolean"},dueDate:{type:"string",description:"RFC3339 timestamp"}},required:["taskId"]}},{name:"vikunja_move_task",description:`Move a card to a kanban COLUMN by name (e.g. "Doing"). Vikunja has no task.status: a column is a bucket on the project's kanban view, so this resolves the view and puts the task in the matching bucket. Returns the available column names when the name does not match.`,input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},column:{type:"string",description:"Target column (bucket) title"},projectId:{type:"string",description:"Optional; defaults to the task's own project"}},required:["taskId","column"]}},{name:"vikunja_add_label",description:"Attach a label to a task by title. Creates the label when it does not exist (pass create=false to refuse instead).",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},label:{type:"string",description:"Label title"},create:{type:"boolean",description:"Create the label if missing (default true)"}},required:["taskId","label"]}},{name:"vikunja_remove_label",description:"Detach a label from a task by title.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},label:{type:"string",description:"Label title"}},required:["taskId","label"]}},{name:"vikunja_add_comment",description:"Add a comment to a task.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},comment:{type:"string",description:"Comment body. Markdown is rendered (headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes)."}},required:["taskId","comment"]}},{name:"vikunja_assign",description:"Assign a user to a task by username.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Numeric task id"},username:{type:"string",description:"Vikunja username"}},required:["taskId","username"]}}]};var zs={id:"plane",serverName:"plane",allowedTools:["mcp__plane__*"],requiresIntegration:I.PLANE,envKeys:["PLANE_API_KEY","PLANE_WORKSPACE_SLUG","PLANE_BASE_URL"],description:"Plane \u2014 projects, work items, cycles, modules, epics, comments (official MCP, API key)",tools:[],promptFragment:`## Plane
|
|
332
330
|
You have direct access to the user's Plane workspace via the official Plane MCP server. All Plane tools are available under the mcp__plane__* namespace \u2014 use them proactively to read and write projects, work items (issues), cycles, modules, epics, sub-issues, comments, labels, states, pages, and workspace data.
|
|
333
331
|
|
|
334
332
|
- List/get projects and work items, then create/update/delete or search work items as needed.
|
|
335
333
|
- For status changes, read the project's available states first, then set the work item's state.
|
|
336
334
|
- Cycles and modules group work items \u2014 list them to scope queries before drilling into items.
|
|
337
|
-
- Always operate within the connected workspace; the workspace slug and base URL are pre-configured (Plane Cloud, self-hosted, or Zibby-hosted all work transparently).`,resolve(){let r={};for(let
|
|
335
|
+
- Always operate within the connected workspace; the workspace slug and base URL are pre-configured (Plane Cloud, self-hosted, or Zibby-hosted all work transparently).`,resolve(){let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);return{type:"stdio",command:"uvx",args:["plane-mcp-server","stdio"],env:r,description:this.description}}};import{existsSync as ud}from"fs";import{fileURLToPath as md}from"url";import{dirname as hd,resolve as fd}from"path";import{resolveIntegrationToken as yd}from"@zibby/core/backend-client.js";function gd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=hd(md(import.meta.url)),e=fd(r,"..","bin","mcp-skill.mjs");return ud(e)?e:null}async function Ys(){let r=await yd(I.OPEN_DESIGN),e=r?.token,t=r?.baseUrl;if(!e||typeof e!="string")throw new Error("OpenDesign is not connected: missing token. Connect it in Integrations.");if(!t||typeof t!="string")throw new Error("OpenDesign is not connected: missing baseUrl. Connect it in Integrations.");let n=t.replace(/\/+$/,"");return{token:e,baseUrl:n}}async function Oe(r,e={}){let{token:t,baseUrl:n}=await Ys(),s=`${n}/api${r}`;if(e.query&&typeof e.query=="object"){let a=new URLSearchParams;for(let[l,d]of Object.entries(e.query))d!=null&&d!==""&&a.set(l,String(d));let c=a.toString();c&&(s+=(s.includes("?")?"&":"?")+c)}let i={Authorization:`Bearer ${t}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},o=await w(s,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0},{kind:"api",what:`OpenDesign ${e.method||"GET"} ${r}`});return Ws(o,"OpenDesign")}async function Ws(r,e){if(!r.ok){let n=await r.text().catch(()=>""),s=n.slice(0,300);try{let i=JSON.parse(n),o=i?.code||i?.error?.code,a=i?.message||i?.error?.message||i?.error;(o||a)&&(s=[o?`[${o}]`:null,a].filter(Boolean).join(" ")||s)}catch{}throw new Error(`${e} API ${r.status}: ${s}`)}let t=await r.text().catch(()=>"");if(!t)return{};try{return JSON.parse(t)}catch{return{raw:t}}}var Zs={id:"open-design",callsBackend:!0,serverName:"opendesign",allowedTools:["mcp__opendesign__*"],envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"OpenDesign \u2014 list projects/designs, run the design agent, and export decks to PDF/HTML",promptFragment:`## OpenDesign (optional)
|
|
338
336
|
You may have access to the user's OpenDesign workspace (the Zibby-managed design/deck app) via its REST API. These tools are OPTIONAL \u2014 if OpenDesign is not connected they will return a "not connected" error; reach for them only when the task involves OpenDesign projects, designs, or exports. Tools (mcp__opendesign__*):
|
|
339
337
|
|
|
340
338
|
### Connectivity
|
|
@@ -356,30 +354,30 @@ You may have access to the user's OpenDesign workspace (the Zibby-managed design
|
|
|
356
354
|
|
|
357
355
|
### Notes
|
|
358
356
|
- A design artifact lookup ALWAYS needs its projectId (it scopes the query).
|
|
359
|
-
- After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let r=
|
|
357
|
+
- After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let r=gd();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/opendesign.js","opendesignSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"opendesign_health":{let{baseUrl:t}=await Ys(),n=await w(`${t}/api/health`,{method:"GET",headers:{Accept:"application/json"}},{kind:"api",what:"OpenDesign GET /api/health"}),s=await Ws(n,"OpenDesign");return JSON.stringify({ok:!0,health:s})}case"opendesign_list_projects":{let t=await Oe("/projects");return JSON.stringify(t)}case"opendesign_get_project":{let t=e?.id||e?.projectId;if(!t)return JSON.stringify({error:"id is required"});let n=await Oe(`/projects/${encodeURIComponent(t)}`);return JSON.stringify(n)}case"opendesign_list_designs":{let t=e?.projectId;if(!t)return JSON.stringify({error:"projectId is required"});let n=await Oe("/live-artifacts",{query:{projectId:t}});return JSON.stringify(n)}case"opendesign_get_design":{let t=e?.id,n=e?.projectId;if(!t)return JSON.stringify({error:"id is required"});if(!n)return JSON.stringify({error:"projectId is required"});let s=await Oe(`/live-artifacts/${encodeURIComponent(t)}`,{query:{projectId:n}});return JSON.stringify(s)}case"opendesign_export_pdf":{let t=e?.projectId||e?.id,{fileName:n,title:s,deck:i}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});if(!n)return JSON.stringify({error:"fileName is required"});let o={fileName:n};s!==void 0&&(o.title=s),i!==void 0&&(o.deck=i);let a=await Oe(`/projects/${encodeURIComponent(t)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(a)}case"opendesign_export_html":{let t=e?.projectId||e?.id,n=e?.path;if(!t)return JSON.stringify({error:"projectId is required"});if(!n)return JSON.stringify({error:"path is required (the export sub-path)"});let i=String(n).replace(/^\/+/,"").split("/").map(a=>encodeURIComponent(a)).join("/"),o=await Oe(`/projects/${encodeURIComponent(t)}/export/${i}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:t,message:n,projectId:s,conversationId:i,model:o}=e||{};if(!t)return JSON.stringify({error:"agentId is required"});if(!n)return JSON.stringify({error:"message is required"});let a={agentId:t,message:n};s!==void 0&&(a.projectId=s),i!==void 0&&(a.conversationId=i),o!==void 0&&(a.model=o);let c=await Oe("/runs",{method:"POST",body:a});return JSON.stringify(c)}case"opendesign_cli_status":{let t=e?.id||e?.runId;if(!t)return JSON.stringify({error:"id (runId) is required"});let n=await Oe(`/runs/${encodeURIComponent(t)}`);return JSON.stringify(n)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"opendesign_health",description:"Probe the OpenDesign instance (GET /api/health, no auth). Use to confirm connectivity before other calls.",input_schema:{type:"object",properties:{}}},{name:"opendesign_list_projects",description:"List the projects in the OpenDesign workspace.",input_schema:{type:"object",properties:{}}},{name:"opendesign_get_project",description:"Get a single OpenDesign project by id.",input_schema:{type:"object",properties:{id:{type:"string",description:"The project id."}},required:["id"]}},{name:"opendesign_list_designs",description:"List the live design artifacts in an OpenDesign project. Requires the projectId, which scopes the query.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id whose designs to list."}},required:["projectId"]}},{name:"opendesign_get_design",description:"Get a single live design artifact by id. Requires both the design id and its projectId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The live-artifact (design) id."},projectId:{type:"string",description:"The project id the design belongs to (scopes the lookup)."}},required:["id","projectId"]}},{name:"opendesign_export_pdf",description:"Export an OpenDesign project deck to PDF. Returns the export result (e.g. a download URL/path).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},fileName:{type:"string",description:"The output PDF file name."},title:{type:"string",description:"Optional deck title for the PDF."},deck:{description:"Optional deck payload/override to render instead of the project's current deck."}},required:["projectId","fileName"]}},{name:"opendesign_export_html",description:"Fetch an OpenDesign project's HTML export by sub-path (requested inline). Requires projectId and the export path.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},path:{type:"string",description:'The export sub-path under /projects/:id/export/ (e.g. "index.html" or a slide path).'}},required:["projectId","path"]}},{name:"opendesign_cli_run",description:"Start an OpenDesign agent run. Returns a runId; poll opendesign_cli_status with it until the run finishes.",input_schema:{type:"object",properties:{agentId:{type:"string",description:"The OpenDesign agent id to run."},message:{type:"string",description:"The instruction/message to send to the agent."},projectId:{type:"string",description:"Optional project id to scope the run to."},conversationId:{type:"string",description:"Optional conversation id to continue an existing thread."},model:{type:"string",description:"Optional model id override for the run."}},required:["agentId","message"]}},{name:"opendesign_cli_status",description:"Poll the status of an OpenDesign agent run by its runId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The runId returned by opendesign_cli_run."}},required:["id"]}}]};import{existsSync as bd}from"fs";import{fileURLToPath as _d}from"url";import{dirname as kd,resolve as wd}from"path";import{resolveIntegrationToken as Sd}from"@zibby/core/backend-client.js";function vd(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let r=kd(_d(import.meta.url)),e=wd(r,"..","bin","mcp-slack.mjs");return bd(e)?e:null}async function W(r,e={}){let{token:t}=await Sd("slack"),n=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(r),s=`https://slack.com/api/${r}`,i={Authorization:`Bearer ${t}`},o;if(n){let l=new URLSearchParams(e).toString();l&&(s+=`?${l}`)}else i["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(e);let c=await(await w(s,{method:n?"GET":"POST",headers:i,body:o},{kind:"api",what:`Slack ${r}`})).json();if(!c.ok)throw new Error(`Slack API error: ${c.error}`);return c}var U={id:"slack",callsBackend:!0,serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:I.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack
|
|
360
358
|
You have access to the user's Slack workspace. Use these tools:
|
|
361
359
|
- slack_list_channels, slack_post_message, slack_reply_to_thread
|
|
362
360
|
- slack_add_reaction, slack_get_channel_history, slack_get_thread_replies
|
|
363
361
|
- slack_get_users, slack_get_user_profile
|
|
364
362
|
- slack_lookup_user_by_email (precise email\u2192user_id, prefer this over scanning slack_get_users)
|
|
365
|
-
- slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=pl();if(!r)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r],env:t,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"slack_list_channels":{let e=await Y("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(e.channels||[]).map(n=>({id:n.id,name:n.name,topic:n.topic?.value}))})}case"slack_post_message":{if(!t.channel||!t.text)return JSON.stringify({error:"channel and text are required"});let e=await Y("chat.postMessage",{channel:t.channel,text:t.text,...t.blocks?{blocks:t.blocks}:{}});return JSON.stringify({ok:!0,ts:e.ts,channel:e.channel})}case"slack_reply_to_thread":{if(!t.channel||!t.thread_ts||!t.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let e=await Y("chat.postMessage",{channel:t.channel,thread_ts:t.thread_ts,text:t.text});return JSON.stringify({ok:!0,ts:e.ts})}case"slack_add_reaction":return!t.channel||!t.timestamp||!t.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await Y("reactions.add",{channel:t.channel,timestamp:t.timestamp,name:t.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!t.channel)return JSON.stringify({error:"channel is required"});let e=await Y("conversations.history",{channel:t.channel,limit:t.limit||20});return JSON.stringify({messages:(e.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_thread_replies":{if(!t.channel||!t.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let e=await Y("conversations.replies",{channel:t.channel,ts:t.thread_ts});return JSON.stringify({messages:(e.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_users":{let e=await Y("users.list",{limit:100});return JSON.stringify({users:(e.members||[]).filter(n=>!n.is_bot&&!n.deleted).map(n=>({id:n.id,name:n.real_name||n.name}))})}case"slack_get_user_profile":{if(!t.user_id)return JSON.stringify({error:"user_id is required"});let e=await Y("users.profile.get",{user:t.user_id});return JSON.stringify({profile:e.profile})}case"slack_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});try{let e=await Y("users.lookupByEmail",{email:t.email});return JSON.stringify({ok:!0,user:{id:e.user?.id,name:e.user?.real_name||e.user?.name,email:e.user?.profile?.email||t.email}})}catch(e){if(/users_not_found/.test(e.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw e}}case"slack_list_usergroups":{let e=await Y("usergroups.list",{});return JSON.stringify({usergroups:(e.usergroups||[]).map(n=>({id:n.id,handle:n.handle,name:n.name,description:n.description||"",user_count:Number(n.user_count||0)}))})}case"slack_get_usergroup_members":{if(!t.usergroup)return JSON.stringify({error:"usergroup id is required"});let e=await Y("usergroups.users.list",{usergroup:t.usergroup});return JSON.stringify({users:e.users||[]})}case"slack_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(t.limit)||5,25)),s=[],i,o=5;for(let c=0;c<o;c+=1){let l={limit:200};i&&(l.cursor=i);let d=await Y("users.list",l);for(let p of d.members||[])p.deleted||p.is_bot||s.push(p);if(i=d.response_metadata?.next_cursor,!i)break}let a=[];for(let c of s){let l=(c.real_name||"").toLowerCase(),d=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;l.includes(e)&&(u+=100-Math.abs(l.length-e.length)),d.includes(e)&&(u+=60-Math.abs(d.length-e.length)),p.includes(e)&&(u+=30-Math.abs(p.length-e.length)),(l===e||d===e)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,l)=>l._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,n).map(({_score:c,...l})=>l),scanned:s.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as ul}from"fs";import{fileURLToPath as ml}from"url";import{dirname as hl,resolve as fl}from"path";import{resolveIntegrationToken as yl}from"@zibby/core/backend-client.js";function gl(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=hl(ml(import.meta.url)),t=fl(r,"..","bin","mcp-lark.mjs");return ul(t)?t:null}var _l=6e3*1e3,at=null;async function bl(){let{appId:r,appSecret:t,host:e}=await yl("lark");if(at&&at.appId===r&&at.expiresAt>Date.now())return{token:at.token,host:e};let s=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:t})})).json();if(s.code!==0)throw new Error(`Lark tenant_access_token failed: ${s.msg||s.code}`);return at={token:s.tenant_access_token,expiresAt:Date.now()+_l,appId:r},{token:s.tenant_access_token,host:e}}async function Ne(r,t,e={}){let{token:n,host:s}=await bl(),i=`${s}${t}`,o={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(o.body=JSON.stringify(e));let c=await(await fetch(i,o)).json();if(c.code!==0)throw new Error(`Lark API ${t} error: ${c.msg||c.code}`);return c.data||{}}function ds(r){return JSON.stringify({text:r})}function kl(r){return!r||typeof r!="string"||r.startsWith("oc_")?"chat_id":r.startsWith("ou_")?"open_id":r.startsWith("on_")?"union_id":r.startsWith("cli_")?"app_id":r.includes("@")?"email":"chat_id"}var F={id:"lark",callsBackend:!0,serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:S.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],promptFragment:`## Lark
|
|
363
|
+
- slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=vd();if(!r)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[t]&&(e[t]=process.env[t]);for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"slack_list_channels":{let t=await W("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(t.channels||[]).map(n=>({id:n.id,name:n.name,topic:n.topic?.value}))})}case"slack_post_message":{if(!e.channel||!e.text)return JSON.stringify({error:"channel and text are required"});let t=await W("chat.postMessage",{channel:e.channel,text:e.text,...e.blocks?{blocks:e.blocks}:{}});return JSON.stringify({ok:!0,ts:t.ts,channel:t.channel})}case"slack_reply_to_thread":{if(!e.channel||!e.thread_ts||!e.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let t=await W("chat.postMessage",{channel:e.channel,thread_ts:e.thread_ts,text:e.text});return JSON.stringify({ok:!0,ts:t.ts})}case"slack_add_reaction":return!e.channel||!e.timestamp||!e.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await W("reactions.add",{channel:e.channel,timestamp:e.timestamp,name:e.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!e.channel)return JSON.stringify({error:"channel is required"});let t=await W("conversations.history",{channel:e.channel,limit:e.limit||20});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_thread_replies":{if(!e.channel||!e.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let t=await W("conversations.replies",{channel:e.channel,ts:e.thread_ts});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_users":{let t=await W("users.list",{limit:100});return JSON.stringify({users:(t.members||[]).filter(n=>!n.is_bot&&!n.deleted).map(n=>({id:n.id,name:n.real_name||n.name}))})}case"slack_get_user_profile":{if(!e.user_id)return JSON.stringify({error:"user_id is required"});let t=await W("users.profile.get",{user:e.user_id});return JSON.stringify({profile:t.profile})}case"slack_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});try{let t=await W("users.lookupByEmail",{email:e.email});return JSON.stringify({ok:!0,user:{id:t.user?.id,name:t.user?.real_name||t.user?.name,email:t.user?.profile?.email||e.email}})}catch(t){if(/users_not_found/.test(t.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw t}}case"slack_list_usergroups":{let t=await W("usergroups.list",{});return JSON.stringify({usergroups:(t.usergroups||[]).map(n=>({id:n.id,handle:n.handle,name:n.name,description:n.description||"",user_count:Number(n.user_count||0)}))})}case"slack_get_usergroup_members":{if(!e.usergroup)return JSON.stringify({error:"usergroup id is required"});let t=await W("usergroups.users.list",{usergroup:e.usergroup});return JSON.stringify({users:t.users||[]})}case"slack_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),s=[],i,o=5;for(let c=0;c<o;c+=1){let l={limit:200};i&&(l.cursor=i);let d=await W("users.list",l);for(let p of d.members||[])p.deleted||p.is_bot||s.push(p);if(i=d.response_metadata?.next_cursor,!i)break}let a=[];for(let c of s){let l=(c.real_name||"").toLowerCase(),d=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;l.includes(t)&&(u+=100-Math.abs(l.length-t.length)),d.includes(t)&&(u+=60-Math.abs(d.length-t.length)),p.includes(t)&&(u+=30-Math.abs(p.length-t.length)),(l===t||d===t)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,l)=>l._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,n).map(({_score:c,...l})=>l),scanned:s.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as Id}from"fs";import{fileURLToPath as Td}from"url";import{dirname as Nd,resolve as Od}from"path";import{resolveIntegrationToken as Ad}from"@zibby/core/backend-client.js";function Rd(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=Nd(Td(import.meta.url)),e=Od(r,"..","bin","mcp-lark.mjs");return Id(e)?e:null}var Ed=6e3*1e3,kt=null;async function xd(){let{appId:r,appSecret:e,host:t}=await Ad("lark");if(kt&&kt.appId===r&&kt.expiresAt>Date.now())return{token:kt.token,host:t};let s=await(await w(`${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})},{kind:"api",what:"Lark tenant_access_token"})).json();if(s.code!==0)throw new Error(`Lark tenant_access_token failed: ${s.msg||s.code}`);return kt={token:s.tenant_access_token,expiresAt:Date.now()+Ed,appId:r},{token:s.tenant_access_token,host:t}}async function Pe(r,e,t={}){let{token:n,host:s}=await xd(),i=`${s}${e}`,o={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(o.body=JSON.stringify(t));let c=await(await w(i,o,{kind:"api",what:`Lark ${r} ${e}`})).json();if(c.code!==0)throw new Error(`Lark API ${e} error: ${c.msg||c.code}`);return c.data||{}}function Vs(r){return JSON.stringify({text:r})}function Ld(r){return!r||typeof r!="string"||r.startsWith("oc_")?"chat_id":r.startsWith("ou_")?"open_id":r.startsWith("on_")?"union_id":r.startsWith("cli_")?"app_id":r.includes("@")?"email":"chat_id"}var F={id:"lark",callsBackend:!0,serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:I.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],promptFragment:`## Lark
|
|
366
364
|
You can send messages and replies on Lark. Use:
|
|
367
365
|
- lark_send_message: post a message to a chat, user, or DM
|
|
368
366
|
- lark_reply: reply to an existing message (threaded)
|
|
369
367
|
- lark_list_chats: list chats the bot is a member of
|
|
370
368
|
- lark_get_chat_history: fetch recent messages in a chat
|
|
371
369
|
- lark_lookup_user_by_email: resolve an email \u2192 open_id for direct DM (prefer this over emailing through lark_send_message when the agent has a user_id already)
|
|
372
|
-
When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=
|
|
373
|
-
`),a=o>
|
|
370
|
+
When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=Rd();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=Ld(e.receive_id),n=await Pe("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:Vs(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 Pe("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:Vs(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,s=((await Pe("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(i=>({chat_id:i.chat_id,name:i.name,description:i.description,owner_id:i.owner_id,chat_mode:i.chat_mode}));return JSON.stringify({chats:s})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,s=((await Pe("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(i=>({message_id:i.message_id,sender_id:i.sender?.id,sender_type:i.sender?.sender_type,msg_type:i.msg_type,content:i.body?.content,create_time:i.create_time}));return JSON.stringify({messages:s})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let n=((await Pe("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(s=>s.email===e.email&&s.user_id);return JSON.stringify(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)),s=200,o=((await Pe("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(d=>d.chat_id),a=new Set,c=[];for(let d of o){if(c.length>=s)break;try{let p=await Pe("GET",`/open-apis/im/v1/chats/${encodeURIComponent(d)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=s))break}catch(p){console.warn(`[lark] member scan failed for ${d}: ${p.message}`)}}let l=[];for(let d of c){let p=(d.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(t)&&(u+=100-Math.abs(p.length-t.length)),p===t&&(u+=200),u>0&&l.push({open_id:d.open_id,name:d.name,_score:u})}return l.sort((d,p)=>p._score-d._score),JSON.stringify({ok:!0,matches:l.slice(0,n).map(({_score:d,...p})=>p),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}}};import{existsSync as $d}from"fs";import{fileURLToPath as jd}from"url";import{dirname as Pd,resolve as Cd}from"path";import{resolveIntegrationToken as Ud}from"@zibby/core/backend-client.js";function Bd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Pd(jd(import.meta.url)),e=Cd(r,"..","bin","mcp-skill.mjs");return $d(e)?e:null}var Dd=process.env.DISCORD_API_URL||"https://discord.com/api/v10",Md=2e3;function Jd(r,e=Md){let t=String(r??"");if(!t.trim())return[];if(t.length<=e)return[t];let n=[],s=t;for(;s.length>e;){let o=s.slice(0,e).lastIndexOf(`
|
|
371
|
+
`),a=o>e/2?o+1:e;n.push(s.slice(0,a)),s=s.slice(a)}return s&&n.push(s),n}async function Xs(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await Ud(I.DISCORD),t=(e&&e.token?String(e.token):"").trim();if(!t)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:t,guildId:(e.guildId||"").trim()}}async function tn(r,e,{token:t,body:n}={}){let s=t.startsWith("Bot ")?t:`Bot ${t}`,i=await w(`${Dd}${e}`,{method:r,headers:{Authorization:s,...n!==void 0?{"Content-Type":"application/json"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{}},{kind:"api",what:`Discord ${r} ${e}`}),o=await i.json().catch(()=>null);if(!i.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${i.status}`;throw new Error(`Discord API error (${i.status}): ${a}`)}return o}async function qd({token:r,guildId:e},t){let n=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(n)return n;let s=await tn("GET","/users/@me/guilds",{token:r}),i=Array.isArray(s)?s:[];if(i.length===1)return i[0].id;if(i.length===0)throw new Error("The bot is not in any Discord server \u2014 invite it to a server first.");let o=i.slice(0,10).map(a=>`${a.name} (${a.id})`).join(", ");throw new Error(`The bot is in ${i.length} servers \u2014 pass guildId explicitly. Servers: ${o}`)}var Qs={id:"discord",callsBackend:!0,serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:I.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord
|
|
374
372
|
You can post to the user's Discord server as their bot. Tools:
|
|
375
373
|
- discord_send_message(channelId, text) \u2014 post a message to a channel (long text is auto-chunked to Discord's 2000-char limit)
|
|
376
|
-
- discord_list_channels(guildId?) \u2014 list the server's text channels (id + name) to find where to post; guildId is optional when the bot is in one server`,resolve(){let r={};for(let
|
|
374
|
+
- 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=Bd();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 s=await Xs(),i=Jd(n),o=[];for(let a of i){let c=await tn("POST",`/channels/${encodeURIComponent(t)}/messages`,{token:s.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:t,messageIds:o,chunks:i.length})}case"discord_list_channels":{let t=await Xs(),n=await qd(t,e.guildId),s=await tn("GET",`/guilds/${encodeURIComponent(n)}/channels`,{token:t.token}),i=(Array.isArray(s)?s:[]).filter(o=>o&&(o.type===0||o.type===5)).map(o=>({id:o.id,name:o.name,type:o.type===5?"announcement":"text",...o.topic?{topic:o.topic}:{}}));return JSON.stringify({ok:!0,guildId:n,channels:i})}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 ii,statSync as Gd,readFileSync as Kd}from"fs";import{fileURLToPath as Fd}from"url";import{basename as Hd,dirname as zd,resolve as Yd}from"path";import{resolveIntegrationToken as Wd,clearTokenCache as Zd}from"@zibby/core/backend-client.js";function Vd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=zd(Fd(import.meta.url)),e=Yd(r,"..","bin","mcp-skill.mjs");return ii(e)?e:null}var Xd="2022-06-28",Qd="https://api.notion.com/v1",ar=2e4,ei=25,ep=25,cr=100,ti=500,tp=20*1024*1024;function ge(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 s=t.match(/[0-9a-fA-F]{32}/g);if(s&&s.length){let i=s[s.length-1].toLowerCase();return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}return null}async function le(r,e={}){let t=async()=>{let{token:n}=await Wd("notion");if(typeof n!="string"||!n)throw new Error(`Invalid notion token type: ${typeof n}`);let s=await w(`${Qd}${r}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"Notion-Version":Xd,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},{kind:e.formData?"transfer":"api",what:`Notion ${e.method||"GET"} ${r}`});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Notion API ${s.status}: ${o.slice(0,300)}`)}let i=await s.text().catch(()=>"");if(!i||!i.trim())return{};try{return JSON.parse(i)}catch{return{raw:i}}};try{return await t()}catch(n){let s=String(n?.message||n||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw n;return Zd("notion"),t()}}function tt(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 s=t.annotations||{};s.code&&(n=`\`${n}\``),s.bold&&(n=`**${n}**`),s.italic&&(n=`_${n}_`),s.strikethrough&&(n=`~~${n}~~`);let i=t?.href||t?.text?.link?.url;i&&(n=`[${n}](${i})`),e+=n}return e}function rp(r,e,t){let n=r?.type,s=r?.[n]||{},i=" ".repeat(Math.max(0,e)),o=(l="rich_text")=>tt(s[l]),a;switch(n){case"paragraph":a=o();break;case"heading_1":a=`# ${o()}`;break;case"heading_2":a=`## ${o()}`;break;case"heading_3":a=`### ${o()}`;break;case"bulleted_list_item":a=`${i}- ${o()}`;break;case"numbered_list_item":a=`${i}1. ${o()}`;break;case"to_do":a=`${i}- [${s.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${i}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${s.icon?.emoji?`${s.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${s.language||""}
|
|
377
375
|
${o()}
|
|
378
|
-
\`\`\``;break}case"divider":a="---";break;case"child_page":a=`[child page: ${s.title||""}]`;break;case"child_database":a=`[child database: ${s.title||""}]`;break;case"bookmark":case"embed":case"link_preview":a=s.url?`<${s.url}>`:"";break;case"equation":a=s.expression?`$${s.expression}$`:"";break;case"table":case"column_list":case"column":a="";break;case"table_row":{let l=(s.cells||[]).map(d=>
|
|
379
|
-
`)}async function
|
|
380
|
-
`)}function
|
|
381
|
-
`),
|
|
382
|
-
`)){let s=n.replace(/\s+$/,"");if(!s.trim())continue;let i=/^(#{1,3})\s+(.*)$/.exec(s),o=/^\s*[-*]\s+(.*)$/.exec(s),a=/^\s*\d+[.)]\s+(.*)$/.exec(s),c,l;i?(c=`heading_${i[1].length}`,l=i[2]):o?(c="bulleted_list_item",l=o[1]):a?(c="numbered_list_item",l=a[1]):(c="paragraph",l=s),
|
|
376
|
+
\`\`\``;break}case"divider":a="---";break;case"child_page":a=`[child page: ${s.title||""}]`;break;case"child_database":a=`[child database: ${s.title||""}]`;break;case"bookmark":case"embed":case"link_preview":a=s.url?`<${s.url}>`:"";break;case"equation":a=s.expression?`$${s.expression}$`:"";break;case"table":case"column_list":case"column":a="";break;case"table_row":{let l=(s.cells||[]).map(d=>tt(d).trim());a=`${i}| ${l.join(" | ")} |`;break}default:a=o();break}let c=[];return a&&a.trim()&&c.push(a),t&&t.trim()&&c.push(t),c.join(`
|
|
377
|
+
`)}async function oi(r,e,t){let n=[],s,i=0;do{if(t.used>=ar)break;let o=new URLSearchParams({page_size:"100"});s&&o.set("start_cursor",s);let a=await le(`/blocks/${r}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let l of c){let d="";l.has_children&&(d=await oi(l.id,e+1,t));let p=rp(l,e,d);if(p&&(n.push(p),t.used+=p.length+1),t.used>=ar)break}s=a.has_more?a.next_cursor:void 0,i+=1}while(s&&i<ep);return n.join(`
|
|
378
|
+
`)}function ri(r){let e=r?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let n=tt(t.title).trim();if(n)return n}return""}function wt(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 np(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:tt(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function sp(r){if(!r||!r.type)return"";switch(r.type){case"title":return tt(r.title).trim();case"rich_text":return tt(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 rn(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function ip(r){let e=String(r??"").replace(/\r\n/g,`
|
|
379
|
+
`),t=[];for(let n of e.split(`
|
|
380
|
+
`)){let s=n.replace(/\s+$/,"");if(!s.trim())continue;let i=/^(#{1,3})\s+(.*)$/.exec(s),o=/^\s*[-*]\s+(.*)$/.exec(s),a=/^\s*\d+[.)]\s+(.*)$/.exec(s),c,l;i?(c=`heading_${i[1].length}`,l=i[2]):o?(c="bulleted_list_item",l=o[1]):a?(c="numbered_list_item",l=a[1]):(c="paragraph",l=s),t.push({object:"block",type:c,[c]:{rich_text:wt(l)}})}return t}function ni(r){return Array.isArray(r?.blocks)&&r.blocks.length?r.blocks.slice(0,ti):typeof r?.markdown=="string"&&r.markdown.trim()?ip(r.markdown).slice(0,ti):null}async function si(r,e){for(let t=0;t<e.length;t+=cr)await le(`/blocks/${r}/children`,{method:"PATCH",body:{children:e.slice(t,t+cr)}})}function op(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!ii(e)||!Gd(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=Kd(e);if(t.length>tp)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return t}async function ap(r){let e=op(r),t=Hd(r.trim()),n=/\.png$/i.test(t)?"image/png":"image/jpeg",i=(await le("/file_uploads",{method:"POST",body:{mode:"single_part",filename:t}}))?.id;if(!i)throw new Error("Notion file upload create returned no id");let o=new FormData;return o.set("file",new Blob([e],{type:n}),t),await le(`/file_uploads/${i}/send`,{method:"POST",formData:o}),i}var ai={id:"notion",callsBackend:!0,serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:I.NOTION,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion
|
|
383
381
|
You can read Notion content as context AND write to Notion (create pages, append blocks, insert images).
|
|
384
382
|
- notion_get_page: pass a Notion page id OR a full Notion URL; returns { id, title, url, text } where text is the page flattened to markdown (truncated to ~20k chars). Use the text as reference context.
|
|
385
383
|
- notion_query_database: pass a database id/URL; returns a small list of rows ({ id, title, url, props }). Use to find a specific page, then notion_get_page it.
|
|
@@ -388,7 +386,7 @@ You can read Notion content as context AND write to Notion (create pages, append
|
|
|
388
386
|
- notion_insert_image: append an image block to a page. Pass { pageId, imagePath } for a LOCAL png/jpg file (\u226420MB, uploaded via Notion's File Upload API) or { pageId, imageUrl } for an external, publicly reachable image URL. Optional caption. Returns { ok, pageId, url }.
|
|
389
387
|
- notion_list_comments: pass a page/block id OR URL; returns the open comment discussions on it ({ id, discussionId, text, author }). Use to read the comment thread you are replying to.
|
|
390
388
|
- notion_add_comment: post a comment. To REPLY in an existing discussion pass { discussionId, text }; to start a NEW top-level comment on a page pass { pageId, text }. Returns { ok, id, discussionId }. Use this to answer a user who @mentioned Zibby in a Notion comment \u2014 reply in the SAME discussionId.
|
|
391
|
-
Do not block the task if Notion is unavailable \u2014 these tools return { ok:false, error } on failure; treat a missing page as "no extra context" / "cannot deliver to Notion" and continue.`,resolve(){let r=Dl();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"notion_get_page":{let e=t?.pageId||t?.page||t?.url||t?.id,n=pe(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let s=await se(`/pages/${n}`),i=fs(s),o=s?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,c=await bs(n,0,{used:0}),l=!1;return c.length>Kt&&(c=c.slice(0,Kt),l=!0),JSON.stringify({ok:!0,id:n,title:i,url:o,text:c,...l?{truncated:!0}:{}})}case"notion_query_database":{let e=t?.databaseId||t?.database||t?.url||t?.id,n=pe(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let i={page_size:Math.max(1,Math.min(Number(t?.maxResults)||ms,ms))};t?.filter&&typeof t.filter=="object"&&(i.filter=t.filter);let o=await se(`/databases/${n}/query`,{method:"POST",body:i}),c=(Array.isArray(o.results)?o.results:[]).map(l=>{let d={};for(let[p,u]of Object.entries(l.properties||{})){let m=Hl(u);m&&(d[p]=m)}return{id:l.id,title:fs(l),url:l.url||`https://www.notion.so/${String(l.id||"").replace(/-/g,"")}`,props:d}});return JSON.stringify({ok:!0,id:n,count:c.length,hasMore:!!o.has_more,rows:c})}case"notion_create_page":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let n=t?.databaseId?pe(t.databaseId):null,s=t?.parentPageId?pe(t.parentPageId):pe(t?.parent||t?.pageId);if(!n&&!s)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let i=n?{database_id:n}:{page_id:s},o={title:{title:ct(e)}},a=ys(t)||[],c=a.slice(0,Gt),l=await se("/pages",{method:"POST",body:{parent:i,properties:o,...c.length?{children:c}:{}}}),d=l?.id;if(!d)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let p=a.slice(Gt);return p.length&&await gs(d,p),JSON.stringify({ok:!0,pageId:d,url:l?.url||Er(d)})}case"notion_append_blocks":{let e=pe(t?.pageId||t?.blockId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=ys(t);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await gs(e,n),JSON.stringify({ok:!0,pageId:e,url:Er(e)}))}case"notion_insert_image":{let e=pe(t?.pageId||t?.url||t?.id);if(!e)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=typeof t?.caption=="string"&&t.caption.trim()?ct(t.caption.trim()):null,s,i;if(typeof t?.imagePath=="string"&&t.imagePath.trim())i=await Wl(t.imagePath),s={type:"file_upload",file_upload:{id:i}};else if(typeof t?.imageUrl=="string"&&t.imageUrl.trim())s={type:"external",external:{url:t.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return n&&(s.caption=n),await se(`/blocks/${e}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:s}]}}),JSON.stringify({ok:!0,pageId:e,url:Er(e),...i?{fileUploadId:i}:{}})}case"notion_list_comments":{let e=t?.blockId||t?.pageId||t?.block||t?.page||t?.url||t?.id,n=pe(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let s=new URLSearchParams({block_id:n,page_size:"100"}),i=await se(`/comments?${s.toString()}`),a=(Array.isArray(i.results)?i.results:[]).map(Gl);return JSON.stringify({ok:!0,id:n,count:a.length,comments:a})}case"notion_add_comment":{let e=typeof t?.text=="string"?t.text:typeof t?.body=="string"?t.body:"";if(!e||!e.trim())return JSON.stringify({ok:!1,error:"text is required"});let n=t?.discussionId||t?.discussion_id||null,s;if(n)s={discussion_id:String(n),rich_text:ct(e)};else{let o=t?.pageId||t?.page||t?.url||t?.id,a=pe(o);if(!a)return JSON.stringify({ok:!1,error:"Either discussionId (to reply) or a valid pageId (to start a comment) is required"});s={parent:{page_id:a},rich_text:ct(e)}}let i=await se("/comments",{method:"POST",body:s});return JSON.stringify({ok:!0,id:i?.id||"",discussionId:i?.discussion_id||n||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}},{name:"notion_create_page",description:"Create a new Notion page under a parent page (parentPageId) OR in a database (databaseId) \u2014 exactly one parent is required. Body from markdown (#/##/### headings, - bullets, 1. ordered lists; inline marks kept as literal text) or raw Notion block objects. Long bodies are chunked automatically (Notion caps 100 blocks/request). Returns { ok, pageId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{parentPageId:{type:"string",description:"Parent PAGE id/URL to create the page under (used when databaseId is absent)."},databaseId:{type:"string",description:"Parent DATABASE id/URL to create the page in (title goes into the title property)."},title:{type:"string",description:"Page title."},markdown:{type:"string",description:"Page body as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["title"]}},{name:"notion_append_blocks",description:"Append markdown (or raw Notion blocks) to the END of an existing Notion page. Accepts a page id or full Notion URL. Chunks automatically at Notion's 100-blocks-per-request cap. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["pageId"]}},{name:"notion_insert_image",description:"Append an image block to a Notion page. Pass imagePath for a LOCAL .png/.jpg file (max 20MB \u2014 uploaded via Notion's File Upload API, stored by Notion) or imageUrl for an external publicly-reachable image URL. Optional caption. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 20MB). Preferred for locally rendered charts."},imageUrl:{type:"string",description:"External image URL (must be publicly reachable; used when imagePath is absent)."},caption:{type:"string",description:"Optional image caption."}},required:["pageId"]}},{name:"notion_list_comments",description:"List the open comment discussions on a Notion page/block. Accepts a page/block id OR a full Notion URL. Returns { ok, comments:[{ id, discussionId, text, author }] }. Use to read the comment thread you are replying to.",input_schema:{type:"object",properties:{blockId:{type:"string",description:"Notion page or block id (dashed UUID or 32-char) OR a full Notion URL."}},required:["blockId"]}},{name:"notion_add_comment",description:"Post a comment on Notion. To REPLY within an existing discussion, pass { discussionId, text }. To start a NEW top-level comment on a page, pass { pageId, text }. Returns { ok, id, discussionId }. Use this to answer a user who @mentioned Zibby in a Notion comment (reply in the same discussionId).",input_schema:{type:"object",properties:{discussionId:{type:"string",description:"The discussion_id to reply into (from notion_list_comments). Preferred for replies."},pageId:{type:"string",description:"Page id/URL to start a NEW top-level comment on (used when discussionId is absent)."},text:{type:"string",description:"The comment body (plain text)."}},required:["text"]}}]};import{existsSync as Zl,readFileSync as Vl}from"fs";import{fileURLToPath as Xl}from"url";import{dirname as Ql,resolve as ed}from"path";import{resolveIntegrationToken as xr,clearTokenCache as td}from"@zibby/core/backend-client.js";function rd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ql(Xl(import.meta.url)),t=ed(r,"..","bin","mcp-skill.mjs");return Zl(t)?t:null}function nd(){let r=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!r)return null;let t=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:r,memberId:t}}function sd(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function id(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var od="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 Lr(){let r=nd();if(r)return r;if(sd()||id())throw new Error(od);return null}var ad="202506",cd="https://api.linkedin.com";function ws(r){if(r==null)return null;let t=String(r).trim();if(!t)return null;let e=t.match(/urn:li:organization:(\d+)/i);return e?e[1]:/^\d+$/.test(t)?t:null}function Ss(r){if(!r)return"";if(r.localizedName)return String(r.localizedName);let t=r.name&&r.name.localized;if(t&&typeof t=="object"){let e=Object.values(t)[0];if(e)return String(e)}return""}function Ht(r,t){return r?typeof r.get=="function"?r.get(t):r[t]||r[t.toLowerCase()]||null:null}async function Te(r,t={},e="linkedin_business"){let n=async()=>{let s;if(e==="linkedin_personal"){let l=Lr();l&&(s=l.token)}if(s||({token:s}=await xr(e)),typeof s!="string"||!s)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let i=r.startsWith("https://")?r:`${cd}${r}`,o=await fetch(i,{method:t.method||"GET",headers:{Authorization:`Bearer ${s}`,"LinkedIn-Version":ad,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${l.slice(0,300)}`)}let a=await o.text().catch(()=>""),c={};if(a&&a.trim())try{c=JSON.parse(a)}catch{c={raw:a}}return{status:o.status,headers:o.headers,body:c}};try{return await n()}catch(s){let i=String(s?.message||s||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw s;return td(e),n()}}async function ld(r){let t;if(r==="linkedin_personal"){let e=Lr();e&&(t=e.token)}if(t||({token:t}=await xr(r)),typeof t!="string"||!t)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return t}function dd(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 vs(r,t,e,n){if(typeof e!="string"||!e.trim())throw new Error("imagePath (a local image file path) is required to upload an image");let{body:s}=await Te("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:t}}},r),i=s?.value?.uploadUrl,o=s?.value?.image;if(!i||!o)throw new Error(`LinkedIn image initializeUpload returned no uploadUrl/image (got: ${JSON.stringify(s).slice(0,200)})`);let a=Vl(e),c=await ld(r),l=await fetch(i,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":n||dd(e)},body:a});if(!l.ok){let d=await l.text().catch(()=>"");throw new Error(`LinkedIn image upload ${l.status}: ${d.slice(0,300)}`)}return o}var Is={id:"linkedin",callsBackend:!0,serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn
|
|
389
|
+
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=Vd();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let s=await le(`/pages/${n}`),i=ri(s),o=s?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,c=await oi(n,0,{used:0}),l=!1;return c.length>ar&&(c=c.slice(0,ar),l=!0),JSON.stringify({ok:!0,id:n,title:i,url:o,text:c,...l?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let i={page_size:Math.max(1,Math.min(Number(e?.maxResults)||ei,ei))};e?.filter&&typeof e.filter=="object"&&(i.filter=e.filter);let o=await le(`/databases/${n}/query`,{method:"POST",body:i}),c=(Array.isArray(o.results)?o.results:[]).map(l=>{let d={};for(let[p,u]of Object.entries(l.properties||{})){let m=sp(u);m&&(d[p]=m)}return{id:l.id,title:ri(l),url:l.url||`https://www.notion.so/${String(l.id||"").replace(/-/g,"")}`,props:d}});return JSON.stringify({ok:!0,id:n,count:c.length,hasMore:!!o.has_more,rows:c})}case"notion_create_page":{let 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?ge(e.databaseId):null,s=e?.parentPageId?ge(e.parentPageId):ge(e?.parent||e?.pageId);if(!n&&!s)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let i=n?{database_id:n}:{page_id:s},o={title:{title:wt(t)}},a=ni(e)||[],c=a.slice(0,cr),l=await le("/pages",{method:"POST",body:{parent:i,properties:o,...c.length?{children:c}:{}}}),d=l?.id;if(!d)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let p=a.slice(cr);return p.length&&await si(d,p),JSON.stringify({ok:!0,pageId:d,url:l?.url||rn(d)})}case"notion_append_blocks":{let t=ge(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=ni(e);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await si(t,n),JSON.stringify({ok:!0,pageId:t,url:rn(t)}))}case"notion_insert_image":{let t=ge(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()?wt(e.caption.trim()):null,s,i;if(typeof e?.imagePath=="string"&&e.imagePath.trim())i=await ap(e.imagePath),s={type:"file_upload",file_upload:{id:i}};else if(typeof e?.imageUrl=="string"&&e.imageUrl.trim())s={type:"external",external:{url:e.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return n&&(s.caption=n),await le(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:s}]}}),JSON.stringify({ok:!0,pageId:t,url:rn(t),...i?{fileUploadId:i}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,n=ge(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let s=new URLSearchParams({block_id:n,page_size:"100"}),i=await le(`/comments?${s.toString()}`),a=(Array.isArray(i.results)?i.results:[]).map(np);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,s;if(n)s={discussion_id:String(n),rich_text:wt(t)};else{let o=e?.pageId||e?.page||e?.url||e?.id,a=ge(o);if(!a)return JSON.stringify({ok:!1,error:"Either discussionId (to reply) or a valid pageId (to start a comment) is required"});s={parent:{page_id:a},rich_text:wt(t)}}let i=await le("/comments",{method:"POST",body:s});return JSON.stringify({ok:!0,id:i?.id||"",discussionId:i?.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 cp,readFileSync as lp}from"fs";import{fileURLToPath as dp}from"url";import{dirname as pp,resolve as up}from"path";import{resolveIntegrationToken as nn,clearTokenCache as mp}from"@zibby/core/backend-client.js";function hp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=pp(dp(import.meta.url)),e=up(r,"..","bin","mcp-skill.mjs");return cp(e)?e:null}function fp(){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 yp(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function gp(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var bp="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 sn(){let r=fp();if(r)return r;if(yp()||gp())throw new Error(bp);return null}var _p="202506",kp="https://api.linkedin.com";function ci(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 li(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 lr(r,e){return r?typeof r.get=="function"?r.get(e):r[e]||r[e.toLowerCase()]||null:null}async function Ce(r,e={},t="linkedin_business"){let n=async()=>{let s;if(t==="linkedin_personal"){let l=sn();l&&(s=l.token)}if(s||({token:s}=await nn(t)),typeof s!="string"||!s)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let i=r.startsWith("https://")?r:`${kp}${r}`,o=await w(i,{method:e.method||"GET",headers:{Authorization:`Bearer ${s}`,"LinkedIn-Version":_p,"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},{kind:"api",what:`LinkedIn ${e.method||"GET"} ${r}`});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${l.slice(0,300)}`)}let a=await o.text().catch(()=>""),c={};if(a&&a.trim())try{c=JSON.parse(a)}catch{c={raw:a}}return{status:o.status,headers:o.headers,body:c}};try{return await n()}catch(s){let i=String(s?.message||s||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw s;return mp(t),n()}}async function wp(r){let e;if(r==="linkedin_personal"){let t=sn();t&&(e=t.token)}if(e||({token:e}=await nn(r)),typeof e!="string"||!e)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return e}function Sp(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 di(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:s}=await Ce("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:e}}},r),i=s?.value?.uploadUrl,o=s?.value?.image;if(!i||!o)throw new Error(`LinkedIn image initializeUpload returned no uploadUrl/image (got: ${JSON.stringify(s).slice(0,200)})`);let a=lp(t),c=await wp(r),l=await w(i,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":n||Sp(t)},body:a},{kind:"transfer",what:"LinkedIn image upload"});if(!l.ok){let d=await l.text().catch(()=>"");throw new Error(`LinkedIn image upload ${l.status}: ${d.slice(0,300)}`)}return o}var pi={id:"linkedin",callsBackend:!0,serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn
|
|
392
390
|
You can post to LinkedIn two ways \u2014 an ORG company Page (business) and your own member PROFILE (personal). Each path needs its own LinkedIn integration connected.
|
|
393
391
|
|
|
394
392
|
Business (company Page) \u2014 DRAFT only:
|
|
@@ -404,19 +402,19 @@ Attaching an image (optional, both tools):
|
|
|
404
402
|
Notes:
|
|
405
403
|
- Org-page posts are ALWAYS created as a DRAFT; personal-profile posts are ALWAYS published live \u2014 choose the tool accordingly.
|
|
406
404
|
- PUBLISHING IS OUTWARD-FACING AND IRREVERSIBLE. linkedin_publish_post posts live to a real audience the instant you call it \u2014 there is no undo and no draft state for member profiles. Only call it after the human has EXPLICITLY approved publishing THIS specific text in THIS conversation. If you wrote or edited the text, show it and get an explicit "yes, publish" first; if you are unsure, HOLD/draft rather than publish. The org draft tool (linkedin_create_draft_post) is the safe default when a human still needs to review.
|
|
407
|
-
- If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=rd();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/linkedin.js","linkedinSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"linkedin_list_organizations":{let{body:e}=await Te("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(e.elements)?e.elements:[],s=[];for(let i of n){let o=i.organizationalTarget||i["organizationalTarget~"]||i.organization,a=ws(o);if(!a)continue;let c="",l="";try{let d=(await Te(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=Ss(d),l=d.vanityName||""}catch{}s.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:l})}return JSON.stringify({ok:!0,count:s.length,organizations:s})}case"linkedin_create_draft_post":{let e=t?.organizationUrn||t?.organizationId||t?.organization||t?.orgId,n=ws(e);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let s=t?.text;if(typeof s!="string"||!s.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let i=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof t?.imagePath=="string"?t.imagePath.trim():"",c=typeof t?.imageAltText=="string"?t.imageAltText:"";if(t?.dry_run===!0)try{let u="";try{let m=(await Te(`/rest/organizations/${n}`,{},"linkedin_business")).body;u=Ss(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:n,urn:o},visibility:i,textPreview:s,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let l={author:o,commentary:s,visibility:i,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await vs("linkedin_business",o,a);l.content={media:{id:u,altText:c||""}}}let d=await Te("/rest/posts",{method:"POST",body:l},"linkedin_business"),p=Ht(d.headers,"x-restli-id")||Ht(d.headers,"x-linkedin-id")||d.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"DRAFT",visibility:i,status:d.status})}case"linkedin_publish_post":{let e=Lr(),n=e?e.memberId:(await xr("linkedin_personal")).memberId;if(!n)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let s=t?.text;if(typeof s!="string"||!s.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let i=t?.visibility?String(t.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof t?.imagePath=="string"?t.imagePath.trim():"",c=typeof t?.imageAltText=="string"?t.imageAltText:"";if(t?.dry_run===!0)try{let u=(await Te("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",h=u?.sub?String(u.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:h,urn:`urn:li:person:${h}`},visibility:i,textPreview:s,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let l={author:o,commentary:s,visibility:i,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await vs("linkedin_personal",o,a);l.content={media:{id:u,altText:c||""}}}let d=await Te("/rest/posts",{method:"POST",body:l},"linkedin_personal"),p=Ht(d.headers,"x-restli-id")||Ht(d.headers,"x-linkedin-id")||d.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"PUBLISHED",visibility:i,status:d.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}}]};import{existsSync as As,statSync as pd,readFileSync as ud}from"fs";import{fileURLToPath as md}from"url";import{basename as hd,dirname as fd,resolve as yd}from"path";import{resolveIntegrationToken as gd,clearTokenCache as _d}from"@zibby/core/backend-client.js";function bd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=fd(md(import.meta.url)),t=yd(r,"..","bin","mcp-skill.mjs");return As(t)?t:null}var Oe="https://docs.googleapis.com/v1",Ns="https://www.googleapis.com/drive/v3",kd="https://www.googleapis.com/upload/drive/v3",wd=5*1024*1024;function Sd(){let r=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!r)return null;let t=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:r,email:t}}function vd(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Id(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Nd="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.",$r=2e4,Td=25;function jr(r){if(!r||typeof r!="string")return null;let t=r.trim(),e=t.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return e?e[1]:/^[a-zA-Z0-9_-]{20,}$/.test(t)?t:null}async function Od(){let r,t=Sd();if(t)r=t.token;else{if(Id()||vd())throw new Error(Nd);({token:r}=await gd("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function ie(r,t={}){let e=async()=>{let n=await Od(),s=await fetch(r,{method:t.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...t.rawBody&&t.contentType?{"Content-Type":t.contentType}:t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.rawBody?t.rawBody:t.body?JSON.stringify(t.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Google API ${s.status}: ${o.slice(0,300)}`)}let i=await s.text().catch(()=>"");if(!i||!i.trim())return{};try{return JSON.parse(i)}catch{return{raw:i}}};try{return await e()}catch(n){let s=String(n?.message||n||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw n;return _d("google"),e()}}function Ad(r){let t=[],e="",n=0;for(;n<r.length;){let s=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(s){t.push({start:e.length,end:e.length+s[1].length,link:s[2]}),e+=s[1],n+=s[0].length;continue}let i=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(i){t.push({start:e.length,end:e.length+i[1].length,bold:!0}),e+=i[1],n+=i[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(n));if(o){t.push({start:e.length,end:e.length+o[1].length,code:!0}),e+=o[1],n+=o[0].length;continue}e+=r[n],n+=1}return{text:e,styles:t}}function Ts(r,t){let e=String(r??"").replace(/\r\n/g,`
|
|
408
|
-
`);if(!
|
|
409
|
-
`),s="",i=[],o=[];for(let d of n){let p=d,u=null,m=null,h=/^(#{1,3})\s+(.*)$/.exec(p),
|
|
410
|
-
`,i.push({start:g,end:
|
|
405
|
+
- If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=hp();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_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 Ce("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(t.elements)?t.elements:[],s=[];for(let i of n){let o=i.organizationalTarget||i["organizationalTarget~"]||i.organization,a=ci(o);if(!a)continue;let c="",l="";try{let d=(await Ce(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=li(d),l=d.vanityName||""}catch{}s.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:l})}return JSON.stringify({ok:!0,count:s.length,organizations:s})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,n=ci(t);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let s=e?.text;if(typeof s!="string"||!s.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let i=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u="";try{let m=(await Ce(`/rest/organizations/${n}`,{},"linkedin_business")).body;u=li(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:n,urn:o},visibility:i,textPreview:s,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let l={author:o,commentary:s,visibility:i,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await di("linkedin_business",o,a);l.content={media:{id:u,altText:c||""}}}let d=await Ce("/rest/posts",{method:"POST",body:l},"linkedin_business"),p=lr(d.headers,"x-restli-id")||lr(d.headers,"x-linkedin-id")||d.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"DRAFT",visibility:i,status:d.status})}case"linkedin_publish_post":{let t=sn(),n=t?t.memberId:(await nn("linkedin_personal")).memberId;if(!n)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let s=e?.text;if(typeof s!="string"||!s.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let i=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u=(await Ce("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",h=u?.sub?String(u.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:h,urn:`urn:li:person:${h}`},visibility:i,textPreview:s,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let l={author:o,commentary:s,visibility:i,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await di("linkedin_personal",o,a);l.content={media:{id:u,altText:c||""}}}let d=await Ce("/rest/posts",{method:"POST",body:l},"linkedin_personal"),p=lr(d.headers,"x-restli-id")||lr(d.headers,"x-linkedin-id")||d.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"PUBLISHED",visibility:i,status:d.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 fi,statSync as vp,readFileSync as Ip}from"fs";import{fileURLToPath as Tp}from"url";import{basename as Np,dirname as Op,resolve as Ap}from"path";import{resolveIntegrationToken as Rp,clearTokenCache as Ep}from"@zibby/core/backend-client.js";function xp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Op(Tp(import.meta.url)),e=Ap(r,"..","bin","mcp-skill.mjs");return fi(e)?e:null}var Ue="https://docs.googleapis.com/v1",ui="https://www.googleapis.com/drive/v3",Lp="https://www.googleapis.com/upload/drive/v3",$p=5*1024*1024;function jp(){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 Pp(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Cp(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Up="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.",an=2e4,Bp=25;function on(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 Dp(){let r,e=jp();if(e)r=e.token;else{if(Cp()||Pp())throw new Error(Up);({token:r}=await Rp("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function de(r,e={}){let t=async()=>{let n=await Dp(),s=await w(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},{kind:e.rawBody?"transfer":"api",what:`Google ${e.method||"GET"} ${String(r).split("?")[0]}`});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Google API ${s.status}: ${o.slice(0,300)}`)}let i=await s.text().catch(()=>"");if(!i||!i.trim())return{};try{return JSON.parse(i)}catch{return{raw:i}}};try{return await t()}catch(n){let s=String(n?.message||n||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw n;return Ep("google"),t()}}function Mp(r){let e=[],t="",n=0;for(;n<r.length;){let s=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(s){e.push({start:t.length,end:t.length+s[1].length,link:s[2]}),t+=s[1],n+=s[0].length;continue}let i=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(i){e.push({start:t.length,end:t.length+i[1].length,bold:!0}),t+=i[1],n+=i[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 mi(r,e){let t=String(r??"").replace(/\r\n/g,`
|
|
406
|
+
`);if(!t.trim())return{requests:[],endIndex:e};let n=t.split(`
|
|
407
|
+
`),s="",i=[],o=[];for(let d of n){let p=d,u=null,m=null,h=/^(#{1,3})\s+(.*)$/.exec(p),y=/^\s*[-*]\s+(.*)$/.exec(p),_=/^\s*\d+[.)]\s+(.*)$/.exec(p);h?(u=`HEADING_${h[1].length}`,p=h[2]):y?(m="BULLET_DISC_CIRCLE_SQUARE",p=y[1]):_&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",p=_[1]);let{text:f,styles:b}=Mp(p),g=e+s.length;for(let k of b)o.push({...k,start:g+k.start,end:g+k.end});s+=`${f}
|
|
408
|
+
`,i.push({start:g,end:e+s.length,named:u,bullet:m})}if(!s)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:s}}];for(let d of i)d.named&&a.push({updateParagraphStyle:{range:{startIndex:d.start,endIndex:d.end},paragraphStyle:{namedStyleType:d.named},fields:"namedStyleType"}});let c=null,l=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let d of i)d.bullet?c&&c.preset===d.bullet?c.end=d.end:(l(),c={start:d.start,end:d.end,preset:d.bullet}):l();l();for(let d of o)d.end<=d.start||(d.bold?a.push({updateTextStyle:{range:{startIndex:d.start,endIndex:d.end},textStyle:{bold:!0},fields:"bold"}}):d.link?a.push({updateTextStyle:{range:{startIndex:d.start,endIndex:d.end},textStyle:{link:{url:d.link}},fields:"link"}}):d.code&&a.push({updateTextStyle:{range:{startIndex:d.start,endIndex:d.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:e+s.length}}function Jp(r){let e="",t=n=>{for(let s of Array.isArray(n)?n:[]){if(e.length>=an)return;if(s.paragraph)for(let i of s.paragraph.elements||[])e+=i?.textRun?.content||"";else if(s.table)for(let i of s.table.tableRows||[])for(let o of i.tableCells||[])t(o.content);else s.tableOfContents&&t(s.tableOfContents.content)}};return t(r?.content),e.slice(0,an)}var St=r=>`https://docs.google.com/document/d/${r}/edit`;function qp(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!fi(e)||!vp(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=Ip(e);if(t.length>$p)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:Np(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Gp(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
|
|
411
409
|
Content-Type: application/json; charset=UTF-8\r
|
|
412
410
|
\r
|
|
413
411
|
${JSON.stringify(r)}\r
|
|
414
412
|
--${n}\r
|
|
415
|
-
Content-Type: ${
|
|
413
|
+
Content-Type: ${t}\r
|
|
416
414
|
\r
|
|
417
|
-
`,"utf8"),
|
|
415
|
+
`,"utf8"),e,Buffer.from(`\r
|
|
418
416
|
--${n}--\r
|
|
419
|
-
`,"utf8")]),contentType:`multipart/related; boundary=${n}`}}var
|
|
417
|
+
`,"utf8")]),contentType:`multipart/related; boundary=${n}`}}var hi=r=>{let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t},yi={id:"google-docs",callsBackend:!0,serverName:"gdocs",allowedTools:["mcp__gdocs__*"],requiresIntegration:I.GOOGLE,description:"Google Docs \u2014 create, append to, insert images into, and read Google Docs (drive.file scoped)",promptFragment:`## Google Docs
|
|
420
418
|
You can create and edit Google Docs for the user. IMPORTANT visibility caveat: the integration uses Google's per-file drive.file scope, so you can only see docs this app CREATED (or the user explicitly picked) \u2014 not the user's whole Drive.
|
|
421
419
|
Docs access is PER-USER: each teammate connects their OWN Google account (Integrations \u2192 Google Docs). In shared-chat contexts the runtime routes these tools to the SENDER's own Google; a teammate who hasn't connected their own Google gets { ok:false } with connect instructions \u2014 for privacy the project owner's Google is NEVER used on someone else's behalf. Relay those instructions rather than retrying.
|
|
422
420
|
- gdocs_create_doc: create a new Google Doc from a title + markdown (headings/bold/bullets/links supported) or plain text; returns { documentId, url }. Share the url with the user.
|
|
@@ -424,17 +422,17 @@ Docs access is PER-USER: each teammate connects their OWN Google account (Integr
|
|
|
424
422
|
- gdocs_insert_image: append a LOCAL image file (png/jpg, \u22645MB) to the end of a doc \u2014 pass { documentId, imagePath, width?, height? } (width/height in PT, optional). The image is uploaded to the user's Drive and made link-readable (anyone with the link) so Docs can render it. Returns { ok, documentId, fileId, url }.
|
|
425
423
|
- gdocs_get: read a doc back as plain text (works for app-created/user-picked docs only; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker \u2014 drive.file has no access to un-picked files).
|
|
426
424
|
- gdocs_list_created: list the Google Docs visible to this app (drive.file \u2192 only docs it created or the user picked).
|
|
427
|
-
These tools return { ok:false, error } on failure \u2014 treat an unavailable Google connection as "cannot deliver to Docs" and report it rather than blocking the task.`,resolve(){let r=
|
|
428
|
-
`}}),d=c+1);let p=
|
|
429
|
-
`),
|
|
430
|
-
`)){let s=n.replace(/\s+$/,"");if(!s.trim())continue;let i=/^(#{1,3})\s+(.*)$/.exec(s),o=/^\s*[-*]\s+(.*)$/.exec(s),a=/^\s*\d+[.)]\s+(.*)$/.exec(s),c,l,d;if(i){let p=i[1].length;c=`heading${p}`,l=2+p,d=i[2]}else o?(c="bullet",l=12,d=o[1]):a?(c="ordered",l=13,d=a[1]):(c="text",l=2,d=s);e.push({block_type:l,[c]:{elements:[{text_run:{content:d}}],style:{}}})}return e}function ut(r){let t=typeof r?.markdown=="string"?r.markdown:null,e=typeof r?.text=="string"?r.text:null;return t??e}async function Ur(r,t){let e;for(let n=0;n<t.length;n+=js){let s=t.slice(n,n+js);e=(await z("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:s})).host}return e}function Yd(r){let t=typeof r=="string"?r.trim():"";if(!t)throw new Error("imagePath is required");if(!Ps(t)||!$d(t).isFile())throw new Error(`imagePath not found (or not a file): ${t}`);if(!/\.(png|jpe?g)$/i.test(t))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let e=Pd(t);if(e.length>Fd)throw new Error(`image is ${(e.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return e}async function zd({fileName:r,parentNode:t,bytes:e}){let{token:n,host:s}=await Cs(),i=new FormData;i.set("file_name",r),i.set("parent_type","docx_image"),i.set("parent_node",t),i.set("size",String(e.length)),i.set("file",new Blob([e]),r);let a=await(await fetch(`${s}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${n}`},body:i})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var Wd="docx",Zd=50;function $s(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function Vd(r){return Array.isArray(r)?r.map(t=>t?.text_run?.text??t?.docs_link?.url??(t?.person?`@${t.person.user_id||""}`:"")).join(""):""}function Xd(r){let t=Array.isArray(r?.reply_list?.replies)?r.reply_list.replies:[];return{commentId:r?.comment_id||"",resolved:!!r?.is_solved,replies:t.map(e=>({replyId:e?.reply_id||"",author:e?.user_id||"",text:Vd(e?.content?.elements),createTime:e?.create_time||""}))}}function Br(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():Wd}var Us={id:"lark-docs",callsBackend:!0,serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:[S.LARK_DOCS,S.LARK],description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV",...Gd],promptFragment:'## Lark Docs\nYou can read, create, and append Lark/Feishu documents (docx), and read/post/reply to their comments. This runs on the connected Lark Docs app (the chat app is used when no separate docs app is connected). Each `larkdoc_*` / `larkwiki_*` tool documents its own params and return shape in its tool description \u2014 they are not restated here.\nThese tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.',resolve(){let r=Jd();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"larkdoc_get":{let e=t?.documentId||t?.url||t?.id,n=Ae(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=await Ke(n),i="";try{i=(await z("GET",`/open-apis/docx/v1/documents/${s}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await z("GET",`/open-apis/docx/v1/documents/${s}/raw_content?lang=0`),c=String(o?.content||""),l=!1;return c.length>Ls&&(c=c.slice(0,Ls),l=!0),JSON.stringify({ok:!0,documentId:s,title:i,url:pt(a,s),text:c,...l?{truncated:!0}:{}})}case"larkdoc_create":{let e=typeof t?.title=="string"&&t.title.trim()?t.title.trim():null;if(!e)return JSON.stringify({ok:!1,error:"title is required"});let n=typeof t?.wikiSpaceId=="string"&&t.wikiSpaceId.trim()?t.wikiSpaceId.trim():null;if(n){let c=typeof t?.parentNodeToken=="string"&&t.parentNodeToken.trim()?t.parentNodeToken.trim():null,{data:l,host:d}=await z("POST",`/open-apis/wiki/v2/spaces/${encodeURIComponent(n)}/nodes`,{obj_type:"docx",node_type:"origin",title:e,...c?{parent_node_token:c}:{}}),p=l?.node||{},u=p.obj_token;if(!u)return JSON.stringify({ok:!1,error:"Lark wiki node create returned no obj_token"});let m=ut(t);if(m&&m.trim()){let h=Cr(m);h.length&&await Ur(u,h)}return JSON.stringify({ok:!0,documentId:u,title:e,wikiSpaceId:n,wikiNodeToken:p.node_token||"",url:p.node_token?Hd(d,p.node_token):pt(d,u)})}let{data:s,host:i}=await z("POST","/open-apis/docx/v1/documents",{title:e,...t?.folderToken?{folder_token:String(t.folderToken)}:{}}),o=s?.document?.document_id;if(!o)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let a=ut(t);if(a&&a.trim()){let c=Cr(a);c.length&&await Ur(o,c)}return JSON.stringify({ok:!0,documentId:o,title:e,url:pt(i,o)})}case"larkdoc_append":{let e=t?.documentId||t?.url||t?.id,n=Ae(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=ut(t);if(!s||!s.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let i=await Ke(n),o=Cr(s);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await Ur(i,o);return JSON.stringify({ok:!0,documentId:i,url:pt(a,i)})}case"larkdoc_insert_image":{let e=t?.documentId||t?.url||t?.id,n=Ae(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!t?.imagePath||typeof t.imagePath!="string"||!t.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let s=await Ke(n),i=t.imagePath.trim(),o=Yd(i),a=Ud(i),l=(await z("POST",`/open-apis/docx/v1/documents/${s}/blocks/${s}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!l)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let d=await zd({fileName:a,parentNode:l,bytes:o}),p={token:d},u=Number(t?.width),m=Number(t?.height);Number.isFinite(u)&&u>0&&(p.width=Math.round(u)),Number.isFinite(m)&&m>0&&(p.height=Math.round(m));let{host:h}=await z("PATCH",`/open-apis/docx/v1/documents/${s}/blocks/${l}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:s,blockId:l,fileToken:d,url:pt(h,s)})}case"larkwiki_list_spaces":{let e=[],n=null;for(let s=0;s<qd;s++){let i=new URLSearchParams({page_size:String(Md)});n&&i.set("page_token",n);let{data:o}=await z("GET",`/open-apis/wiki/v2/spaces?${i.toString()}`),a=Array.isArray(o?.items)?o.items:[];for(let c of a)e.push({spaceId:String(c?.space_id||""),name:String(c?.name||"")});if(!o?.has_more||!o?.page_token)break;n=o.page_token}return JSON.stringify({ok:!0,count:e.length,spaces:e})}case"larkdoc_list_comments":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,n=Ae(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=await Ke(n),i=Br(t),o=new URLSearchParams({file_type:i,page_size:String(Zd)}),{data:a}=await z("GET",`/open-apis/drive/v1/files/${s}/comments?${o.toString()}`),l=(Array.isArray(a?.items)?a.items:[]).map(Xd);return JSON.stringify({ok:!0,documentId:s,count:l.length,comments:l})}case"larkdoc_add_comment":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,n=Ae(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=ut({text:t?.text??t?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let i=await Ke(n),o=Br(t),{data:a}=await z("POST",`/open-apis/drive/v1/files/${i}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:$s(s)}}]}});return JSON.stringify({ok:!0,documentId:i,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let e=t?.documentId||t?.url||t?.id||t?.fileToken,n=Ae(e);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=t?.commentId||t?.comment_id;if(!s)return JSON.stringify({ok:!1,error:"commentId is required"});let i=ut({text:t?.text??t?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Ke(n),a=Br(t),{data:c}=await z("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(s)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:$s(i)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(s),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Pass wikiSpaceId (from larkwiki_list_spaces) to create the doc INSIDE a wiki space instead of as a standalone doc \u2014 optionally nested under parentNodeToken. Returns { ok, documentId, url } (plus wikiNodeToken when created in a wiki) \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root. Ignored when wikiSpaceId is set."},wikiSpaceId:{type:"string",description:"Optional wiki space id (from larkwiki_list_spaces) \u2014 create the doc as a node inside this wiki space."},parentNodeToken:{type:"string",description:"Optional wiki node token to nest the new doc under (only with wikiSpaceId). Absent = the space root."}},required:["title"]}},{name:"larkwiki_list_spaces",description:"List the Lark/Feishu wiki spaces visible to the connected app. Returns { ok, count, spaces:[{ spaceId, name }] }. Use to discover the wikiSpaceId for larkdoc_create.",input_schema:{type:"object",properties:{}}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};import{existsSync as Qd}from"fs";import{fileURLToPath as ep}from"url";import{dirname as tp,resolve as rp}from"path";function np(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=tp(ep(import.meta.url)),t=rp(r,"..","bin","mcp-skill.mjs");return Qd(t)?t:null}var sp=6e3*1e3,mt=null,ip=50,op=50,ap=40,cp=31,lp=200,dp=31,pp=50,Bs=50,Ds=Object.freeze(["daily","month"]),Js=Object.freeze(["zh","en","ja"]),up=Object.freeze(["employee_id","employee_no"]),mp=Yt;async function hp(){let{appId:r,appSecret:t,host:e}=await zt();if(mt&&mt.appId===r&&mt.expiresAt>Date.now())return{token:mt.token,host:e};let s=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:t})})).json();if(s.code!==0)throw new Error(`Lark tenant_access_token failed: ${s.msg||s.code}`);return mt={token:s.tenant_access_token,expiresAt:Date.now()+sp,appId:r},{token:s.tenant_access_token,host:e}}function fp(r,t,e){let n=`Lark attendance API ${r} error ${t}: ${e||"(no message)"}`,s=r.includes("/attendance/v1/groups")?"attendance:rule:readonly (\u6253\u5361\u89C4\u5219/\u8003\u52E4\u7EC4 \u8BFB\u53D6)":r.includes("/contact/v3/users")?"contact:user.id:readonly (\u90AE\u7BB1 \u2192 \u7528\u6237 ID)":"attendance:task:readonly (\u6253\u5361\u7ED3\u679C/\u7EDF\u8BA1\u6570\u636E \u8BFB\u53D6)";return String(t)==="99991672"||/permission|scope|权限/i.test(String(e||""))?`${n}. The connected Lark app is missing the ${s} permission \u2014 add it in the Lark/Feishu developer console (\u5F00\u53D1\u8005\u540E\u53F0 > \u6743\u9650\u7BA1\u7406), then RE-PUBLISH a new app version so the scope takes effect.`:String(t)==="1220002"?`${n}. The tenant token was rejected \u2014 the Lark integration's app credentials look wrong; reconnect Lark in Integrations.`:String(t)==="1220001"?`${n}. Lark rejected the parameters \u2014 check the date range (yyyyMMdd, and within the documented span), stats_type, and that every user id matches the employeeType you passed.`:n}async function Ge(r,t,e){let{token:n,host:s}=await hp(),i={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&e!==void 0&&(i.body=JSON.stringify(e));let a=await(await fetch(`${s}${t}`,i)).json();if(a.code!==0)throw new Error(fp(t,a.code,a.msg));return a.data||{}}function Ms(r){if(r==null||r==="")return null;let t=String(r).trim().replace(/[-/.]/g,"");if(!/^\d{8}$/.test(t))return null;let e=Number(t.slice(0,4)),n=Number(t.slice(4,6)),s=Number(t.slice(6,8));if(e<1970||e>9999||n<1||n>12||s<1||s>31)return null;let i=new Date(Date.UTC(e,n-1,s));return i.getUTCFullYear()!==e||i.getUTCMonth()!==n-1||i.getUTCDate()!==s?null:Number(t)}function yp(r,t){let e=n=>Date.UTC(Math.floor(n/1e4),Math.floor(n%1e4/100)-1,n%100);return Math.floor((e(t)-e(r))/864e5)+1}function Dr(r,t){let e=Ms(r?.startDate??r?.start_date),n=Ms(r?.endDate??r?.end_date);if(!e||!n)return{error:"startDate and endDate are required, as yyyyMMdd (e.g. 20260401) or YYYY-MM-DD"};if(n<e)return{error:"endDate must not be earlier than startDate"};let s=yp(e,n);return s>t?{error:`Lark caps this query at ${t} days; the requested range is ${s} days. Split it into consecutive windows and merge the results.`}:{startDate:e,endDate:n}}function qs(r,t){let e=r?.userIds??r?.user_ids,n=(Array.isArray(e)?e:typeof e=="string"?[e]:[]).map(s=>String(s||"").trim()).filter(Boolean);return n.length?n.length>t?{error:`Lark accepts at most ${t} user ids per call; ${n.length} were passed. Split into batches.`}:{ids:n}:{error:"userIds is required \u2014 attendance data is personal, so this tool never returns a whole tenant. Get the ids from larkattendance_get_group (bind_user_ids) or larkattendance_resolve_users."}}function ht(r,t,e){let n=String(r||"").trim().toLowerCase();return t.includes(n)?n:e}function Wt(r){return ht(r?.employeeType??r?.employee_type,up,"employee_id")}function gp(r){return{code:String(r?.code||""),title:String(r?.title||""),fields:(Array.isArray(r?.child_fields)?r.child_fields:[]).map(t=>({code:String(t?.code||""),title:String(t?.title||""),...t?.time_unit?{timeUnit:String(t.time_unit)}:{}}))}}function _p(r,t){let n=(Array.isArray(r?.datas)?r.datas:[]).filter(s=>!t||t.has(String(s?.code||""))||t.has(String(s?.title||""))).map(s=>({code:String(s?.code||""),title:String(s?.title||""),value:s?.value===void 0||s?.value===null?"":String(s.value),...s?.duration_num?{durationNum:s.duration_num}:{},...Array.isArray(s?.features)&&s.features.length?{features:s.features}:{}}));return{userId:String(r?.user_id||""),name:String(r?.name||""),fields:n}}function bp(r){return{userId:String(r?.user_id||""),name:String(r?.employee_name||""),day:r?.day??null,groupId:String(r?.group_id||""),shiftId:String(r?.shift_id||""),records:(Array.isArray(r?.records)?r.records:[]).map(t=>({checkInTime:t?.check_in_record?.check_time??null,checkInResult:String(t?.check_in_result||""),checkInResultSupplement:String(t?.check_in_result_supplement||""),checkInShiftTime:t?.check_in_shift_time??null,checkOutTime:t?.check_out_record?.check_time??null,checkOutResult:String(t?.check_out_result||""),checkOutResultSupplement:String(t?.check_out_result_supplement||""),checkOutShiftTime:t?.check_out_shift_time??null,...t?.task_shift_type===void 0?{}:{taskShiftType:t.task_shift_type}}))}}var Fs={id:"lark-attendance",callsBackend:!0,serverName:"larkattendance",allowedTools:["mcp__larkattendance__*"],requiresIntegration:[S.LARK_DOCS,S.LARK],description:"Lark / Feishu attendance (\u8003\u52E4) \u2014 discover attendance groups and statistic fields, then read per-user work-hour / attendance statistics and clock-in records. Read-only.",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV",...mp],promptFragment:"## Lark Attendance (\u8003\u52E4)\nRead-only access to this tenant's Lark/Feishu attendance data. NOTHING about the tenant's setup is known in advance \u2014 group names, what counts as \"\u5DE5\u65F6\", and the per-tenant \u81EA\u5B9A\u4E49\u5B57\u6BB5 all differ \u2014 so DISCOVER before you fetch:\n1. `larkattendance_list_groups` \u2192 the \u8003\u52E4\u7EC4 that exist.\n2. `larkattendance_get_group` \u2192 that group's member user ids (the scope for every data call).\n3. `larkattendance_list_stats_fields` \u2192 every statistic column available for the period, INCLUDING this tenant's \u81EA\u5B9A\u4E49\u5B57\u6BB5. Match the user's words (\"\u5DE5\u65F6\", \"\u51FA\u52E4\u5929\u6570\", \u2026) against the returned `title`s and pass the matching `code`s onward.\n4. `larkattendance_query_stats` (aggregated numbers) and/or `larkattendance_query_records` (raw clock-in/out).\n`larkattendance_query_stats` also needs an `operatorUserId` \u2014 the attendance admin the query runs AS. Lark rejects the call without one, and it selects the saved statistics view that decides which columns come back, so this skill refuses to invent it: if the prompt did not supply one, ASK for it rather than substituting a member id.\nIdentity mapping: attendance ids are the tenant `user_id` (employee_id), NOT the `open_id` the `lark` skill's `lark_lookup_user_by_email` returns \u2014 use `larkattendance_resolve_users` to turn emails into attendance ids. For chat/DM routing keep using the `lark` skill's tools.\nAttendance is personal HR data: every data tool requires an explicit `userIds` list, and there is no whole-tenant dump. Report the numbers as returned; do not invent a column the tenant does not have.\nThese tools return { ok:false, error } on failure \u2014 read the error, it names the missing permission or the range limit.",resolve(){let r=np();if(!r)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/larkAttendance.js","larkAttendanceSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"larkattendance_list_groups":{let e=Number(t?.pageSize??t?.page_size),n=Number.isFinite(e)&&e>0?Math.min(Math.floor(e),ip):op,s=new URLSearchParams({page_size:String(n)}),i=String(t?.pageToken??t?.page_token??"").trim();i&&s.set("page_token",i);let o=await Ge("GET",`/open-apis/attendance/v1/groups?${s.toString()}`),a=(Array.isArray(o?.group_list)?o.group_list:[]).map(c=>({groupId:String(c?.group_id||""),groupName:String(c?.group_name||"")}));return JSON.stringify({ok:!0,count:a.length,groups:a,hasMore:!!o?.has_more,...o?.has_more&&o?.page_token?{pageToken:String(o.page_token)}:{}})}case"larkattendance_get_group":{let e=String(t?.groupId??t?.group_id??"").trim();if(!e)return JSON.stringify({ok:!1,error:"groupId is required (from larkattendance_list_groups)"});let n=Wt(t),s=new URLSearchParams({employee_type:n,dept_type:"open_id"}),i=await Ge("GET",`/open-apis/attendance/v1/groups/${encodeURIComponent(e)}?${s.toString()}`),o=a=>Array.isArray(a)?a.map(c=>String(c)):[];return JSON.stringify({ok:!0,groupId:String(i?.group_id||e),groupName:String(i?.group_name||""),employeeType:n,memberUserIds:o(i?.bind_user_ids),memberDeptIds:o(i?.bind_dept_ids),excludedUserIds:o(i?.except_user_ids),excludedDeptIds:o(i?.except_dept_ids),noPunchUserIds:o(i?.bind_default_user_ids),noPunchDeptIds:o(i?.bind_default_dept_ids),...Array.isArray(i?.group_leader_ids)?{leaderUserIds:o(i.group_leader_ids)}:{}})}case"larkattendance_list_stats_fields":{let e=Dr(t,ap);if(e.error)return JSON.stringify({ok:!1,error:e.error});let n=ht(t?.statsType??t?.stats_type,Ds,"month"),s=ht(t?.locale,Js,"zh"),i=Wt(t),a=(await Ge("POST",`/open-apis/attendance/v1/user_stats_fields/query?employee_type=${encodeURIComponent(i)}`,{locale:s,stats_type:n,start_date:e.startDate,end_date:e.endDate}))?.user_stats_field||{},c=(Array.isArray(a?.fields)?a.fields:[]).map(gp);return JSON.stringify({ok:!0,statsType:n,locale:s,startDate:e.startDate,endDate:e.endDate,fieldGroupCount:c.length,fieldGroups:c})}case"larkattendance_query_stats":{let e=Dr(t,cp);if(e.error)return JSON.stringify({ok:!1,error:e.error});let n=qs(t,lp);if(n.error)return JSON.stringify({ok:!1,error:n.error});let s=ht(t?.statsType??t?.stats_type,Ds,"month"),i=ht(t?.locale,Js,"zh"),o=Wt(t),a=String(t?.operatorUserId??t?.user_id??"").trim();if(!a)return JSON.stringify({ok:!1,error:'operatorUserId is required by Lark (the API rejects this call with 1220001 "Need user_id"). It is the OPERATOR performing the query \u2014 a third id, not one of `userIds` and not `employeeType`. It must be a user whose saved attendance statistics view contains the columns you want (normally an attendance admin), because that view decides which columns Lark returns. This skill will NOT pick one for you: substituting an arbitrary member would silently return the wrong column set instead of failing. Ask the caller/prompt for the attendance admin\'s user id, or resolve their email with larkattendance_resolve_users.'});let c={locale:i,stats_type:s,start_date:e.startDate,end_date:e.endDate,user_ids:n.ids,user_id:a,need_history:t?.needHistory===!0,current_group_only:t?.currentGroupOnly===!0},l=Array.isArray(t?.fieldCodes)?t.fieldCodes:null,d=l?l.map(h=>String(h||"").trim()).filter(Boolean):[],p=d.length?new Set(d):null,u=await Ge("POST",`/open-apis/attendance/v1/user_stats_datas/query?employee_type=${encodeURIComponent(o)}`,c),m=(Array.isArray(u?.user_datas)?u.user_datas:[]).map(h=>_p(h,p));return JSON.stringify({ok:!0,statsType:s,startDate:e.startDate,endDate:e.endDate,employeeType:o,userCount:m.length,users:m,invalidUserIds:Array.isArray(u?.invalid_user_list)?u.invalid_user_list.map(h=>String(h)):[]})}case"larkattendance_query_records":{let e=Dr({startDate:t?.startDate??t?.checkDateFrom??t?.check_date_from,endDate:t?.endDate??t?.checkDateTo??t?.check_date_to},dp);if(e.error)return JSON.stringify({ok:!1,error:e.error});let n=qs(t,pp);if(n.error)return JSON.stringify({ok:!1,error:n.error});let s=Wt(t),i=new URLSearchParams({employee_type:s,ignore_invalid_users:"true"});t?.includeTerminatedUser===!0&&i.set("include_terminated_user","true");let o=await Ge("POST",`/open-apis/attendance/v1/user_tasks/query?${i.toString()}`,{user_ids:n.ids,check_date_from:e.startDate,check_date_to:e.endDate,need_overtime_result:t?.needOvertimeResult===!0}),a=(Array.isArray(o?.user_task_results)?o.user_task_results:[]).map(bp);return JSON.stringify({ok:!0,startDate:e.startDate,endDate:e.endDate,employeeType:s,count:a.length,results:a,invalidUserIds:Array.isArray(o?.invalid_user_ids)?o.invalid_user_ids.map(c=>String(c)):[],unauthorizedUserIds:Array.isArray(o?.unauthorized_user_ids)?o.unauthorized_user_ids.map(c=>String(c)):[]})}case"larkattendance_resolve_users":{let e=t?.emails,n=(Array.isArray(e)?e:typeof e=="string"?[e]:[]).map(c=>String(c||"").trim()).filter(Boolean);if(!n.length)return JSON.stringify({ok:!1,error:"emails is required (a non-empty array of work email addresses)"});if(n.length>Bs)return JSON.stringify({ok:!1,error:`At most ${Bs} emails per call; ${n.length} were passed. Split into batches.`});let s=await Ge("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=user_id",{emails:n}),o=(Array.isArray(s?.user_list)?s.user_list:[]).filter(c=>c?.user_id).map(c=>({email:String(c?.email||""),userId:String(c.user_id)})),a=new Set(o.map(c=>c.email));return JSON.stringify({ok:!0,employeeType:"employee_id",users:o,notFound:n.filter(c=>!a.has(c))})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({ok:!1,error:e?.message||String(e)})}},tools:[{name:"larkattendance_list_groups",description:"DISCOVERY (start here). List this tenant's Lark/Feishu attendance groups (\u8003\u52E4\u7EC4) \u2014 their names are tenant-specific, so never assume one. Returns { ok, count, groups:[{ groupId, groupName }], hasMore, pageToken }. When hasMore is true, call again with pageToken to continue. Needs the attendance:rule:readonly permission on the connected Lark app.",input_schema:{type:"object",properties:{pageSize:{type:"number",description:"Groups per page, 1-50 (default 50)."},pageToken:{type:"string",description:"Cursor from a previous call's pageToken \u2014 omit for the first page."}}}},{name:"larkattendance_get_group",description:"DISCOVERY. Read one attendance group and, crucially, ITS MEMBERS \u2014 memberUserIds is the scope you pass as userIds to larkattendance_query_stats / larkattendance_query_records (a real group can hold hundreds, so expect to batch). Returns { ok, groupId, groupName, employeeType, memberUserIds, memberDeptIds, excludedUserIds, excludedDeptIds, noPunchUserIds, noPunchDeptIds }. THREE different exclusion lists, do not conflate them: excludedUserIds are removed from the group; noPunchUserIds are in the group but not required to clock in (they still have statistics). Members bound by DEPARTMENT appear in memberDeptIds, not memberUserIds \u2014 resolve those people another way (e.g. larkattendance_resolve_users from emails you already have). Lark does not reliably return the group leaders here, so leaderUserIds may be absent \u2014 never source the query operator id from this tool.",input_schema:{type:"object",properties:{groupId:{type:"string",description:"Attendance group id from larkattendance_list_groups."},employeeType:{type:"string",description:"Which id form to return members in: 'employee_id' (tenant user_id, the default and what every other tool here expects) or 'employee_no' (\u5DE5\u53F7)."}},required:["groupId"]}},{name:"larkattendance_list_stats_fields",description:'DISCOVERY \u2014 call this BEFORE larkattendance_query_stats. Lists every statistic column this tenant has for the period, grouped (e.g. \u57FA\u672C\u4FE1\u606F / \u51FA\u52E4\u7EDF\u8BA1 / \u5F02\u5E38\u7EDF\u8BA1 / \u6BCF\u65E5\u7EDF\u8BA1 / \u81EA\u5B9A\u4E49\u5B57\u6BB5). The \u81EA\u5B9A\u4E49\u5B57\u6BB5 group is tenant-defined and exists nowhere else, so this is the only way to learn its codes. Match the user\'s wording ("\u5DE5\u65F6", "\u51FA\u52E4\u5929\u6570", "\u8FDF\u5230\u6B21\u6570") against the returned `title`s and pass the matching `code`s as fieldCodes to larkattendance_query_stats. Returns { ok, statsType, locale, startDate, endDate, fieldGroups:[{ code, title, fields:[{ code, title, timeUnit }] }] }. Range is capped at 40 days.',input_schema:{type:"object",properties:{startDate:{type:"string",description:"Period start as yyyyMMdd (20260401) or YYYY-MM-DD."},endDate:{type:"string",description:"Period end, same format. At most 40 days after startDate."},statsType:{type:"string",description:"'month' (default) for period totals, or 'daily' for per-day columns."},locale:{type:"string",description:"Field-title language: 'zh' (default), 'en', or 'ja'."},employeeType:{type:"string",description:"'employee_id' (default) or 'employee_no'."}},required:["startDate","endDate"]}},{name:"larkattendance_query_stats",description:'The numbers: per-user attendance statistics (work hours, attendance days, exceptions, custom fields) for a period. Needs THREE separate things: userIds (whose data you want, max 200), operatorUserId (WHO IS ASKING \u2014 required by Lark, see below), and the date range (max 31 days). Attendance is personal data and there is no whole-tenant read; get ids from larkattendance_get_group or larkattendance_resolve_users. Returns { ok, statsType, startDate, endDate, users:[{ userId, name, fields:[{ code, title, value, durationNum? }] }], invalidUserIds }. Values are STRINGS exactly as Lark returns them \u2014 report them as-is, do not re-derive. EXPECT MANY COLUMNS: a one-month query returns roughly 40+ cells per person, because Lark mixes period totals (e.g. an "actual attendance hours" column, late/early counts) with identity columns (department, employee number) AND one column PER DAY of the range \u2014 so match on `title` rather than assuming a short list, and pass fieldCodes to trim. The exact set of columns follows the SAVED STATISTICS VIEW of the operatorUserId (\u8003\u52E4 > \u7EDF\u8BA1\u8BBE\u7F6E), so if a field that larkattendance_list_stats_fields advertises is missing from the result, it is switched off in that operator\'s view and an admin must enable it \u2014 or you are querying as the wrong operator.',input_schema:{type:"object",properties:{userIds:{type:"array",items:{type:"string"},description:"The people to report on, in the employeeType id form. Max 200. Required."},startDate:{type:"string",description:"Period start as yyyyMMdd (20260401) or YYYY-MM-DD."},endDate:{type:"string",description:"Period end, same format. At most 31 days after startDate."},statsType:{type:"string",description:"'month' (default) for period totals, or 'daily' for per-day rows."},fieldCodes:{type:"array",items:{type:"string"},description:"Optional filter \u2014 only these field codes/titles are returned. Omit to get every column."},locale:{type:"string",description:"Field-title language: 'zh' (default), 'en', or 'ja'."},employeeType:{type:"string",description:"'employee_id' (default) or 'employee_no' \u2014 must match the form of userIds."},operatorUserId:{type:"string",description:'REQUIRED. The user id of the OPERATOR performing the query \u2014 a third id, distinct from `userIds` (whose data you want) and from `employeeType` (the id form). Lark rejects the call without it (1220001 "Need user_id"). It should be an attendance admin whose saved statistics view contains the columns you need, because that view decides which columns come back. This skill will not pick one for you \u2014 get it from the caller/prompt, or from an email via larkattendance_resolve_users.'},needHistory:{type:"boolean",description:"Include transferred/departed staff (default false)."},currentGroupOnly:{type:"boolean",description:"Restrict to the user's current attendance group (default false)."}},required:["userIds","operatorUserId","startDate","endDate"]}},{name:"larkattendance_query_records",description:"The raw clock-in/out results (\u6253\u5361\u7ED3\u679C) per person per day \u2014 use when the aggregated statistics are not enough (e.g. to show which days were late, or the actual punch times). REQUIRES an explicit userIds list (max 50); range capped at 31 days. Returns { ok, results:[{ userId, name, day, groupId, shiftId, records:[{ checkInTime, checkInResult, checkOutTime, checkOutResult, checkInShiftTime, checkOutShiftTime }] }], invalidUserIds, unauthorizedUserIds }. Unknown ids are reported in invalidUserIds rather than failing the batch. Result values are Lark's own enums (Normal / Early / Late / Lack / \u2026).",input_schema:{type:"object",properties:{userIds:{type:"array",items:{type:"string"},description:"The people to read, in the employeeType id form. Max 50. Required."},startDate:{type:"string",description:"First day as yyyyMMdd (20260401) or YYYY-MM-DD."},endDate:{type:"string",description:"Last day, same format. At most 31 days after startDate."},employeeType:{type:"string",description:"'employee_id' (default) or 'employee_no' \u2014 must match the form of userIds."},needOvertimeResult:{type:"boolean",description:"Also return overtime shift records (default false)."},includeTerminatedUser:{type:"boolean",description:"Include departed employees (default false)."}},required:["userIds","startDate","endDate"]}},{name:"larkattendance_resolve_users",description:"Map work EMAIL addresses to the attendance user ids (tenant user_id = the attendance API's employee_id). Use this to line a report's people up with attendance rows. NOTE this is deliberately different from the `lark` skill's lark_lookup_user_by_email, which returns an open_id for chat/DM \u2014 the attendance endpoints reject open_ids. Max 50 emails per call. Returns { ok, employeeType:\"employee_id\", users:[{ email, userId }], notFound:[email] }. Needs the contact:user.id:readonly permission.",input_schema:{type:"object",properties:{emails:{type:"array",items:{type:"string"},description:"Work email addresses to resolve. Max 50."}},required:["emails"]}}]};var Ks={id:"chat_notify",description:"Chat notification meta-skill \u2014 routes to whichever messaging integration (Slack OR Lark) the user has configured for this project.",envKeys:[...P.envKeys||[],...F.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return P.serverName;if(process.env.LARK_RECEIVE_ID)return F.serverName;if(process.env.SLACK_BOT_TOKEN)return P.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?P.allowedTools||[]:process.env.LARK_RECEIVE_ID?F.allowedTools||[]:process.env.SLACK_BOT_TOKEN?P.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
|
|
425
|
+
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=xp();if(!r)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[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 s=(await de(`${Ue}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!s)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let i=hi(e);if(i&&i.trim()){let{requests:o}=mi(i,1);o.length&&await de(`${Ue}/documents/${s}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:s,title:t,url:St(s)})}case"gdocs_append":{let t=on(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=hi(e);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let i=(await de(`${Ue}/documents/${t}`))?.body,o=Array.isArray(i?.content)?i.content:[],a=o.length&&o[o.length-1].endIndex||2,c=Math.max(1,a-1),l=[],d=c;c>1&&(l.push({insertText:{location:{index:c},text:`
|
|
426
|
+
`}}),d=c+1);let p=mi(n,d);return l.push(...p.requests),await de(`${Ue}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:l}}),JSON.stringify({ok:!0,documentId:t,url:St(t)})}case"gdocs_insert_image":{let t=on(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:s,mimeType:i}=qp(e.imagePath),{rawBody:o,contentType:a}=Gp({name:s,mimeType:i},n,i),l=(await de(`${Lp}/files?uploadType=multipart&fields=id`,{method:"POST",rawBody:o,contentType:a}))?.id;if(!l)return JSON.stringify({ok:!1,error:"Drive upload returned no file id"});await de(`${ui}/files/${l}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let d=await de(`${Ue}/documents/${t}`),p=Array.isArray(d?.body?.content)?d.body.content:[],u=p.length&&p[p.length-1].endIndex||2,h={location:{index:Math.max(1,u-1)},uri:`https://drive.google.com/uc?export=download&id=${l}`},y=Number(e?.width),_=Number(e?.height);return(Number.isFinite(y)&&y>0||Number.isFinite(_)&&_>0)&&(h.objectSize={...Number.isFinite(y)&&y>0?{width:{magnitude:y,unit:"PT"}}:{},...Number.isFinite(_)&&_>0?{height:{magnitude:_,unit:"PT"}}:{}}),await de(`${Ue}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:h}]}}),JSON.stringify({ok:!0,documentId:t,fileId:l,url:St(t)})}case"gdocs_get":{let t=on(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 de(`${Ue}/documents/${t}`),s=Jp(n?.body);return JSON.stringify({ok:!0,documentId:t,title:n?.title||"",url:St(t),text:s,...s.length>=an?{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(Bp),orderBy:"modifiedTime desc"}),n=await de(`${ui}/files?${t.toString()}`),s=(Array.isArray(n?.files)?n.files:[]).map(i=>({documentId:i.id,title:i.name,modifiedTime:i.modifiedTime,url:i.webViewLink||St(i.id)}));return JSON.stringify({ok:!0,count:s.length,files:s})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). The drive.file scope grants access ONLY to docs this app created or the user explicitly picked; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker (drive.file cannot see un-picked files). Returns { ok, documentId, title, url, text }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."}},required:["documentId"]}},{name:"gdocs_list_created",description:"List the Google Docs visible to this integration, newest first (max 25). NOTE: under the drive.file scope this lists ONLY docs the app created or the user explicitly picked \u2014 it is NOT a full Drive search. Returns { ok, count, files:[{ documentId, title, modifiedTime, url }] }.",input_schema:{type:"object",properties:{}}}]};import{existsSync as Si,statSync as Hp,readFileSync as zp}from"fs";import{fileURLToPath as Yp}from"url";import{basename as Wp,dirname as Zp,resolve as Vp}from"path";import{resolveIntegrationToken as gi}from"@zibby/core/backend-client.js";var Kp="https://open.larksuite.com",bi=Object.freeze([Object.freeze({appId:"LARK_DOCS_APP_ID",appSecret:"LARK_DOCS_APP_SECRET",host:"LARK_DOCS_HOST"}),Object.freeze({appId:"LARK_APP_ID",appSecret:"LARK_APP_SECRET",host:"LARK_HOST"})]),dr=Object.freeze(bi.flatMap(r=>[r.appId,r.appSecret,r.host]));function cn(r){let e=String(r||"").trim().replace(/\/+$/,"");return e?/^https?:\/\//i.test(e)?e:`https://${e}`:Kp}function Fp(r){let e=String(process.env[r.appId]||"").trim(),t=String(process.env[r.appSecret]||"").trim();return!e||!t?null:{appId:e,appSecret:t,host:cn(process.env[r.host])}}async function pr(){for(let r of bi){let e=Fp(r);if(e)return e}try{let r=await gi(I.LARK_DOCS);return{appId:r?.appId,appSecret:r?.appSecret,host:cn(r?.host)}}catch(r){if(!/unknown provider/i.test(String(r?.message||"")))throw r;let e=await gi(I.LARK);return{appId:e?.appId,appSecret:e?.appSecret,host:cn(e?.host)}}}function Xp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Zp(Yp(import.meta.url)),e=Vp(r,"..","bin","mcp-skill.mjs");return Si(e)?e:null}var _i=2e4,ki=50,Qp=50,eu=20,tu=10*1024*1024,ru=6e3*1e3,vt=null,nu=dr;async function vi(){let{appId:r,appSecret:e,host:t}=await pr();if(vt&&vt.appId===r&&vt.expiresAt>Date.now())return{token:vt.token,host:t};let s=await(await w(`${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})},{kind:"api",what:"Lark tenant_access_token"})).json();if(s.code!==0)throw new Error(`Lark tenant_access_token failed: ${s.msg||s.code}`);return vt={token:s.tenant_access_token,expiresAt:Date.now()+ru,appId:r},{token:s.tenant_access_token,host:t}}async function Z(r,e,t){let{token:n,host:s}=await vi(),i={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(i.body=JSON.stringify(t));let a=await(await w(`${s}${e}`,i,{kind:"api",what:`Lark Docx ${r} ${e}`})).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:s}}function It(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function su(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/wiki/${e}`:`https://www.larksuite.com/wiki/${e}`}function Be(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 rt(r){let e=typeof r=="string"?Be(r):r;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:t}=await Z("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),n=t?.node||{};if(n.obj_type!=="docx"||!n.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${n.obj_type||"unknown"})`);return n.obj_token}function ln(r){let e=String(r??"").replace(/\r\n/g,`
|
|
427
|
+
`),t=[];for(let n of e.split(`
|
|
428
|
+
`)){let s=n.replace(/\s+$/,"");if(!s.trim())continue;let i=/^(#{1,3})\s+(.*)$/.exec(s),o=/^\s*[-*]\s+(.*)$/.exec(s),a=/^\s*\d+[.)]\s+(.*)$/.exec(s),c,l,d;if(i){let p=i[1].length;c=`heading${p}`,l=2+p,d=i[2]}else o?(c="bullet",l=12,d=o[1]):a?(c="ordered",l=13,d=a[1]):(c="text",l=2,d=s);t.push({block_type:l,[c]:{elements:[{text_run:{content:d}}],style:{}}})}return t}function Tt(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function dn(r,e){let t;for(let n=0;n<e.length;n+=ki){let s=e.slice(n,n+ki);t=(await Z("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:s})).host}return t}function iu(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Si(e)||!Hp(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=zp(e);if(t.length>tu)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function ou({fileName:r,parentNode:e,bytes:t}){let{token:n,host:s}=await vi(),i=new FormData;i.set("file_name",r),i.set("parent_type","docx_image"),i.set("parent_node",e),i.set("size",String(t.length)),i.set("file",new Blob([t]),r);let a=await(await w(`${s}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${n}`},body:i},{kind:"transfer",what:"Lark Docx image upload"})).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 au="docx",cu=50;function wi(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function lu(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function du(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:lu(t?.content?.elements),createTime:t?.create_time||""}))}}function pn(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():au}var Ii={id:"lark-docs",callsBackend:!0,serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:[I.LARK_DOCS,I.LARK],description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV",...nu],promptFragment:'## Lark Docs\nYou can read, create, and append Lark/Feishu documents (docx), and read/post/reply to their comments. This runs on the connected Lark Docs app (the chat app is used when no separate docs app is connected). Each `larkdoc_*` / `larkwiki_*` tool documents its own params and return shape in its tool description \u2014 they are not restated here.\nThese tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.',resolve(){let r=Xp();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,n=Be(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=await rt(n),i="";try{i=(await Z("GET",`/open-apis/docx/v1/documents/${s}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await Z("GET",`/open-apis/docx/v1/documents/${s}/raw_content?lang=0`),c=String(o?.content||""),l=!1;return c.length>_i&&(c=c.slice(0,_i),l=!0),JSON.stringify({ok:!0,documentId:s,title:i,url:It(a,s),text:c,...l?{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 n=typeof e?.wikiSpaceId=="string"&&e.wikiSpaceId.trim()?e.wikiSpaceId.trim():null;if(n){let c=typeof e?.parentNodeToken=="string"&&e.parentNodeToken.trim()?e.parentNodeToken.trim():null,{data:l,host:d}=await Z("POST",`/open-apis/wiki/v2/spaces/${encodeURIComponent(n)}/nodes`,{obj_type:"docx",node_type:"origin",title:t,...c?{parent_node_token:c}:{}}),p=l?.node||{},u=p.obj_token;if(!u)return JSON.stringify({ok:!1,error:"Lark wiki node create returned no obj_token"});let m=Tt(e);if(m&&m.trim()){let h=ln(m);h.length&&await dn(u,h)}return JSON.stringify({ok:!0,documentId:u,title:t,wikiSpaceId:n,wikiNodeToken:p.node_token||"",url:p.node_token?su(d,p.node_token):It(d,u)})}let{data:s,host:i}=await Z("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),o=s?.document?.document_id;if(!o)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let a=Tt(e);if(a&&a.trim()){let c=ln(a);c.length&&await dn(o,c)}return JSON.stringify({ok:!0,documentId:o,title:t,url:It(i,o)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,n=Be(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=Tt(e);if(!s||!s.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let i=await rt(n),o=ln(s);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await dn(i,o);return JSON.stringify({ok:!0,documentId:i,url:It(a,i)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,n=Be(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 s=await rt(n),i=e.imagePath.trim(),o=iu(i),a=Wp(i),l=(await Z("POST",`/open-apis/docx/v1/documents/${s}/blocks/${s}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!l)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let d=await ou({fileName:a,parentNode:l,bytes:o}),p={token:d},u=Number(e?.width),m=Number(e?.height);Number.isFinite(u)&&u>0&&(p.width=Math.round(u)),Number.isFinite(m)&&m>0&&(p.height=Math.round(m));let{host:h}=await Z("PATCH",`/open-apis/docx/v1/documents/${s}/blocks/${l}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:s,blockId:l,fileToken:d,url:It(h,s)})}case"larkwiki_list_spaces":{let t=[],n=null;for(let s=0;s<eu;s++){let i=new URLSearchParams({page_size:String(Qp)});n&&i.set("page_token",n);let{data:o}=await Z("GET",`/open-apis/wiki/v2/spaces?${i.toString()}`),a=Array.isArray(o?.items)?o.items:[];for(let c of a)t.push({spaceId:String(c?.space_id||""),name:String(c?.name||"")});if(!o?.has_more||!o?.page_token)break;n=o.page_token}return JSON.stringify({ok:!0,count:t.length,spaces:t})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=Be(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=await rt(n),i=pn(e),o=new URLSearchParams({file_type:i,page_size:String(cu)}),{data:a}=await Z("GET",`/open-apis/drive/v1/files/${s}/comments?${o.toString()}`),l=(Array.isArray(a?.items)?a.items:[]).map(du);return JSON.stringify({ok:!0,documentId:s,count:l.length,comments:l})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=Be(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=Tt({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let i=await rt(n),o=pn(e),{data:a}=await Z("POST",`/open-apis/drive/v1/files/${i}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:wi(s)}}]}});return JSON.stringify({ok:!0,documentId:i,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=Be(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let s=e?.commentId||e?.comment_id;if(!s)return JSON.stringify({ok:!1,error:"commentId is required"});let i=Tt({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await rt(n),a=pn(e),{data:c}=await Z("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(s)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:wi(i)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(s),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). Pass wikiSpaceId (from larkwiki_list_spaces) to create the doc INSIDE a wiki space instead of as a standalone doc \u2014 optionally nested under parentNodeToken. Returns { ok, documentId, url } (plus wikiNodeToken when created in a wiki) \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root. Ignored when wikiSpaceId is set."},wikiSpaceId:{type:"string",description:"Optional wiki space id (from larkwiki_list_spaces) \u2014 create the doc as a node inside this wiki space."},parentNodeToken:{type:"string",description:"Optional wiki node token to nest the new doc under (only with wikiSpaceId). Absent = the space root."}},required:["title"]}},{name:"larkwiki_list_spaces",description:"List the Lark/Feishu wiki spaces visible to the connected app. Returns { ok, count, spaces:[{ spaceId, name }] }. Use to discover the wikiSpaceId for larkdoc_create.",input_schema:{type:"object",properties:{}}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};import{existsSync as pu}from"fs";import{fileURLToPath as uu}from"url";import{dirname as mu,resolve as hu}from"path";function fu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=mu(uu(import.meta.url)),e=hu(r,"..","bin","mcp-skill.mjs");return pu(e)?e:null}var yu=6e3*1e3,Nt=null,gu=50,bu=50,_u=40,ku=31,wu=200,Su=31,vu=50,Ti=50,Ni=Object.freeze(["daily","month"]),Oi=Object.freeze(["zh","en","ja"]),Iu=Object.freeze(["employee_id","employee_no"]),Tu=dr;async function Nu(){let{appId:r,appSecret:e,host:t}=await pr();if(Nt&&Nt.appId===r&&Nt.expiresAt>Date.now())return{token:Nt.token,host:t};let s=await(await w(`${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})},{kind:"api",what:"Lark tenant_access_token"})).json();if(s.code!==0)throw new Error(`Lark tenant_access_token failed: ${s.msg||s.code}`);return Nt={token:s.tenant_access_token,expiresAt:Date.now()+yu,appId:r},{token:s.tenant_access_token,host:t}}function Ou(r,e,t){let n=`Lark attendance API ${r} error ${e}: ${t||"(no message)"}`,s=r.includes("/attendance/v1/groups")?"attendance:rule:readonly (\u6253\u5361\u89C4\u5219/\u8003\u52E4\u7EC4 \u8BFB\u53D6)":r.includes("/contact/v3/users")?"contact:user.id:readonly (\u90AE\u7BB1 \u2192 \u7528\u6237 ID)":"attendance:task:readonly (\u6253\u5361\u7ED3\u679C/\u7EDF\u8BA1\u6570\u636E \u8BFB\u53D6)";return String(e)==="99991672"||/permission|scope|权限/i.test(String(t||""))?`${n}. The connected Lark app is missing the ${s} permission \u2014 add it in the Lark/Feishu developer console (\u5F00\u53D1\u8005\u540E\u53F0 > \u6743\u9650\u7BA1\u7406), then RE-PUBLISH a new app version so the scope takes effect.`:String(e)==="1220002"?`${n}. The tenant token was rejected \u2014 the Lark integration's app credentials look wrong; reconnect Lark in Integrations.`:String(e)==="1220001"?`${n}. Lark rejected the parameters \u2014 check the date range (yyyyMMdd, and within the documented span), stats_type, and that every user id matches the employeeType you passed.`:n}async function nt(r,e,t){let{token:n,host:s}=await Nu(),i={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(i.body=JSON.stringify(t));let a=await(await w(`${s}${e}`,i,{kind:"api",what:`Lark Attendance ${r} ${e}`})).json();if(a.code!==0)throw new Error(Ou(e,a.code,a.msg));return a.data||{}}function Ai(r){if(r==null||r==="")return null;let e=String(r).trim().replace(/[-/.]/g,"");if(!/^\d{8}$/.test(e))return null;let t=Number(e.slice(0,4)),n=Number(e.slice(4,6)),s=Number(e.slice(6,8));if(t<1970||t>9999||n<1||n>12||s<1||s>31)return null;let i=new Date(Date.UTC(t,n-1,s));return i.getUTCFullYear()!==t||i.getUTCMonth()!==n-1||i.getUTCDate()!==s?null:Number(e)}function Au(r,e){let t=n=>Date.UTC(Math.floor(n/1e4),Math.floor(n%1e4/100)-1,n%100);return Math.floor((t(e)-t(r))/864e5)+1}function un(r,e){let t=Ai(r?.startDate??r?.start_date),n=Ai(r?.endDate??r?.end_date);if(!t||!n)return{error:"startDate and endDate are required, as yyyyMMdd (e.g. 20260401) or YYYY-MM-DD"};if(n<t)return{error:"endDate must not be earlier than startDate"};let s=Au(t,n);return s>e?{error:`Lark caps this query at ${e} days; the requested range is ${s} days. Split it into consecutive windows and merge the results.`}:{startDate:t,endDate:n}}function Ri(r,e){let t=r?.userIds??r?.user_ids,n=(Array.isArray(t)?t:typeof t=="string"?[t]:[]).map(s=>String(s||"").trim()).filter(Boolean);return n.length?n.length>e?{error:`Lark accepts at most ${e} user ids per call; ${n.length} were passed. Split into batches.`}:{ids:n}:{error:"userIds is required \u2014 attendance data is personal, so this tool never returns a whole tenant. Get the ids from larkattendance_get_group (bind_user_ids) or larkattendance_resolve_users."}}function Ot(r,e,t){let n=String(r||"").trim().toLowerCase();return e.includes(n)?n:t}function ur(r){return Ot(r?.employeeType??r?.employee_type,Iu,"employee_id")}function Ru(r){return{code:String(r?.code||""),title:String(r?.title||""),fields:(Array.isArray(r?.child_fields)?r.child_fields:[]).map(e=>({code:String(e?.code||""),title:String(e?.title||""),...e?.time_unit?{timeUnit:String(e.time_unit)}:{}}))}}function Eu(r,e){let n=(Array.isArray(r?.datas)?r.datas:[]).filter(s=>!e||e.has(String(s?.code||""))||e.has(String(s?.title||""))).map(s=>({code:String(s?.code||""),title:String(s?.title||""),value:s?.value===void 0||s?.value===null?"":String(s.value),...s?.duration_num?{durationNum:s.duration_num}:{},...Array.isArray(s?.features)&&s.features.length?{features:s.features}:{}}));return{userId:String(r?.user_id||""),name:String(r?.name||""),fields:n}}function xu(r){return{userId:String(r?.user_id||""),name:String(r?.employee_name||""),day:r?.day??null,groupId:String(r?.group_id||""),shiftId:String(r?.shift_id||""),records:(Array.isArray(r?.records)?r.records:[]).map(e=>({checkInTime:e?.check_in_record?.check_time??null,checkInResult:String(e?.check_in_result||""),checkInResultSupplement:String(e?.check_in_result_supplement||""),checkInShiftTime:e?.check_in_shift_time??null,checkOutTime:e?.check_out_record?.check_time??null,checkOutResult:String(e?.check_out_result||""),checkOutResultSupplement:String(e?.check_out_result_supplement||""),checkOutShiftTime:e?.check_out_shift_time??null,...e?.task_shift_type===void 0?{}:{taskShiftType:e.task_shift_type}}))}}var Ei={id:"lark-attendance",callsBackend:!0,serverName:"larkattendance",allowedTools:["mcp__larkattendance__*"],requiresIntegration:[I.LARK_DOCS,I.LARK],description:"Lark / Feishu attendance (\u8003\u52E4) \u2014 discover attendance groups and statistic fields, then read per-user work-hour / attendance statistics and clock-in records. Read-only.",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV",...Tu],promptFragment:"## Lark Attendance (\u8003\u52E4)\nRead-only access to this tenant's Lark/Feishu attendance data. NOTHING about the tenant's setup is known in advance \u2014 group names, what counts as \"\u5DE5\u65F6\", and the per-tenant \u81EA\u5B9A\u4E49\u5B57\u6BB5 all differ \u2014 so DISCOVER before you fetch:\n1. `larkattendance_list_groups` \u2192 the \u8003\u52E4\u7EC4 that exist.\n2. `larkattendance_get_group` \u2192 that group's member user ids (the scope for every data call).\n3. `larkattendance_list_stats_fields` \u2192 every statistic column available for the period, INCLUDING this tenant's \u81EA\u5B9A\u4E49\u5B57\u6BB5. Match the user's words (\"\u5DE5\u65F6\", \"\u51FA\u52E4\u5929\u6570\", \u2026) against the returned `title`s and pass the matching `code`s onward.\n4. `larkattendance_query_stats` (aggregated numbers) and/or `larkattendance_query_records` (raw clock-in/out).\n`larkattendance_query_stats` also needs an `operatorUserId` \u2014 the attendance admin the query runs AS. Lark rejects the call without one, and it selects the saved statistics view that decides which columns come back, so this skill refuses to invent it: if the prompt did not supply one, ASK for it rather than substituting a member id.\nIdentity mapping: attendance ids are the tenant `user_id` (employee_id), NOT the `open_id` the `lark` skill's `lark_lookup_user_by_email` returns \u2014 use `larkattendance_resolve_users` to turn emails into attendance ids. For chat/DM routing keep using the `lark` skill's tools.\nAttendance is personal HR data: every data tool requires an explicit `userIds` list, and there is no whole-tenant dump. Report the numbers as returned; do not invent a column the tenant does not have.\nThese tools return { ok:false, error } on failure \u2014 read the error, it names the missing permission or the range limit.",resolve(){let r=fu();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/larkAttendance.js","larkAttendanceSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"larkattendance_list_groups":{let t=Number(e?.pageSize??e?.page_size),n=Number.isFinite(t)&&t>0?Math.min(Math.floor(t),gu):bu,s=new URLSearchParams({page_size:String(n)}),i=String(e?.pageToken??e?.page_token??"").trim();i&&s.set("page_token",i);let o=await nt("GET",`/open-apis/attendance/v1/groups?${s.toString()}`),a=(Array.isArray(o?.group_list)?o.group_list:[]).map(c=>({groupId:String(c?.group_id||""),groupName:String(c?.group_name||"")}));return JSON.stringify({ok:!0,count:a.length,groups:a,hasMore:!!o?.has_more,...o?.has_more&&o?.page_token?{pageToken:String(o.page_token)}:{}})}case"larkattendance_get_group":{let t=String(e?.groupId??e?.group_id??"").trim();if(!t)return JSON.stringify({ok:!1,error:"groupId is required (from larkattendance_list_groups)"});let n=ur(e),s=new URLSearchParams({employee_type:n,dept_type:"open_id"}),i=await nt("GET",`/open-apis/attendance/v1/groups/${encodeURIComponent(t)}?${s.toString()}`),o=a=>Array.isArray(a)?a.map(c=>String(c)):[];return JSON.stringify({ok:!0,groupId:String(i?.group_id||t),groupName:String(i?.group_name||""),employeeType:n,memberUserIds:o(i?.bind_user_ids),memberDeptIds:o(i?.bind_dept_ids),excludedUserIds:o(i?.except_user_ids),excludedDeptIds:o(i?.except_dept_ids),noPunchUserIds:o(i?.bind_default_user_ids),noPunchDeptIds:o(i?.bind_default_dept_ids),...Array.isArray(i?.group_leader_ids)?{leaderUserIds:o(i.group_leader_ids)}:{}})}case"larkattendance_list_stats_fields":{let t=un(e,_u);if(t.error)return JSON.stringify({ok:!1,error:t.error});let n=Ot(e?.statsType??e?.stats_type,Ni,"month"),s=Ot(e?.locale,Oi,"zh"),i=ur(e),a=(await nt("POST",`/open-apis/attendance/v1/user_stats_fields/query?employee_type=${encodeURIComponent(i)}`,{locale:s,stats_type:n,start_date:t.startDate,end_date:t.endDate}))?.user_stats_field||{},c=(Array.isArray(a?.fields)?a.fields:[]).map(Ru);return JSON.stringify({ok:!0,statsType:n,locale:s,startDate:t.startDate,endDate:t.endDate,fieldGroupCount:c.length,fieldGroups:c})}case"larkattendance_query_stats":{let t=un(e,ku);if(t.error)return JSON.stringify({ok:!1,error:t.error});let n=Ri(e,wu);if(n.error)return JSON.stringify({ok:!1,error:n.error});let s=Ot(e?.statsType??e?.stats_type,Ni,"month"),i=Ot(e?.locale,Oi,"zh"),o=ur(e),a=String(e?.operatorUserId??e?.user_id??"").trim();if(!a)return JSON.stringify({ok:!1,error:'operatorUserId is required by Lark (the API rejects this call with 1220001 "Need user_id"). It is the OPERATOR performing the query \u2014 a third id, not one of `userIds` and not `employeeType`. It must be a user whose saved attendance statistics view contains the columns you want (normally an attendance admin), because that view decides which columns Lark returns. This skill will NOT pick one for you: substituting an arbitrary member would silently return the wrong column set instead of failing. Ask the caller/prompt for the attendance admin\'s user id, or resolve their email with larkattendance_resolve_users.'});let c={locale:i,stats_type:s,start_date:t.startDate,end_date:t.endDate,user_ids:n.ids,user_id:a,need_history:e?.needHistory===!0,current_group_only:e?.currentGroupOnly===!0},l=Array.isArray(e?.fieldCodes)?e.fieldCodes:null,d=l?l.map(h=>String(h||"").trim()).filter(Boolean):[],p=d.length?new Set(d):null,u=await nt("POST",`/open-apis/attendance/v1/user_stats_datas/query?employee_type=${encodeURIComponent(o)}`,c),m=(Array.isArray(u?.user_datas)?u.user_datas:[]).map(h=>Eu(h,p));return JSON.stringify({ok:!0,statsType:s,startDate:t.startDate,endDate:t.endDate,employeeType:o,userCount:m.length,users:m,invalidUserIds:Array.isArray(u?.invalid_user_list)?u.invalid_user_list.map(h=>String(h)):[]})}case"larkattendance_query_records":{let t=un({startDate:e?.startDate??e?.checkDateFrom??e?.check_date_from,endDate:e?.endDate??e?.checkDateTo??e?.check_date_to},Su);if(t.error)return JSON.stringify({ok:!1,error:t.error});let n=Ri(e,vu);if(n.error)return JSON.stringify({ok:!1,error:n.error});let s=ur(e),i=new URLSearchParams({employee_type:s,ignore_invalid_users:"true"});e?.includeTerminatedUser===!0&&i.set("include_terminated_user","true");let o=await nt("POST",`/open-apis/attendance/v1/user_tasks/query?${i.toString()}`,{user_ids:n.ids,check_date_from:t.startDate,check_date_to:t.endDate,need_overtime_result:e?.needOvertimeResult===!0}),a=(Array.isArray(o?.user_task_results)?o.user_task_results:[]).map(xu);return JSON.stringify({ok:!0,startDate:t.startDate,endDate:t.endDate,employeeType:s,count:a.length,results:a,invalidUserIds:Array.isArray(o?.invalid_user_ids)?o.invalid_user_ids.map(c=>String(c)):[],unauthorizedUserIds:Array.isArray(o?.unauthorized_user_ids)?o.unauthorized_user_ids.map(c=>String(c)):[]})}case"larkattendance_resolve_users":{let t=e?.emails,n=(Array.isArray(t)?t:typeof t=="string"?[t]:[]).map(c=>String(c||"").trim()).filter(Boolean);if(!n.length)return JSON.stringify({ok:!1,error:"emails is required (a non-empty array of work email addresses)"});if(n.length>Ti)return JSON.stringify({ok:!1,error:`At most ${Ti} emails per call; ${n.length} were passed. Split into batches.`});let s=await nt("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=user_id",{emails:n}),o=(Array.isArray(s?.user_list)?s.user_list:[]).filter(c=>c?.user_id).map(c=>({email:String(c?.email||""),userId:String(c.user_id)})),a=new Set(o.map(c=>c.email));return JSON.stringify({ok:!0,employeeType:"employee_id",users:o,notFound:n.filter(c=>!a.has(c))})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t?.message||String(t)})}},tools:[{name:"larkattendance_list_groups",description:"DISCOVERY (start here). List this tenant's Lark/Feishu attendance groups (\u8003\u52E4\u7EC4) \u2014 their names are tenant-specific, so never assume one. Returns { ok, count, groups:[{ groupId, groupName }], hasMore, pageToken }. When hasMore is true, call again with pageToken to continue. Needs the attendance:rule:readonly permission on the connected Lark app.",input_schema:{type:"object",properties:{pageSize:{type:"number",description:"Groups per page, 1-50 (default 50)."},pageToken:{type:"string",description:"Cursor from a previous call's pageToken \u2014 omit for the first page."}}}},{name:"larkattendance_get_group",description:"DISCOVERY. Read one attendance group and, crucially, ITS MEMBERS \u2014 memberUserIds is the scope you pass as userIds to larkattendance_query_stats / larkattendance_query_records (a real group can hold hundreds, so expect to batch). Returns { ok, groupId, groupName, employeeType, memberUserIds, memberDeptIds, excludedUserIds, excludedDeptIds, noPunchUserIds, noPunchDeptIds }. THREE different exclusion lists, do not conflate them: excludedUserIds are removed from the group; noPunchUserIds are in the group but not required to clock in (they still have statistics). Members bound by DEPARTMENT appear in memberDeptIds, not memberUserIds \u2014 resolve those people another way (e.g. larkattendance_resolve_users from emails you already have). Lark does not reliably return the group leaders here, so leaderUserIds may be absent \u2014 never source the query operator id from this tool.",input_schema:{type:"object",properties:{groupId:{type:"string",description:"Attendance group id from larkattendance_list_groups."},employeeType:{type:"string",description:"Which id form to return members in: 'employee_id' (tenant user_id, the default and what every other tool here expects) or 'employee_no' (\u5DE5\u53F7)."}},required:["groupId"]}},{name:"larkattendance_list_stats_fields",description:'DISCOVERY \u2014 call this BEFORE larkattendance_query_stats. Lists every statistic column this tenant has for the period, grouped (e.g. \u57FA\u672C\u4FE1\u606F / \u51FA\u52E4\u7EDF\u8BA1 / \u5F02\u5E38\u7EDF\u8BA1 / \u6BCF\u65E5\u7EDF\u8BA1 / \u81EA\u5B9A\u4E49\u5B57\u6BB5). The \u81EA\u5B9A\u4E49\u5B57\u6BB5 group is tenant-defined and exists nowhere else, so this is the only way to learn its codes. Match the user\'s wording ("\u5DE5\u65F6", "\u51FA\u52E4\u5929\u6570", "\u8FDF\u5230\u6B21\u6570") against the returned `title`s and pass the matching `code`s as fieldCodes to larkattendance_query_stats. Returns { ok, statsType, locale, startDate, endDate, fieldGroups:[{ code, title, fields:[{ code, title, timeUnit }] }] }. Range is capped at 40 days.',input_schema:{type:"object",properties:{startDate:{type:"string",description:"Period start as yyyyMMdd (20260401) or YYYY-MM-DD."},endDate:{type:"string",description:"Period end, same format. At most 40 days after startDate."},statsType:{type:"string",description:"'month' (default) for period totals, or 'daily' for per-day columns."},locale:{type:"string",description:"Field-title language: 'zh' (default), 'en', or 'ja'."},employeeType:{type:"string",description:"'employee_id' (default) or 'employee_no'."}},required:["startDate","endDate"]}},{name:"larkattendance_query_stats",description:'The numbers: per-user attendance statistics (work hours, attendance days, exceptions, custom fields) for a period. Needs THREE separate things: userIds (whose data you want, max 200), operatorUserId (WHO IS ASKING \u2014 required by Lark, see below), and the date range (max 31 days). Attendance is personal data and there is no whole-tenant read; get ids from larkattendance_get_group or larkattendance_resolve_users. Returns { ok, statsType, startDate, endDate, users:[{ userId, name, fields:[{ code, title, value, durationNum? }] }], invalidUserIds }. Values are STRINGS exactly as Lark returns them \u2014 report them as-is, do not re-derive. EXPECT MANY COLUMNS: a one-month query returns roughly 40+ cells per person, because Lark mixes period totals (e.g. an "actual attendance hours" column, late/early counts) with identity columns (department, employee number) AND one column PER DAY of the range \u2014 so match on `title` rather than assuming a short list, and pass fieldCodes to trim. The exact set of columns follows the SAVED STATISTICS VIEW of the operatorUserId (\u8003\u52E4 > \u7EDF\u8BA1\u8BBE\u7F6E), so if a field that larkattendance_list_stats_fields advertises is missing from the result, it is switched off in that operator\'s view and an admin must enable it \u2014 or you are querying as the wrong operator.',input_schema:{type:"object",properties:{userIds:{type:"array",items:{type:"string"},description:"The people to report on, in the employeeType id form. Max 200. Required."},startDate:{type:"string",description:"Period start as yyyyMMdd (20260401) or YYYY-MM-DD."},endDate:{type:"string",description:"Period end, same format. At most 31 days after startDate."},statsType:{type:"string",description:"'month' (default) for period totals, or 'daily' for per-day rows."},fieldCodes:{type:"array",items:{type:"string"},description:"Optional filter \u2014 only these field codes/titles are returned. Omit to get every column."},locale:{type:"string",description:"Field-title language: 'zh' (default), 'en', or 'ja'."},employeeType:{type:"string",description:"'employee_id' (default) or 'employee_no' \u2014 must match the form of userIds."},operatorUserId:{type:"string",description:'REQUIRED. The user id of the OPERATOR performing the query \u2014 a third id, distinct from `userIds` (whose data you want) and from `employeeType` (the id form). Lark rejects the call without it (1220001 "Need user_id"). It should be an attendance admin whose saved statistics view contains the columns you need, because that view decides which columns come back. This skill will not pick one for you \u2014 get it from the caller/prompt, or from an email via larkattendance_resolve_users.'},needHistory:{type:"boolean",description:"Include transferred/departed staff (default false)."},currentGroupOnly:{type:"boolean",description:"Restrict to the user's current attendance group (default false)."}},required:["userIds","operatorUserId","startDate","endDate"]}},{name:"larkattendance_query_records",description:"The raw clock-in/out results (\u6253\u5361\u7ED3\u679C) per person per day \u2014 use when the aggregated statistics are not enough (e.g. to show which days were late, or the actual punch times). REQUIRES an explicit userIds list (max 50); range capped at 31 days. Returns { ok, results:[{ userId, name, day, groupId, shiftId, records:[{ checkInTime, checkInResult, checkOutTime, checkOutResult, checkInShiftTime, checkOutShiftTime }] }], invalidUserIds, unauthorizedUserIds }. Unknown ids are reported in invalidUserIds rather than failing the batch. Result values are Lark's own enums (Normal / Early / Late / Lack / \u2026).",input_schema:{type:"object",properties:{userIds:{type:"array",items:{type:"string"},description:"The people to read, in the employeeType id form. Max 50. Required."},startDate:{type:"string",description:"First day as yyyyMMdd (20260401) or YYYY-MM-DD."},endDate:{type:"string",description:"Last day, same format. At most 31 days after startDate."},employeeType:{type:"string",description:"'employee_id' (default) or 'employee_no' \u2014 must match the form of userIds."},needOvertimeResult:{type:"boolean",description:"Also return overtime shift records (default false)."},includeTerminatedUser:{type:"boolean",description:"Include departed employees (default false)."}},required:["userIds","startDate","endDate"]}},{name:"larkattendance_resolve_users",description:"Map work EMAIL addresses to the attendance user ids (tenant user_id = the attendance API's employee_id). Use this to line a report's people up with attendance rows. NOTE this is deliberately different from the `lark` skill's lark_lookup_user_by_email, which returns an open_id for chat/DM \u2014 the attendance endpoints reject open_ids. Max 50 emails per call. Returns { ok, employeeType:\"employee_id\", users:[{ email, userId }], notFound:[email] }. Needs the contact:user.id:readonly permission.",input_schema:{type:"object",properties:{emails:{type:"array",items:{type:"string"},description:"Work email addresses to resolve. Max 50."}},required:["emails"]}}]};var xi={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:[...U.envKeys||[],...F.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return U.serverName;if(process.env.LARK_RECEIVE_ID)return F.serverName;if(process.env.SLACK_BOT_TOKEN)return U.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?U.allowedTools||[]:process.env.LARK_RECEIVE_ID?F.allowedTools||[]:process.env.SLACK_BOT_TOKEN?U.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
|
|
431
429
|
You can post chat messages via:
|
|
432
430
|
- slack_post_message (channel, text[, blocks]) \u2014 Slack. The \`channel\` is REQUIRED on every call.
|
|
433
431
|
- lark_send_message (receive_id, text) \u2014 Lark.
|
|
434
432
|
Where to post:
|
|
435
433
|
- If SLACK_CHANNEL / LARK_RECEIVE_ID is set, that is the default destination \u2014 use it.
|
|
436
434
|
- If NO destination env var is set but your instructions name a channel (e.g. "post to #bla"), post to THAT channel \u2014 pass it as the \`channel\` arg (a "#name" or "C0123" id both work).
|
|
437
|
-
- If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(r){return process.env.SLACK_CHANNEL&&typeof
|
|
435
|
+
- If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(r){return process.env.SLACK_CHANNEL&&typeof U.resolve=="function"?U.resolve(r):process.env.LARK_RECEIVE_ID&&typeof F.resolve=="function"?F.resolve(r):process.env.SLACK_BOT_TOKEN&&typeof U.resolve=="function"?U.resolve(r):null},async handleToolCall(r,e,t){return typeof r=="string"&&r.startsWith("slack_")?U.handleToolCall(r,e,t):typeof r=="string"&&r.startsWith("lark_")?F.handleToolCall(r,e,t):JSON.stringify({error:`chat_notify: unknown tool "${r}". Expected slack_* or lark_*.`})},get tools(){return[...U.tools||[],...F.tools||[]]}};import{createRequire as Lu}from"module";import{execFileSync as $u}from"child_process";import{join as Li}from"path";import{existsSync as ju}from"fs";var Pu=Lu(import.meta.url);function Cu(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return Pu.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var $i={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:r}=await import("@zibby/ui-memory");return r()}catch{return null}},promptFragment:`BEFORE executing browser actions:
|
|
438
436
|
- Review any test memory/history above. Prefer selectors proven to work.
|
|
439
437
|
- If a previous run failed, avoid the same approach.
|
|
440
438
|
- After setup/login completes, navigate directly to the target page instead of clicking through menus.
|
|
@@ -446,7 +444,7 @@ DURING execution \u2014 when a selector fails and you switch to a fallback:
|
|
|
446
444
|
AFTER completing the test, you MUST call memory_save_insight at least once:
|
|
447
445
|
- Save any useful finding: reliable selectors, timing quirks, navigation patterns, workarounds.
|
|
448
446
|
- Category: selector_tip | timing | navigation | workaround | flaky | general
|
|
449
|
-
- Be specific \u2014 future runs will read your insights.`,resolve(){let r=
|
|
447
|
+
- Be specific \u2014 future runs will read your insights.`,resolve(){let r=Cu();if(!r)return console.warn("[memory] @zibby/ui-memory not found \u2014 memory tools disabled for this run"),null;let e=Li(process.cwd(),".zibby","memory");if(!ju(Li(e,".dolt")))return console.warn("[memory] DB/dolt unavailable \u2014 memory tools disabled for this run"),null;try{let t=$u("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:e,encoding:"utf-8",timeout:5e3}),n=JSON.parse(t.trim()).rows||[];if(!n[0]||n[0].cnt===0)return console.log("[memory] Database empty \u2014 memory tools activate after first completed run"),null}catch(t){return console.warn(`[memory] DB/dolt unavailable \u2014 memory tools disabled for this run (${t.message})`),null}return{command:"node",args:[r,"--db-path",e],description:this.description}},tools:[{name:"memory_get_test_history",description:"Query recent test runs with pass/fail results and timing",input_schema:{type:"object",properties:{specPath:{type:"string",description:"Filter by spec path (substring match)"},limit:{type:"number",description:"Max results (default 10)"}}}},{name:"memory_get_selectors",description:"Query known selectors for a page with stability metrics",input_schema:{type:"object",properties:{pageUrl:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_page_model",description:"Query page structure \u2014 elements, roles, selectors",input_schema:{type:"object",properties:{url:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_navigation",description:"Query known page-to-page transitions",input_schema:{type:"object",properties:{fromUrl:{type:"string",description:"Filter by source URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_save_insight",description:"Save a useful observation for future runs (selector tips, timing, workarounds)",input_schema:{type:"object",properties:{category:{type:"string",enum:["selector_tip","timing","navigation","workaround","flaky","general"],description:"Type of insight"},content:{type:"string",description:"The insight text \u2014 be specific and actionable"},specPath:{type:"string",description:"Related spec path"},sessionId:{type:"string",description:"Current session ID"}},required:["category","content"]}}]};import{existsSync as Uu,readFileSync as Bu}from"fs";import{homedir as Du}from"os";import{join as Mu}from"path";import{spawn as Ju}from"child_process";var De={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
|
|
450
448
|
1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
|
|
451
449
|
2. Click "Connect Jira" and authorize via Atlassian OAuth
|
|
452
450
|
3. After OAuth completes, ask me to install Jira again`},github:{description:"GitHub issues, PRs, repository management",integrationProvider:"github",envKeys:[],setupInstructions:`To connect GitHub:
|
|
@@ -458,17 +456,17 @@ AFTER completing the test, you MUST call memory_save_insight at least once:
|
|
|
458
456
|
3. After OAuth completes, ask me to install Slack again`},sentry:{description:"Sentry error tracking \u2014 projects, issues, events",integrationProvider:"sentry",envKeys:[],setupInstructions:`To connect Sentry:
|
|
459
457
|
1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
|
|
460
458
|
2. Click "Connect Sentry" and authorize
|
|
461
|
-
3. After OAuth completes, ask me to install Sentry again`},runner:{description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],setupInstructions:"Ready to use. Runs zibby test workflows as background processes \u2014 each with its own browser and session."},browser:{description:"Playwright browser automation (navigate, click, fill, screenshot)",envKeys:[],setupInstructions:"Ready to use. Starts a Playwright browser for web automation."},memory:{description:"Test memory database (Dolt) \u2014 history, selectors, insights",envKeys:[],setupInstructions:"Ready to use. Requires Dolt (https://docs.dolthub.com/introduction/installation) and a memory DB via `zibby init --mem`."},"chat-memory":{description:"Persistent chat memory \u2014 remembers facts, decisions, and task history across sessions (Dolt-backed)",envKeys:[],setupInstructions:'Ready to use. Requires Dolt installed. Tables auto-create on first use. Install with: "add chat memory" or "install chat-memory".'},git:{description:"Clone and explore git repositories locally for codebase analysis",envKeys:[],setupInstructions:"Ready to use. Clone repos with git_checkout, explore with git_explore. Auto-authenticates with GitHub/GitLab tokens."}};function
|
|
462
|
-
`)}function
|
|
463
|
-
`)}function
|
|
459
|
+
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 qu(){let r=["## Available Skills"];for(let[e,t]of Object.entries(De)){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: ${mn()}`),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(`
|
|
460
|
+
`)}function Gu(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=Mu(Du(),".zibby","config.json");return Uu(r)&&JSON.parse(Bu(r,"utf-8")).sessionToken||null}catch{return null}}function Ku(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function mn(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function Fu(r){try{let e=process.platform;return Ju(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 Hu(){let r=Gu();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await w(`${Ku()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${r}`}},{kind:"api",what:"Zibby GET /integrations/status"});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 ji(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 Pi={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:De,promptFragment:qu,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,s=await Hu();if(r==="list_available_skills"){let i=Object.entries(De).map(([o,a])=>{let c=n.includes(o),l=ji(s.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:l.connected,setupInstructions:l.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:i})}if(r==="install_skill"){let{skillId:i}=e;if(!i)return JSON.stringify({ok:!1,error:"skillId is required"});if(n.includes(i)){let d=De[i],{getSkill:p}=await import("@zibby/agent-workflow"),m=(p(i)?.tools||[]).map(h=>h.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:i,description:d?.description,availableTools:m,integrationUrl:d?.integrationProvider?mn():void 0,hint:`${i} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!De[i])return JSON.stringify({ok:!1,error:`Unknown skill "${i}". Available: ${Object.keys(De).join(", ")}`});let o=De[i];if(o.integrationProvider){let d=ji(s.statuses,o.integrationProvider),p=mn();if(s.checked&&d.connected===!1){let u=Fu(p);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:p,openedBrowser:u,setupInstructions:`Please connect ${o.integrationProvider} first at ${p}. After you finish OAuth, ask me to install ${i} again.`})}}n.push(i);let{getSkill:a}=await import("@zibby/agent-workflow"),l=(a(i)?.tools||[]).map(d=>d.name);return JSON.stringify({ok:!0,installed:i,description:o.description,availableTools:l,hint:`${i} is now active. You now have these tools: ${l.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:i}=e;if(!i)return JSON.stringify({ok:!1,error:"skillId is required"});if(i==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=n.indexOf(i);return o===-1?JSON.stringify({ok:!1,error:`${i} is not installed`}):(n.splice(o,1),JSON.stringify({ok:!0,uninstalled:i}))}return JSON.stringify({error:`Unknown tool: ${r}`})},resolve(){return null}};import{readFileSync as zu,readdirSync as Yu,statSync as Ui,writeFileSync as Wu,mkdirSync as Zu}from"fs";import{join as Bi,resolve as Vu,relative as Xu}from"path";import{execSync as Di}from"child_process";var Ci=256*1024,Qu=64*1024,Mi={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 em(e,n);case"write_file":return tm(e,n);case"list_directory":return rm(e,n);case"run_command":return nm(e,n);case"open_url":return sm(e);case"wait":return await im(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(s){return JSON.stringify({error:s.message})}},resolve(){return null}};function mr(r,e){return Vu(e,r)}function em(r,e){let t=mr(r.path,e),n=Ui(t);return n.size>Ci?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${Ci/1024}KB`}):zu(t,"utf-8")}function tm(r,e){let t=mr(r.path,e),n=Bi(t,"..");return Zu(n,{recursive:!0}),Wu(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:Xu(e,t)})}function rm(r,e){let t=mr(r.path||".",e);return Yu(t).map(s=>{try{return Ui(Bi(t,s)).isDirectory()?`${s}/`:s}catch{return s}}).join(`
|
|
461
|
+
`)}function nm(r,e){let t=r.cwd?mr(r.cwd,e):e;return Di(r.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:Qu,stdio:["pipe","pipe","pipe"]})||"(no output)"}function sm(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 Di(`${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 im(r,e){let t=Math.min(Math.max(r.seconds||5,1),300),n=r.reason||"async operation",s=500,i=Date.now()+t*1e3;for(;Date.now()<i;){if(e?.aborted)return JSON.stringify({ok:!0,waited:Math.round((t*1e3-(i-Date.now()))/1e3),reason:n,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(s,i-Date.now())))}return JSON.stringify({ok:!0,waited:t,reason:n})}import{existsSync as om}from"fs";import{fileURLToPath as am}from"url";import{dirname as cm,resolve as lm}from"path";import{resolveIntegrationToken as At}from"@zibby/core/backend-client.js";function dm(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=cm(am(import.meta.url)),e=lm(r,"..","bin","mcp-sentry.mjs");return om(e)?e:null}function Rt(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Ji(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 qi(r,e={}){let{token:t,organizationSlug:n,baseUrl:s}=await At("sentry"),i=`${Rt(s)}/api/0/organizations/${Ji(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 w(i,o,{kind:"api",what:`Sentry ${e.method||"GET"} ${r}`});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 pm(){return qi("/projects/?per_page=50")}async function um({query:r="is:unresolved",sort:e="date",project:t,limit:n=25}={}){let s=`/issues/?query=${encodeURIComponent(r)}&sort=${e}&per_page=${n}`;return t&&(s+=`&project=${encodeURIComponent(t)}`),qi(s)}async function hn(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:s}=await At("sentry"),i=await w(`${Rt(s)}/api/0/organizations/${Ji(n)}/shortids/${encodeURIComponent(e)}/`,{headers:{Authorization:`Bearer ${t}`}},{kind:"api",what:"Sentry GET shortids"});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`Sentry API ${i.status} resolving shortId "${e}": ${c.slice(0,200)}`)}let o=await i.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${e}" did not resolve to a numeric issue id`);return String(a)}async function mm(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let e=await hn(r),{token:t,baseUrl:n}=await At("sentry"),s=await w(`${Rt(n)}/api/0/issues/${e}/`,{headers:{Authorization:`Bearer ${t}`}},{kind:"api",what:`Sentry GET issue ${e}`});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status}: ${i.slice(0,300)}`)}return s.json()}async function hm(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 hn(r),{token:s,baseUrl:i}=await At("sentry"),o=await w(`${Rt(i)}/api/0/issues/${n}/`,{method:"PUT",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify(t)},{kind:"api",what:`Sentry PUT issue ${n}`});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 fm(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 hn(r),{token:n,baseUrl:s}=await At("sentry"),i=await w(`${Rt(s)}/api/0/issues/${t}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(e)})},{kind:"api",what:`Sentry POST issue ${t} comment`});if(!i.ok){let o=await i.text().catch(()=>"");throw i.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 ${i.status} commenting on issue ${r}: ${o.slice(0,300)}`)}return i.json()}var hr={id:"sentry",callsBackend:!0,serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:I.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry
|
|
464
462
|
You have access to the user's Sentry. Use these tools:
|
|
465
463
|
- sentry_list_projects: List projects in the organization
|
|
466
464
|
- sentry_list_issues: List errors/issues (supports Sentry search query, project filter, sort)
|
|
467
465
|
- sentry_get_issue: Get detailed info about a specific issue (requires issueId)
|
|
468
466
|
- sentry_update_issue: Change an issue's status (resolved / resolvedInNextRelease / ignored / unresolved / muted), assignment, or bookmark (requires issueId; needs write scope)
|
|
469
|
-
- sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=
|
|
470
|
-
${
|
|
471
|
-
`;try{process.stderr.write(n)}catch{}}function
|
|
467
|
+
- sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=dm();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 pm();return JSON.stringify({projects:t.map(n=>({slug:n.slug,name:n.name,platform:n.platform}))})}case"sentry_list_issues":{let t=await um({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 mm(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 hm(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 fm(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"]}}]};hr.tools=hr.toolsForAssistant;import{spawn as Xi}from"child_process";import{writeFileSync as ym,mkdirSync as Gi,existsSync as pe,readdirSync as br,readFileSync as gr,unlinkSync as gm,createWriteStream as bm,statSync as _m}from"fs";import{resolve as Me,join as te}from"path";import{resolveMaxParallelRuns as Qi}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as km}from"@zibby/core/constants/zibby-scratch.js";var gn="sessions",bn=".zibby/output",fr=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",wm=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",eo=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",H=new Map,Ae=[],Sm=0,fn=0,Ki=3e3;function to(){return`run_${++Sm}_${Date.now().toString(36)}`}function Fi(r){let e=Math.floor(r/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ro(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function q(r,e,t){if(!wm)return;let n=`
|
|
468
|
+
${e} [${r}] ${t}
|
|
469
|
+
`;try{process.stderr.write(n)}catch{}}function _n(){Ae.length=0;for(let[,r]of H)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",_n);process.on("SIGINT",()=>{_n(),process.exit(0)});process.on("SIGTERM",()=>{_n(),process.exit(0)});var no={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
|
|
472
470
|
You can run zibby test workflows directly from chat:
|
|
473
471
|
|
|
474
472
|
**CRITICAL: When user asks to test a ticket:**
|
|
@@ -605,35 +603,35 @@ Each run generates:
|
|
|
605
603
|
- events.json: All browser events
|
|
606
604
|
- raw_stream_output.txt: Agent log
|
|
607
605
|
|
|
608
|
-
Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(r,t
|
|
609
|
-
`)){let k=
|
|
610
|
-
`);continue}if(n.type==="rule"){
|
|
606
|
+
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 vm(e,n);case"run_test":return await Rm(e,n,t);case"run_status":return Em(e);case"run_cancel":return xm(e);case"run_artifacts":return jm(e,n);case"run_diagnose":return Pm(e,n);case"list_specs":return Cm(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(s){return JSON.stringify({error:s.message})}},tools:[{name:"run_generate",description:"Generate specs from codebase. CRITICAL: DO NOT USE if ticket has test steps in comments. Only use when: (1) NO steps in ticket AND (2) local codebase exists (not external URLs). For tickets with steps, use run_test with inline format.",input_schema:{type:"object",properties:{ticket:{type:"string",description:"Jira ticket key (e.g. SCRUM-123). Auto-fetches ticket details."},description:{type:"string",description:"Ticket description text (use if no Jira key available)"},input:{type:"string",description:"Path to a file containing ticket/requirements text"},repo:{type:"string",description:"Path to the codebase (default: current directory)"},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},output:{type:"string",description:"Output directory for spec files (default: test-specs)"}}}},{name:"run_test",description:"Start a test (async, returns runId). spec = file path, or inline:+steps, or a Jira-shaped issue key (e.g. PROJ-123): when Jira is connected, the runner loads that issue's description+comments into an inline spec. After starting, tell the user and let them ask for progress via run_status.",input_schema:{type:"object",properties:{spec:{type:"string",description:"Workspace file path; or inline:+steps; or Jira issue key (KEY-123) to auto-fetch from Jira when the jira skill is active."},ticketKey:{type:"string",description:"Optional label (e.g. SCRUM-123). If spec is an issue key, this defaults to that key."},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},headless:{type:"boolean",description:"Run browser headless (default false)"},workflow:{type:"string",description:"Workflow override (e.g. quick-smoke)"}},required:["spec"]}},{name:"run_status",description:'Instant progress check \u2014 returns immediately. Use this whenever user asks about test progress. ALWAYS use runId="all".',input_schema:{type:"object",properties:{runId:{type:"string",description:'Use "all" to see all runs in this session (recommended). Or a specific run ID if known.'}},required:["runId"]}},{name:"run_cancel",description:'Cancel/kill a running test. ONLY use when the USER explicitly asks to cancel or stop a run. NEVER auto-cancel \u2014 tests take 1-5 minutes and "running" is normal. Use runId="all" to cancel all active runs.',input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID to cancel, or "all" to cancel all active runs'}},required:["runId"]}},{name:"run_artifacts",description:"Read artifacts from a test run session. Can list files, read results/events/logs, or search across all sessions.",input_schema:{type:"object",properties:{runId:{type:"string",description:"Run ID from run_test. Omit to search across all sessions."},type:{type:"string",enum:["list","result","events","log","search"],description:'What to retrieve: "list" = all files in session, "result" = result.json, "events" = events.json, "log" = raw output tail, "search" = search text across sessions'},node:{type:"string",description:'Node name to read from (e.g. "execute_live", "generate_script"). Default: "execute_live"'},query:{type:"string",description:'Search text (only for type="search"). Searches across all session logs/events.'},tail:{type:"number",description:"Number of characters from end of log to return (default: 3000)"}},required:["type"]}},{name:"run_diagnose",description:"Diagnose one or all runs, especially failed ones. Uses run logs + known error patterns and returns likely root cause with suggested next action.",input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID from run_test, or "all" (default) to diagnose all known runs'},tail:{type:"number",description:"Characters of run log tail to inspect (default: 2000)"}}}},{name:"list_specs",description:"List available test spec files in the project",input_schema:{type:"object",properties:{directory:{type:"string",description:'Directory to scan (default: "test-specs")'}}}}]};function yn(){let r=0;for(let[,e]of H)e.status==="running"&&r++;return r}function Hi(){for(;Ae.length>0;){let r=Qi(Ae[0]?.context?.options?.config);if(yn()>=r)break;let{args:e,cwd:t,context:n}=Ae.shift();so(e,t,n)}}async function vm(r,e){let{ticket:t,description:n,input:s,repo:i,agent:o,output:a}=r,c=["generate"];t&&c.push("--ticket",t),n&&c.push("--description",n),s&&c.push("--input",s),i&&c.push("--repo",i),a&&c.push("--output",a);let l=["assistant","cursor","claude","codex","gemini"],d=o||process.env.AGENT_TYPE,p=d&&l.includes(d)?d:null;p&&c.push("--agent",p);let u=t||"generate";return q(u,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{eo&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(f=>/\s/.test(f)?JSON.stringify(f):f).join(" ")} cwd=${e}`);let h=Xi("zibby",c,{cwd:e,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),y="",_="";h.stdout.on("data",f=>{let b=f.toString();y+=b;for(let g of b.split(`
|
|
607
|
+
`)){let k=ro(g).trim();k.startsWith("\u2705")?q(u,"\u2705",k.slice(2).trim()):k.startsWith("\u2713")&&q(u,"\u2714",k.slice(2).trim())}}),h.stderr.on("data",f=>{_+=f.toString()}),h.on("close",f=>{if(f!==0){q(u,"\u274C",`Generation failed (exit ${f})`),m(JSON.stringify({error:`zibby generate failed with exit code ${f}`,stderr:_.slice(-1e3)}));return}let b=Me(e,a||"test-specs"),g=[];try{let k=t?t.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";g=br(b).filter(v=>v.endsWith(".txt")&&(!k||v.startsWith(k))).map(v=>te(b,v))}catch{}q(u,"\u2705",`Generated ${g.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:t||null,specFiles:g.map(k=>k.replace(`${e}/`,"")),total:g.length,message:`Generated ${g.length} specs. Now call run_test for each file.`}))}),h.on("error",f=>{q(u,"\u274C",`Spawn error: ${f.message}`),m(JSON.stringify({error:f.message}))})})}var zi=1e5,Yi=/^[A-Z][A-Z0-9]+-\d+$/,Im=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Tm(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 yr(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let n of r){if(n.type==="text"){t.push(Tm(n.text||"",n.marks));continue}if(n.type==="hardBreak"){t.push(`
|
|
608
|
+
`);continue}if(n.type==="rule"){t.push(`
|
|
611
609
|
---
|
|
612
|
-
`);continue}let s=n.content?
|
|
610
|
+
`);continue}let s=n.content?yr(n.content,e+1):"";if(n.type==="listItem")t.push(s);else if(n.type==="bulletList"){let i=(n.content||[]).map(o=>`- ${yr(o.content||[],e+1).trim()}`);t.push(`
|
|
613
611
|
${i.join(`
|
|
614
612
|
`)}
|
|
615
|
-
`)}else if(n.type==="orderedList"){let i=(n.content||[]).map((o,a)=>`${a+1}. ${
|
|
613
|
+
`)}else if(n.type==="orderedList"){let i=(n.content||[]).map((o,a)=>`${a+1}. ${yr(o.content||[],e+1).trim()}`);t.push(`
|
|
616
614
|
${i.join(`
|
|
617
615
|
`)}
|
|
618
|
-
`)}else if(n.type==="heading"){let i=n.attrs?.level||2;
|
|
616
|
+
`)}else if(n.type==="heading"){let i=n.attrs?.level||2;t.push(`
|
|
619
617
|
|
|
620
618
|
${"#".repeat(i)} ${s.trim()}
|
|
621
619
|
|
|
622
|
-
`)}else
|
|
620
|
+
`)}else Im.has(n.type)?t.push(`
|
|
623
621
|
|
|
624
622
|
${s}
|
|
625
|
-
`):
|
|
623
|
+
`):t.push(s)}return t.join("").replace(/\n{3,}/g,`
|
|
626
624
|
|
|
627
|
-
`)}function
|
|
625
|
+
`)}function Nm(r){return r==null||r===""?"":typeof r=="string"?r.trim():typeof r=="object"&&Array.isArray(r.content)?yr(r.content).trim():""}async function Om(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}),s=JSON.parse(n);if(s?.error)return null;let i=await t.handleToolCall("jira_get_comments",{issueKey:r,maxResults:50}),o=JSON.parse(i);if(o?.error)return null;let a=Nm(s.description),c=[];a&&c.push(a);let l=Array.isArray(o.comments)?o.comments:[];if(l.length>0){let p=l.map(u=>String(u.body||"").trim()).filter(Boolean).join(`
|
|
628
626
|
|
|
629
627
|
`);p&&c.push(p)}let d=c.join(`
|
|
630
628
|
|
|
631
|
-
`).trim();return d?(d.length>
|
|
629
|
+
`).trim();return d?(d.length>zi&&(d=`${d.slice(0,zi)}
|
|
632
630
|
|
|
633
|
-
...[truncated]`),{inlineSpec:`inline:${d}`,issueKey:r}):null}catch{return null}}function
|
|
634
|
-
`);
|
|
635
|
-
Spawn error: ${
|
|
636
|
-
${
|
|
631
|
+
...[truncated]`),{inlineSpec:`inline:${d}`,issueKey:r}):null}catch{return null}}function Am(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function Rm(r,e,t){let n={...r},s=String(n.spec??"").trim();if(!s)return JSON.stringify({error:"spec is required"});let i=null;if(Yi.test(s)&&!s.startsWith("inline:")){let d=await Om(s);d&&(s=d.inlineSpec,n.spec=s,String(n.ticketKey||"").trim()||(n.ticketKey=d.issueKey),i=d.issueKey)}let o=String(n.ticketKey||"").trim();if(o){for(let[d,p]of H.entries())if(p?.ticketKey===o&&!(p?.status!=="running"&&p?.status!=="queued"))return JSON.stringify({runId:d,ticketKey:o,status:p.status,reused:!0,message:`A run for ${o} is already ${p.status}. Reusing existing run instead of starting a duplicate.`})}if(!s.startsWith("inline:")){let d=Me(e,s);if(!pe(d))return Yi.test(s)?JSON.stringify({error:`Invalid run_test spec: "${s}" is an issue id, not a spec.`,reason:"Jira auto-load was attempted but did not return usable text, or Jira is not configured.",doNext:["Confirm the jira skill is active and authenticated.",'Or call tracker tools yourself, then run_test with spec: "inline:" + steps.'],validExample:{spec:"inline:1. Open https://example.com \u2026 2. Verify \u2026",ticketKey:s},invalidExample:{spec:s,ticketKey:s}}):JSON.stringify({error:`Test spec not found: ${s}`,hint:'If this should be issue steps, load the issue with your tracker tools first, then run_test with spec: "inline:" + steps. Otherwise use a real file path.'})}let a=Qi(t?.options?.config);if(yn()>=a){let d=to(),p=n.ticketKey||d,u={runId:d,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};H.set(d,u),Ae.push({args:{...n,_queuedRunId:d},cwd:e,context:t}),q(p,"\u23F3",`Queued (${yn()}/${a} running, ${Ae.length} queued)`);let m={runId:d,spec:u.spec,ticketKey:u.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return i&&(m.resolvedFromJiraIssue=i,m.message+=` (spec built from Jira ${i})`),JSON.stringify(m)}let c=Date.now()-fn;c<Ki&&fn>0&&await new Promise(d=>setTimeout(d,Ki-c)),fn=Date.now();let l=so(n,e,t);return i?Am(l,{resolvedFromJiraIssue:i,message:`Spec was loaded from Jira issue ${i} (description + comments).`}):l}function so(r,e,t){let{spec:n,ticketKey:s,agent:i,headless:o,workflow:a,_queuedRunId:c}=r,l=c||to(),d=n,p=!1;if(n.startsWith("inline:")){p=!0;let R=km(e);Gi(R,{recursive:!0}),d=te(R,`${l}.txt`),ym(d,n.slice(7).trim(),"utf-8")}let u=Me(e,".zibby","output","runs");Gi(u,{recursive:!0});let m=te(u,`${l}.log`),h=bm(m,{flags:"a"}),_=i&&["assistant","cursor","claude","codex","gemini"].includes(i)?i:null,f=["test",d];_&&f.push("--agent",_),o&&f.push("--headless"),a&&f.push("--workflow",a),eo&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${f.map(R=>/\s/.test(R)?JSON.stringify(R):R).join(" ")} cwd=${e}`);let b=Xi("zibby",f,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),g={runId:l,spec:s?`${s}: ${n}`:n,ticketKey:s||null,specPath:d,logPath:m,isInline:p,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=s||l,v="";function x(R){let A=ro(R).trim();if(!A)return;if(A.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let j=JSON.parse(A.slice(22));j.phase==="node_begin"?g.currentNode=j.node:j.phase==="node_end"&&(j.node&&!g.completedNodes.includes(j.node)&&g.completedNodes.push(j.node),g.currentNode===j.node&&(g.currentNode=null))}catch{}return}let K=A.match(/Session\s+(\S+)/);if(K&&!g.sessionId&&(g.sessionId=K[1],g.sessionPath=Me(e,bn,gn,g.sessionId)),A.startsWith("\u250C ")||A.startsWith("\u250C ")){let j=A.slice(2).trim();g.currentNode=j,fr&&q(k,"\u25B6",`${j}`)}else if(A.startsWith("\u2514 ")||A.startsWith("\u2514 ")){let j=A.slice(2).trim();j.startsWith("done")?(g.currentNode&&!g.completedNodes.includes(g.currentNode)&&g.completedNodes.push(g.currentNode),fr&&q(k,"\u2714",`${g.currentNode||"node"} done ${j.replace("done","").trim()}`),g.currentNode=null):j.startsWith("failed")&&(fr&&q(k,"\u2718",`${g.currentNode||"node"} failed ${j.replace("failed","").trim()}`),g.currentNode=null)}else A.includes("Workflow completed")&&(g.currentNode=null,fr&&q(k,"\u2714",`Workflow completed (${Fi(Date.now()-g.startTime)})`))}function V(R){let A=R.toString();g.output+=A,h.write(A),g.output.length>5e4&&(g.output=g.output.slice(-3e4)),v+=A;let K=v.split(`
|
|
632
|
+
`);v=K.pop();for(let j of K)x(j)}return b.stdout.on("data",V),b.stderr.on("data",R=>{let A=R.toString();g.error+=A,h.write(A),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(),v&&x(v),h.end();let A=Fi(Date.now()-g.startTime);if(R===0?q(k,"\u2705",`Passed (${A})`):q(k,"\u274C",`Failed (${A})`),g.isInline)try{gm(g.specPath)}catch{}Hi()}),b.on("error",R=>{g.status="error",g.error+=`
|
|
633
|
+
Spawn error: ${R.message}`,q(k,"\u274C",`Spawn error: ${R.message}`),h.end(),Hi()}),g._child=b,H.set(l,g),JSON.stringify({runId:l,spec:g.spec,ticketKey:g.ticketKey,status:"running",pid:b.pid,logFile:m})}function Wi(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 s;return n?(s=`Actively executing node "${n}"`,t.length&&(s+=` (completed: ${t.join(", ")})`)):t.length?s=`Between nodes (completed: ${t.join(", ")})`:s="Starting up (initializing workflow)",s+=`. Elapsed: ${e}s. This is normal progress \u2014 do not cancel.`,{elapsed:e,stage:"running",currentNode:n,completedNodes:t,progress:s}}function Em(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let i=[...H.entries()].map(([d,p])=>{let u=Wi(p),m={runId:d,spec:p.spec,ticketKey:p.ticketKey,status:p.status,elapsed:u.elapsed,exitCode:p.exitCode,sessionId:p.sessionId||null};return p.status==="running"?(m.currentNode=u.currentNode,m.completedNodes=u.completedNodes,m.progress=u.progress):m.outputTail=p.output.slice(-500),m}),o=i.filter(d=>d.status==="running").length,a=i.filter(d=>d.status==="passed").length,c=i.filter(d=>d.status==="failed").length,l={total:i.length,running:o,passed:a,failed:c,runs:i};return o>0&&(l._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(l)}let t=H.get(e);if(!t)return JSON.stringify({error:`Run not found: ${e}`});let n=Wi(t),s={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"?(s.currentNode=n.currentNode,s.completedNodes=n.completedNodes,s.progress=n.progress):(s.outputTail=t.output.slice(-1e3),s.errorTail=t.error.slice(-500)),t.status==="running"&&(s._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(s)}function Zi(r,e){if(e.status==="queued"){let t=Ae.findIndex(n=>n.args._queuedRunId===r);return t>=0&&Ae.splice(t,1),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}if(e.status!=="running")return{ok:!1,runId:r,error:`Run is not active (status: ${e.status})`};try{return e._child.kill("SIGTERM"),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}catch(t){return{ok:!1,runId:r,error:`Failed to cancel: ${t.message}`}}}function xm(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let n=[];for(let[s,i]of H.entries())(i.status==="running"||i.status==="queued")&&n.push(Zi(s,i));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=H.get(e);return JSON.stringify(t?Zi(e,t):{error:`Run not found: ${e}`})}function Lm(r,e){let t=H.get(r);if(t?.sessionPath&&pe(t.sessionPath))return t.sessionPath;if(t?.sessionId){let n=Me(e,bn,gn,t.sessionId);if(pe(n))return n}return null}function io(r,e=""){let t=[];if(!pe(r))return t;for(let n of br(r,{withFileTypes:!0})){let s=e?`${e}/${n.name}`:n.name;if(n.isDirectory())t.push(...io(te(r,n.name),s));else{let i=_m(te(r,n.name));t.push({path:s,size:i.size})}}return t}function Vi(r){if(!pe(r))return null;try{return JSON.parse(gr(r,"utf-8"))}catch{return null}}function oo(r,e=2e3){if(!r||!pe(r))return"";try{return gr(r,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function $m({run:r,logTail:e,errorTail:t}){let s=`${e||""}
|
|
634
|
+
${t||""}`.toLowerCase(),i={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"?{...i,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:s.includes("test spec not found")?{...i,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:s.includes("unknown command")&&s.includes("'run'")?{...i,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:s.includes("missing openai_api_key")||s.includes("didn't provide an api key")||s.includes("401")?{...i,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:s.includes("spawn error")||s.includes("enoent")?{...i,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:s.includes("security command failed")||s.includes("security process exited with code: 45")||s.includes("password not found for account")?{...i,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:i}function jm(r,e){let{runId:t,type:n,node:s="execute_live",query:i,tail:o=3e3}=r;if(n==="search"){if(!i)return JSON.stringify({error:'query is required for type="search"'});let c=Me(e,bn,gn);if(!pe(c))return JSON.stringify({matches:[],message:"No sessions found"});let l=[],d=i.toLowerCase();for(let p of br(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=te(c,p.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:h,label:y}of m){let _=te(u,h);if(pe(_))try{let f=gr(_,"utf-8");if(f.toLowerCase().includes(d)){let b=f.toLowerCase().indexOf(d),g=Math.max(0,b-100),k=Math.min(f.length,b+i.length+100);l.push({sessionId:p.name,artifact:y,snippet:f.slice(g,k)})}}catch{}}if(l.length>=20)break}return JSON.stringify({query:i,matches:l,total:l.length})}if(!t)return JSON.stringify({error:"runId is required for this type"});if(n==="log"){let c=H.get(t),l=oo(c?.logPath,o);if(l)return JSON.stringify({runId:t,source:"run-log",totalLength:l.length,tail:l})}let a=Lm(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=io(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=Vi(te(a,s,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:s,result:c}:{error:`No result.json found in ${s}`})}case"events":{let c=Vi(te(a,s,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${s}`});let l=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:s,totalEvents:l.length,events:l.slice(-50)})}case"log":{let c=te(a,s,"raw_stream_output.txt");if(!pe(c))return JSON.stringify({error:`No log found in ${s}`});let l=gr(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:s,totalLength:l.length,tail:l.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${n}. Use: list, result, events, log, search`})}}function Pm(r,e){let t=String(r?.runId||"all"),n=Number(r?.tail||2e3),s=t==="all"?[...H.keys()]:[t];if(s.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let i=s.map(c=>{let l=H.get(c);if(!l)return{runId:c,error:`Run not found: ${c}`};let d=oo(l.logPath,n),p=String(l.error||"").slice(-Math.max(200,n));return{...$m({run:l,logTail:d,errorTail:p}),ticketKey:l.ticketKey||null,spec:l.spec,logTail:d,errorTail:p}}),o=i.filter(c=>c.status==="failed"||c.status==="error"),a=i.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:i.length,failed:o.length,active:a.length,diagnoses:i})}function Cm(r,e){let t=r?.directory||"test-specs",n=Me(e,t);if(!pe(n))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let i=function(o,a){for(let c of br(o,{withFileTypes:!0})){let l=a?`${a}/${c.name}`:c.name;c.isDirectory()?i(te(o,c.name),l):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&s.push(l)}},s=[];return i(n,""),JSON.stringify({specs:s.map(o=>`${t}/${o}`),total:s.length,directory:t})}catch(s){return JSON.stringify({error:s.message})}}function ao(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 co={...Te,id:"git-write",envKeys:[...Te.envKeys||[],...Ve.envKeys||[],...Xe.envKeys||[]].filter((r,e,t)=>t.indexOf(r)===e),promptFragment:`${Te.promptFragment}
|
|
637
635
|
|
|
638
636
|
## Opening a pull request / merge request (git_open_pr)
|
|
639
637
|
After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
|
|
@@ -645,7 +643,7 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
|
|
|
645
643
|
To MERGE an open PR/MR, use the provider-agnostic tool:
|
|
646
644
|
- git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
|
|
647
645
|
{ repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
|
|
648
|
-
Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(r,t
|
|
646
|
+
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 Te.handleToolCall(r,e,t);try{let n=e||{},s=n.repoUrl||n.repo_url||n.url;if(!s)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(r==="git_merge_pr"){let d=n.number??n.iid??n.prNumber;if(d==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let p=ao(s);return p?p.provider==="github"?Ve.handleToolCall("github_merge_pr",{owner:p.owner,repo:p.repo,number:d,mergeMethod:n.mergeMethod},t):Xe.handleToolCall("gitlab_accept_mr",{project:`${p.owner}/${p.repo}`,iid:d},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${s}. git_merge_pr supports github.com and gitlab.com.`})}let i=n.head||n.source_branch||n.sourceBranch||n.branch,o=n.base||n.target_branch||n.targetBranch,{title:a,body:c}=n;if(!i||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let l=ao(s);return l?l.provider==="github"?Ve.handleToolCall("github_create_pr",{owner:l.owner,repo:l.repo,head:i,base:o,title:a,body:c},t):Xe.handleToolCall("gitlab_create_mr",{project:`${l.owner}/${l.repo}`,source_branch:i,target_branch:o,title:a,description:c},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${s}. git_open_pr supports github.com and gitlab.com.`})}catch(n){return JSON.stringify({error:n.message})}},tools:[...Te.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 ho}from"child_process";import{existsSync as Tn,mkdirSync as fo}from"fs";import{join as be,basename as Um}from"path";import{randomBytes as Bm}from"crypto";import{pathToFileURL as xt}from"url";import{createRequire as yo}from"module";var Sn=".zibby/memory",go="dolt",bo={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},vn="mem0",kn=new Map,_r=new Map,kr=!1,Dm=yo(import.meta.url),Ir=()=>Bm(8).toString("hex"),Je=()=>new Date().toISOString(),Mm=[`CREATE TABLE IF NOT EXISTS chat_memory (
|
|
649
647
|
id VARCHAR(64) PRIMARY KEY,
|
|
650
648
|
memory_key VARCHAR(160),
|
|
651
649
|
category VARCHAR(32) NOT NULL,
|
|
@@ -676,10 +674,10 @@ To MERGE an open PR/MR, use the provider-agnostic tool:
|
|
|
676
674
|
tasks_failed INT DEFAULT 0,
|
|
677
675
|
key_facts TEXT,
|
|
678
676
|
created_at VARCHAR(32) NOT NULL
|
|
679
|
-
)`],
|
|
680
|
-
`)};`;
|
|
681
|
-
${
|
|
682
|
-
`)}`}function
|
|
677
|
+
)`],lo=new Set;function z(r,e){return ho(go,e,{...bo,cwd:r})}function Re(r,e){try{let t=z(r,["sql","-q",e,"-r","json"]);return JSON.parse(t.trim()).rows||[]}catch{return[]}}function Y(r,e){z(r,["sql","-q",e])}function wr(r){if(lo.has(r))return!0;if(!Tn(be(r,".dolt"))){if(!Jm())return!1;fo(r,{recursive:!0}),z(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${Mm.join(`;
|
|
678
|
+
`)};`;Y(r,e);try{Y(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{Y(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return lo.add(r),!0}function Jm(){try{return ho(go,["version"],{...bo,timeout:5e3}),!0}catch{return!1}}function T(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function In(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function st(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function Nn(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 _o(r){let e=new Map;for(let t of r||[]){let n=In(t.content),s=t.memory_key?`key:${t.memory_key}`:n?`norm:${n}`:"";if(!s)continue;let i=e.get(s);if(!i){e.set(s,t);continue}let o=st(i.tier),a=st(t.tier);if(a>o){e.set(s,t);continue}a===o&&Number(t.relevance||0)>Number(i.relevance||0)&&e.set(s,t)}return[...e.values()]}function vr(r,e){let t=String(r??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function Et(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||vn),error:r?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function po(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(`- ${vr(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}] ${vr(t.content,120)}`)}}return e.length===0?"":`## Memory Context
|
|
679
|
+
${e.join(`
|
|
680
|
+
`)}`}function Sr(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:vr(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:vr(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function qm(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(_r.has(r))return _r.get(r);try{let s=be(r,".zibby.config.mjs");if(Tn(s)){let i=await import(xt(s).href),o=String(i?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return _r.set(r,o),o}}catch{}return _r.set(r,vn),vn}function ko(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${Um(r||process.cwd())}`}var Gm="mem0";function wo(r){let e=be(r,Sn,Gm);return{dir:e,vectorDbPath:be(e,"vectors.db"),historyDbPath:be(e,"history.db")}}function Km(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(),s=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),i=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=wo(r||process.cwd());return{llm:{provider:"openai",config:{model:n,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:s,embeddingDims:i,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:i,dbPath:o}},historyDbPath:a}}async function So(r){let e=r||process.cwd();if(kn.has(e))return kn.get(e);let t;try{let a=yo(xt(be(e,"package.json")).href).resolve("mem0ai/oss");t=await import(xt(a).href)}catch{try{let o=Dm.resolve("mem0ai/oss");t=await import(xt(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 s=Km(e);if(s)try{fo(wo(e).dir,{recursive:!0})}catch{}let i=s?new n(s):new n;return kn.set(e,i),i}function uo(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||Ir(),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:Nn(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||Je()})).filter(n=>String(n.content||"").trim().length>0)}var it={id:"dolt",store:(r,e)=>Io(r,e),recall:(r,e)=>Zm(r,e),brief:(r,e)=>Vm(r,e),endSession:(r,e)=>No(r,e),logTask:(r,e)=>Oo(r,e),taskHistory:(r,e)=>Ao(r,e)},Fm={id:"mem0",store:(r,e,t)=>Wm(r,e,t),recall:(r,e,t)=>To(r,e,t),brief:(r,e,t)=>Xm(r,e,t),endSession:(r,e)=>No(r,e),logTask:(r,e)=>Oo(r,e),taskHistory:(r,e)=>Ao(r,e)},Hm={dolt:it,mem0:Fm};async function mo(r,e){let t=await qm(r,e);return Hm[t]||it}var vo={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
|
|
683
681
|
You have persistent memory across sessions. Use it to avoid losing context:
|
|
684
682
|
- **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
|
|
685
683
|
- **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
|
|
@@ -695,40 +693,40 @@ You have persistent memory across sessions. Use it to avoid losing context:
|
|
|
695
693
|
- When the user's request is complete: call memory_end_session
|
|
696
694
|
|
|
697
695
|
### Categories for memory_store
|
|
698
|
-
fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,
|
|
699
|
-
`)}catch{}}try{let l=await
|
|
700
|
-
`)}catch{}}try{return await c(
|
|
696
|
+
fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,e={}){let t=r?.options?.workspace||process.cwd(),n=be(t,Sn),s=await mo(t,r),i=s.id;if(i==="dolt"&&!wr(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:i,brief:Et({backend:i,error:o},i),promptContext:"",debugPreview:Sr(Et({backend:i,error:o},i)),error:o}}try{let o=await s.brief(e,n,t),a=JSON.parse(o||"{}"),c=Et({...a,backend:i},i);return{backend:i,brief:c,promptContext:po(c),debugPreview:Sr(c),error:c.error||null}}catch(o){if(i==="mem0"&&s!==it&&wr(n)){if(!kr){kr=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
|
|
697
|
+
`)}catch{}}try{let l=await it.brief(e,n,t),d=JSON.parse(l||"{}"),p=Et({...d,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:po(p),debugPreview:Sr(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=Et({backend:i,error:a},i);return{backend:i,brief:c,promptContext:"",debugPreview:Sr(c),error:a}}},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd(),s=be(n,Sn),i=await mo(n,t),o=i.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!wr(s))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=l=>{switch(r){case"memory_store":return l.store(e,s,n);case"memory_recall":return l.recall(e,s,n);case"memory_brief":return l.brief(e,s,n);case"memory_end_session":return l.endSession(e,s,n);case"task_log":return l.logTask(e,s,n);case"task_history":return l.taskHistory(e,s,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(i)}catch(l){if(o==="mem0"&&i!==it){if(wr(s)){if(!kr){kr=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${l.message}); degrading to dolt for this run
|
|
698
|
+
`)}catch{}}try{return await c(it)}catch(d){return JSON.stringify({error:d.message,backend:"dolt",degradedFrom:"mem0"})}}return JSON.stringify({error:`mem0 unavailable (${l.message}); dolt fallback also unavailable`,backend:"mem0"})}return JSON.stringify({error:l.message})}},tools:[{name:"memory_store",description:"Save a fact, decision, or context to persistent memory. Survives across sessions.",input_schema:{type:"object",properties:{memoryKey:{type:"string",description:"Stable semantic identity key (e.g. user.jira.default_board)"},content:{type:"string",description:"The information to remember"},category:{type:"string",enum:["fact","decision","context","insight","preference","credential","url","error","workaround"],description:"Category of memory"},tier:{type:"string",enum:["short","mid","long"],description:"Memory tier: short (session/24h), mid (days/weeks), long (permanent)"},source:{type:"string",description:'Where this info came from (e.g. "jira", "github", "user", "test_run")'},ticketKey:{type:"string",description:"Related ticket key (optional)"},infer:{type:"boolean",description:"true = LLM distills/dedupes facts (costs tokens); false = store raw, embed-only, free",default:!1}},required:["content","category"]}},{name:"memory_recall",description:"Search persistent memory by keyword, category, ticket, or tier. Returns matching facts and context.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search text (matches content)"},category:{type:"string",description:"Filter by category"},ticketKey:{type:"string",description:"Filter by ticket key"},tier:{type:"string",enum:["short","mid","long"],description:"Filter by memory tier"},limit:{type:"number",description:"Max results (default: 20)"}}}},{name:"memory_brief",description:"Get a compact briefing: recent session summaries + top relevant facts. Call at the start of a conversation.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Focus briefing on a specific ticket (optional)"}}}},{name:"memory_end_session",description:"End the current session and save a summary for future recall. Call when a task is complete.",input_schema:{type:"object",properties:{summary:{type:"string",description:"What happened in this session (1-3 sentences)"},tickets:{type:"string",description:"Comma-separated ticket keys covered"},tasksRun:{type:"number",description:"Number of tasks/tests run"},tasksPassed:{type:"number",description:"Number passed"},tasksFailed:{type:"number",description:"Number failed"},keyFacts:{type:"string",description:"Key facts worth remembering from this session (semicolon-separated)"}},required:["summary"]}},{name:"task_log",description:"Record a completed task (test run, analysis, generation) to persistent history.",input_schema:{type:"object",properties:{title:{type:"string",description:"Task description"},type:{type:"string",enum:["test_run","generate","analysis","research","other"],description:"Task type"},status:{type:"string",enum:["passed","failed","cancelled","error"],description:"Outcome"},ticketKey:{type:"string",description:"Related ticket key"},specPath:{type:"string",description:"Spec file path (if test run)"},resultSummary:{type:"string",description:"Brief result description"}},required:["title","type","status"]}},{name:"task_history",description:"Query past tasks by ticket, status, or type. See what was done before.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Filter by ticket key"},type:{type:"string",description:"Filter by task type"},status:{type:"string",description:"Filter by status"},limit:{type:"number",description:"Max results (default: 20)"}}}}]};function Io(r,e){let{content:t,category:n,source:s,ticketKey:i,tier:o,memoryKey:a}=r;if(!t||!n)return JSON.stringify({error:"content and category are required"});let c=In(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let l=Nn(o,n),d=l==="long"?1:l==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let f=Re(e,`SELECT id, tier, relevance
|
|
701
699
|
FROM chat_memory
|
|
702
|
-
WHERE memory_key = ${
|
|
700
|
+
WHERE memory_key = ${T(p)}
|
|
703
701
|
ORDER BY created_at DESC
|
|
704
|
-
LIMIT 1`)[0];if(
|
|
705
|
-
SET content = ${
|
|
706
|
-
category = ${
|
|
707
|
-
source = ${
|
|
708
|
-
ticket_key = ${
|
|
709
|
-
tier = ${
|
|
710
|
-
relevance = ${
|
|
711
|
-
created_at = ${
|
|
712
|
-
WHERE id = ${
|
|
702
|
+
LIMIT 1`)[0];if(f){let b=String(f.tier||"mid"),g=Number(f.relevance||0),k=st(l)>st(b)?l:b,v=Math.max(d,g);Y(e,`UPDATE chat_memory
|
|
703
|
+
SET content = ${T(t)},
|
|
704
|
+
category = ${T(n)},
|
|
705
|
+
source = ${T(s)},
|
|
706
|
+
ticket_key = ${T(i)},
|
|
707
|
+
tier = ${T(k)},
|
|
708
|
+
relevance = ${v},
|
|
709
|
+
created_at = ${T(Je())}
|
|
710
|
+
WHERE id = ${T(f.id)}`);try{z(e,["add","."]),z(e,["commit","-m",`memory upsert: ${n} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f.id,category:n,tier:k,memoryKey:p,upserted:!0})}}let m=Re(e,`SELECT id, content, tier, relevance
|
|
713
711
|
FROM chat_memory
|
|
714
|
-
WHERE category = ${
|
|
712
|
+
WHERE category = ${T(n)}
|
|
715
713
|
ORDER BY created_at DESC
|
|
716
|
-
LIMIT 200`).find(
|
|
717
|
-
SET tier = ${
|
|
718
|
-
relevance = ${Math.max(d,
|
|
719
|
-
WHERE id = ${
|
|
720
|
-
VALUES (${
|
|
714
|
+
LIMIT 200`).find(_=>In(_.content)===c);if(m){let _=String(m.tier||"mid"),f=Number(m.relevance||0),b=st(l)>st(_),g=d>f;if(b||g){Y(e,`UPDATE chat_memory
|
|
715
|
+
SET tier = ${T(b?l:_)},
|
|
716
|
+
relevance = ${Math.max(d,f)}
|
|
717
|
+
WHERE id = ${T(m.id)}`);try{z(e,["add","."]),z(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?l:_,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:n,tier:_,deduped:!0,promoted:!1})}let h=Ir(),y=process.env.ZIBBY_CHAT_SESSION_ID||null;Y(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
|
|
718
|
+
VALUES (${T(h)}, ${T(p||null)}, ${T(n)}, ${T(t)}, ${T(s)}, ${T(i)}, ${T(y)}, ${T(l)}, ${d}, ${T(Je())})`);try{z(e,["add","."]),z(e,["commit","-m",`memory: ${n} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:h,category:n,tier:l,memoryKey:p||null,stored:t.slice(0,100)})}function zm(r){let e=String(r||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var wn=new Map;async function Ym(r,e){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return zm(process.env.ZIBBY_MEM0_INFER);let t=e||process.cwd();if(wn.has(t))return wn.get(t);let n=!1;try{let s=be(t,".zibby.config.mjs");Tn(s)&&(n=(await import(xt(s).href))?.default?.memory?.infer===!0)}catch{}return wn.set(t,n),n}async function Wm(r,e,t){let{content:n,category:s,source:i,ticketKey:o,tier:a,memoryKey:c,infer:l}=r;if(!n||!s)return JSON.stringify({error:"content and category are required"});try{let d=await So(t),p=ko(t),u=Nn(a,s),m=await Ym(l,t);return await d.add([{role:"user",content:String(n)}],{userId:p,infer:m,metadata:{memoryKey:c||null,category:s,tier:u,source:i||"zibby-chat",ticketKey:o||null,created_at:Je()}}),JSON.stringify({ok:!0,backend:"mem0",userId:p,category:s,tier:u,infer:m,memoryKey:c||null,stored:String(n).slice(0,100)})}catch(d){throw new Error(`mem0 store failed: ${d.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:d})}}function Zm(r,e){let{query:t,category:n,ticketKey:s,tier:i,limit:o=20}=r,a=[];t&&a.push(`content LIKE ${T(`%${t}%`)}`),n&&a.push(`category = ${T(n)}`),s&&a.push(`ticket_key = ${T(s)}`),i&&a.push(`tier = ${T(i)}`);let l=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
|
|
721
719
|
FROM chat_memory ${a.length>0?`WHERE ${a.join(" AND ")}`:""}
|
|
722
720
|
ORDER BY relevance DESC, created_at DESC
|
|
723
|
-
LIMIT ${o}`,d=
|
|
724
|
-
FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),i=
|
|
725
|
-
WHERE tier = 'long' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=
|
|
726
|
-
WHERE tier = 'mid' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 8`),l=
|
|
727
|
-
GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),d=
|
|
728
|
-
VALUES (${
|
|
729
|
-
VALUES (${
|
|
721
|
+
LIMIT ${o}`,d=Re(e,l);return JSON.stringify({total:d.length,memories:d})}async function To(r,e,t){let{query:n,category:s,ticketKey:i,tier:o,limit:a=20}=r;try{let c=await So(t),l=ko(t),d=[];if(n&&String(n).trim()){let p=await c.search(String(n),{filters:{user_id:l},topK:a});d=uo(p)}else{let p=await c.getAll({filters:{user_id:l},topK:Math.max(a,50)});d=uo(p)}return s&&(d=d.filter(p=>p.category===s)),i&&(d=d.filter(p=>p.ticket_key===i)),o&&(d=d.filter(p=>p.tier===o)),d=d.slice(0,a),JSON.stringify({total:d.length,memories:d,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function Vm(r,e){let{ticketKey:t}=r;eh(e);let s=Re(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
|
|
722
|
+
FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),i=t?`AND ticket_key = ${T(t)}`:"",o=Re(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
|
|
723
|
+
WHERE tier = 'long' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=Re(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
|
|
724
|
+
WHERE tier = 'mid' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 8`),l=Re(e,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
|
|
725
|
+
GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),d=_o([...o,...a]);return JSON.stringify({recentSessions:s,topMemories:d,taskStats:l,ticketFilter:t||null})}async function Xm(r,e,t){let{ticketKey:n}=r,s=await To({limit:80},e,t),i=JSON.parse(s||"{}"),o=Array.isArray(i.memories)?i.memories:[];n&&(o=o.filter(u=>u.ticket_key===n));let a=u=>{let m=Date.parse(String(u?.created_at||""))||0;return Number(u?.relevance||0)*1e12+m},c=(u,m)=>a(m)-a(u),l=o.filter(u=>u.tier==="long").sort(c).slice(0,10),d=o.filter(u=>u.tier==="mid").sort(c).slice(0,8),p=_o([...l,...d]);return JSON.stringify({recentSessions:[],topMemories:p,taskStats:[],ticketFilter:n||null,backend:"mem0"})}function No(r,e){let{summary:t,tickets:n,tasksRun:s=0,tasksPassed:i=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_${Ir()}`;if(Y(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
|
|
726
|
+
VALUES (${T(c)}, ${T(t)}, ${T(n)}, ${s}, ${i}, ${o}, ${T(a)}, ${T(Je())})`),a)for(let l of a.split(";").map(d=>d.trim()).filter(Boolean))Io({content:l,category:"fact",source:"session_summary",tier:"mid"},e);Qm(e);try{z(e,["add","."]),z(e,["commit","-m",`session end: ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:t.slice(0,200)})}function Oo(r,e){let{title:t,type:n,status:s,ticketKey:i,specPath:o,resultSummary:a}=r;if(!t||!n||!s)return JSON.stringify({error:"title, type, and status are required"});let c=Ir(),l=process.env.ZIBBY_CHAT_SESSION_ID||null;Y(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
|
|
727
|
+
VALUES (${T(c)}, ${T(i)}, ${T(n)}, ${T(t)}, ${T(s)}, ${T(o)}, ${T(l)}, ${T(a)}, ${T(Je())}, ${T(Je())})`);try{z(e,["add","."]),z(e,["commit","-m",`task: ${s} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:t,type:n,status:s})}function Ao(r,e){let{ticketKey:t,type:n,status:s,limit:i=20}=r,o=[];t&&o.push(`ticket_key = ${T(t)}`),n&&o.push(`type = ${T(n)}`),s&&o.push(`status = ${T(s)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
|
|
730
728
|
FROM chat_tasks ${o.length>0?`WHERE ${o.join(" AND ")}`:""}
|
|
731
|
-
ORDER BY created_at DESC LIMIT ${i}`,l=
|
|
729
|
+
ORDER BY created_at DESC LIMIT ${i}`,l=Re(e,c);return JSON.stringify({total:l.length,tasks:l})}function Qm(r){try{Y(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),Y(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),Y(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),Y(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function eh(r){try{let e=new Date(Date.now()-864e5).toISOString();Y(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${T(e)}`)}catch{}}import{existsSync as Ro,readFileSync as th}from"node:fs";import{homedir as rh}from"node:os";import{join as nh,dirname as sh,resolve as ih}from"node:path";import{fileURLToPath as oh}from"node:url";function ah(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=sh(oh(import.meta.url)),e=ih(r,"..","bin","mcp-skill.mjs");return Ro(e)?e:null}function ch(){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=nh(rh(),".zibby","config.json");return Ro(r)&&JSON.parse(th(r,"utf-8")).sessionToken||null}catch{return null}}function lh(){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 dh(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function On(r){return`${dh()}:${r}`}async function An(r,e){let t=ch();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${lh()}/credits/review-memory`,s=await w(n,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})},{kind:"api",what:`kv-memory ${r}`});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${s.status}): ${i.slice(0,300)}`)}return s.json()}var Eo={id:"kv-memory",callsBackend:!0,serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
|
|
732
730
|
You have a PRIVATE per-agent key-value memory that survives across your
|
|
733
731
|
stateless runs. It is automatically namespaced to YOU (this agent type) \u2014 other
|
|
734
732
|
agents cannot see or collide with your entries, and you don't need to prefix
|
|
@@ -743,7 +741,7 @@ Tools:
|
|
|
743
741
|
Use to record durable facts \u2014 e.g. dedup markers, prior decisions, summaries.
|
|
744
742
|
|
|
745
743
|
Your namespace is added for you automatically; pass plain keys like
|
|
746
|
-
"seen#owner/repo#42" or "lastRun".`,resolve(){let r=
|
|
744
|
+
"seen#owner/repo#42" or "lastRun".`,resolve(){let r=ah();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 An("recall",{scope:On(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 An("recall-prefix",{scopePrefix:On(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:On(t),content:e.content};e.metadata!=null&&(n.metadata=e.metadata);let s=await An("store",n);return JSON.stringify(s)}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 Lo,readFileSync as ph}from"node:fs";import{homedir as uh}from"node:os";import{join as mh,dirname as hh,resolve as fh}from"node:path";import{fileURLToPath as yh}from"node:url";function gh(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=hh(yh(import.meta.url)),e=fh(r,"..","bin","mcp-skill.mjs");return Lo(e)?e:null}function $o(){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=mh(uh(),".zibby","config.json");return Lo(r)&&JSON.parse(ph(r,"utf-8")).sessionToken||null}catch{return null}}function jo(){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 xo(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function bh(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let s=typeof t=="string"?t.trim():"";s&&(r[n[1]]=s)}return r}var Po={};function qe(r){let e={...bh(),...Po},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 _h(r){let e=$o();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await w(`${jo()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)},{kind:"api",what:"dataset store ensure"});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 _e(r,e,t){let n=$o();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let s=`${jo()}/datasets/stores/${encodeURIComponent(r)}/${e}`,i=await w(s,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)},{kind:e==="query"||e==="sql"?"job":"api",what:`dataset store ${e}`});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Store ${e} failed (${i.status}): ${o.slice(0,300)}`)}return i.json()}var kh=Math.floor(3.5*1024*1024);async function wh(r,e,t,n){let s=await _e(r,"put-url",{path:e,contentType:n});if(!s?.url)throw new Error("put-url did not return an upload URL");let i=await w(s.url,{method:s.method||"PUT",headers:s.headers||{"Content-Type":n},body:t},{kind:"transfer",what:`dataset store presigned upload of ${e}`});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`direct upload failed (${i.status}): ${o.slice(0,200)}`)}return{ok:!0,path:s.path||e,size:t.length,contentType:s.contentType||n,via:"presign"}}async function Sh(r,e){let t=await _e(r,"get-url",{path:e});if(!t?.url)throw new Error("get-url did not return a download URL");let n=await w(t.url,{method:t.method||"GET"},{kind:"transfer",what:`dataset store presigned download of ${e}`});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`direct download failed (${n.status}): ${i.slice(0,200)}`)}let s=await n.arrayBuffer();return{buf:Buffer.from(s),contentType:n.headers.get("content-type")||"application/octet-stream"}}var Co={id:"dataset-store",callsBackend:!0,serverName:"dataset_store",allowedTools:["mcp__dataset_store__*"],description:"Dataset store \u2014 a durable, queryable store for structured JSON records; append rows now, run SQL-style aggregations/reports later",promptFragment:`## Dataset Store (durable, queryable structured-record store)
|
|
747
745
|
You have one or more durable stores for STRUCTURED records that survive across
|
|
748
746
|
your stateless runs. Unlike key-value memory (for picking up where you left
|
|
749
747
|
off), this is for accumulating DATA you want to QUERY and AGGREGATE later \u2014 e.g.
|
|
@@ -790,7 +788,7 @@ Tools:
|
|
|
790
788
|
- file_list: (file stores) List stored files (optionally by path prefix).
|
|
791
789
|
- file_delete: (file stores) Delete ONE file by path.
|
|
792
790
|
Pick the tool that matches the store's TYPE; using a dataset tool on a sqlite
|
|
793
|
-
store (or a file tool on either, etc.) is rejected.`,resolve(){let r=im();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/datasetStore.js","datasetStoreSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(r,t){try{switch(r){case"dataset_append":{if(t?.record==null||typeof t.record!="object"||Array.isArray(t.record))return JSON.stringify({error:"record is required (a JSON object)"});let e=Le(t?.store);if(e.error)return JSON.stringify({error:e.error});let n=typeof t?.agent=="string"&&t.agent.trim()?t.agent.trim():Fi(),s={record:t.record,agent:n};typeof t?.description=="string"&&t.description.trim()&&(s.description=t.description.trim());let i=await me(e.storeId,"append",s);return JSON.stringify({...i,store:e.name,storeId:e.storeId})}case"dataset_query":{let e=Le(t?.store);if(e.error)return JSON.stringify({error:e.error});let n={};for(let i of["select","where","groupBy","orderBy","limit","since","until","agent"])t?.[i]!=null&&(n[i]=t[i]);let s=await me(e.storeId,"query",n);return JSON.stringify({...s,store:e.name,storeId:e.storeId})}case"ensure_store":{let e=typeof t?.name=="string"?t.name.trim():"";if(!e)return JSON.stringify({error:"name is required"});let n=typeof t?.type=="string"&&t.type.trim()?t.type.trim().toLowerCase():"sqlite",s=typeof t?.description=="string"?t.description.trim():"",i=await am({name:e,type:n,description:s,namespace:Fi()});return i?.storeId&&(Yi[e]=i.storeId),JSON.stringify({...i,store:e})}case"file_put":{let e=Le(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.path!="string"||!t.path.trim())return JSON.stringify({error:'path is required (a relative file path like "reports/2026-07.json")'});let n=typeof t?.content=="string",s=typeof t?.contentBase64=="string"&&t.contentBase64.length>0;if(!n&&!s)return JSON.stringify({error:"content (text) or contentBase64 (base64 bytes) is required"});let i=t.path.trim(),o=typeof t?.contentType=="string"&&t.contentType.trim()?t.contentType.trim():"",a=n?Buffer.from(t.content,"utf8"):Buffer.from(String(t.contentBase64).replace(/\s+/g,""),"base64");if(a.length>cm){let d=o||(n?"text/plain; charset=utf-8":"application/octet-stream"),p=await lm(e.storeId,i,a,d);return JSON.stringify({...p,store:e.name,storeId:e.storeId})}let c={path:i};n?c.content=t.content:c.contentBase64=t.contentBase64,o&&(c.contentType=o);let l=await me(e.storeId,"put",c);return JSON.stringify({...l,store:e.name,storeId:e.storeId})}case"file_get":{let e=Le(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.path!="string"||!t.path.trim())return JSON.stringify({error:"path is required"});let n=t.path.trim(),s;try{s=await me(e.storeId,"get",{path:n})}catch(c){if(!/failed \(413\)/.test(c?.message||""))throw c;let l=await dm(e.storeId,n);s={path:n,size:l.buf.length,contentType:l.contentType,lastModified:null,contentBase64:l.buf.toString("base64")}}let i={ok:!0,store:e.name,storeId:e.storeId,path:s.path,size:s.size,contentType:s.contentType,lastModified:s.lastModified},o=Buffer.from(s.contentBase64||"","base64"),a=o.toString("utf8");return Buffer.compare(Buffer.from(a,"utf8"),o)===0&&!a.includes("\0")?(i.content=a,i.encoding="utf8"):(i.contentBase64=s.contentBase64,i.encoding="base64"),JSON.stringify(i)}case"file_list":{let e=Le(t?.store);if(e.error)return JSON.stringify({error:e.error});let n={};typeof t?.prefix=="string"&&t.prefix.trim()&&(n.prefix=t.prefix.trim()),t?.limit!=null&&(n.limit=t.limit),typeof t?.cursor=="string"&&t.cursor&&(n.cursor=t.cursor);let s=await me(e.storeId,"list",n);return JSON.stringify({...s,store:e.name,storeId:e.storeId})}case"file_delete":{let e=Le(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.path!="string"||!t.path.trim())return JSON.stringify({error:"path is required"});let n=await me(e.storeId,"delete",{path:t.path.trim()});return JSON.stringify({...n,store:e.name,storeId:e.storeId})}case"sqlite_exec":case"sqlite_query":{let e=Le(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.sql!="string"||!t.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let n={sql:t.sql};r==="sqlite_query"&&(n.readOnly=!0),Array.isArray(t?.params)&&(n.params=t.params);let s=await me(e.storeId,"sql",n);return JSON.stringify({...s,store:e.name,storeId:e.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset","file"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics. "file" = arbitrary file/blob storage by relative path (file_put/file_get/file_list/file_delete).'},description:{type:"string",description:"What this store is for (shown in the Storage UI)."}},required:["name"]}},{name:"sqlite_exec",description:"For SQLITE-type stores: run SQL that CHANGES data \u2014 CREATE TABLE (use IF NOT EXISTS), INSERT, UPDATE, DELETE (one or more statements in one call). The store is a real, mutable SQLite database that persists across your stateless runs. Returns { rowsModified, wrote }. Use this to build schema on the fly and to update rows / track changing state (e.g. a queue with a status column).",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:'The SQL to run. May contain multiple statements separated by ";". Prefer CREATE TABLE IF NOT EXISTS for idempotent schema.'},params:{type:"array",description:'Optional positional bind params for a SINGLE parameterized statement (safe binding of values), e.g. sql "UPDATE t SET s=? WHERE id=?" with params ["done", 1].'}},required:["sql"]}},{name:"sqlite_query",description:"For SQLITE-type stores: run a read-only SELECT (optionally with `params` for safe binding) against the store's SQLite database. Returns { columns, rows }. Never changes data. Use to read back rows/state you stored earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:"A single SELECT statement. Use ? placeholders + `params` for any values."},params:{type:"array",description:'Optional positional bind params for the SELECT, e.g. ["linkedin_personal"].'}},required:["sql"]}},{name:"file_put",description:"For FILE-type stores: write (or overwrite) ONE file at a relative path \u2014 raw JSON dumps, CSVs, images, snapshots, any blob you want to keep across your stateless runs. Text goes in `content`; binary goes base64-encoded in `contentBase64` (pass exactly one). SIZE: there is no practical limit \u2014 anything over ~3.5 MiB is streamed straight to object storage via a presigned URL automatically, so do NOT gzip, base64-wrap, chunk or split a file just to make it fit. Non-ASCII paths (e.g. \u4E2A\u4EBA\u62A5\u544A.html) are fine \u2014 do not transliterate. Overwriting the same path UPDATES the file. Returns { ok, path, size }.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},path:{type:"string",description:'Relative file path, e.g. "dumps/run-42.json" or "img/chart.png". Letters, digits, ".", "_", "-" and "/" only; no "..", no leading "/".'},content:{type:"string",description:"Text content (UTF-8). Use for JSON/CSV/text files."},contentBase64:{type:"string",description:"Base64-encoded binary content (images etc.). Alternative to `content`."},contentType:{type:"string",description:'Optional MIME type (e.g. "application/json", "image/png"). Defaults sensibly.'}},required:["path"]}},{name:"file_get",description:'For FILE-type stores: read ONE stored file back by its relative path. Text files come back as `content` (encoding "utf8"); binary files come back as `contentBase64` (encoding "base64"). Returns { path, size, contentType, lastModified, content|contentBase64, encoding }.',input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},path:{type:"string",description:"The relative file path to fetch (as listed by file_list / used in file_put)."}},required:["path"]}},{name:"file_list",description:'For FILE-type stores: list the stored files \u2014 each entry has { path, size, lastModified }. Optionally filter by a path `prefix` (e.g. "dumps/"). Paginated via `cursor` when there are more results.',input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},prefix:{type:"string",description:'Optional path prefix filter, e.g. "dumps/" or "reports/2026".'},limit:{type:"number",description:"Max entries to return (default/max 1000)."},cursor:{type:"string",description:"Pagination cursor from a previous file_list response (nextCursor)."}},required:[]}},{name:"file_delete",description:"For FILE-type stores: delete ONE stored file by its relative path. Returns { ok, path, deleted }. Errors if the path does not exist.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},path:{type:"string",description:"The relative file path to delete."}},required:["path"]}}]};import{SKILL_META as Wm}from"@zibby/skill-ids";import{existsSync as ho,readFileSync as Zm}from"node:fs";import{homedir as Vm}from"node:os";import{join as Xm,dirname as Qm,resolve as eh}from"node:path";import{fileURLToPath as th}from"node:url";import{existsSync as pm}from"node:fs";import{dirname as um,resolve as mm}from"node:path";import{fileURLToPath as hm}from"node:url";var Q={ZERO_WIDTH:"zero-width-bar",ROW_COUNT:"data-row-count",ROW_MISSING:"data-row-missing",BAR_COUNT:"data-bar-count",BAR_PROPORTION:"bar-proportion",VALUE_MISMATCH:"data-value-mismatch",PLACEHOLDER_TEXT:"placeholder-text",OVERFLOW:"overflow-clipped"},fm=5,ym=20,gm=.04,_m=3,bm=.5;function ae(r,t){if(t==null||t<0)return null;let e=1;for(let n=0;n<t&&n<r.length;n+=1)r.charCodeAt(n)===10&&(e+=1);return e}function ce(r,t,e){let n=t[e.code]||0;n>=fm||r.length>=ym||(t[e.code]=n+1,r.push(e))}var km={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026"};function Vi(r){return String(r).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi,(t,e)=>{if(e[0]==="#"){let s=e[1]==="x"||e[1]==="X"?parseInt(e.slice(2),16):parseInt(e.slice(1),10);return Number.isFinite(s)?String.fromCodePoint(s):t}let n=km[String(e).toLowerCase()];return n??t})}function ze(r){return Vi(String(r??"")).replace(/\s+/g," ").trim().toLowerCase()}function Wi(r){return Math.round(r*10)/10}var wm=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),nn=new Set(["script","style","textarea"]),Sm=new Set(["span","a","em","strong","b","i","u","s","small","code","label","abbr","cite","q","sub","sup","mark","time","var","kbd","samp","font","tt"]),vm=/^<\s*(\/?)\s*([a-zA-Z][a-zA-Z0-9:_.-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/;function Im(r){let t={},e=/([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'=<>`]+))|([a-zA-Z_:][-a-zA-Z0-9_:.]*)/g,n;for(;(n=e.exec(r))!==null;)n[1]?t[n[1].toLowerCase()]=n[3]!=null?n[3]:n[4]!=null?n[4]:n[5]==null?"":n[5]:n[6]&&(t[n[6].toLowerCase()]="");return t}function Nm(r){let t={tag:"#root",attrs:{},children:[],parent:null,start:0},e=t,n=[t],s=0,i=(o,a)=>{if(a<=o)return;let c=r.slice(o,a);c.trim()&&e.children.push({tag:"#text",attrs:{},children:[],parent:e,start:o,value:c})};for(;s<r.length;){let o=r.indexOf("<",s);if(o<0){i(s,r.length);break}if(i(s,o),r.startsWith("<!--",o)){let p=r.indexOf("-->",o);s=p<0?r.length:p+3;continue}if(r.startsWith("<!",o)||r.startsWith("<?",o)){let p=r.indexOf(">",o);s=p<0?r.length:p+1;continue}let a=vm.exec(r.slice(o));if(!a){s=o+1;continue}let c=a[0],l=a[2].toLowerCase();if(a[1]){for(let p=n.length-1;p>0;p-=1)if(n[p].tag===l){n.length=p,e=n[p-1];break}s=o+c.length;continue}let d={tag:l,attrs:Im(a[3]||""),children:[],parent:e,start:o};if(e.children.push(d),s=o+c.length,!(a[4]||wm.has(l))){if(nn.has(l)){let p=r.slice(s),u=new RegExp(`</\\s*${l}\\s*>`,"i").exec(p);d.raw=u?p.slice(0,u.index):p,s+=u?u.index+u[0].length:p.length;continue}n.push(d),e=d}}return t}function je(r,t){for(let e of r.children)e.tag!=="#text"&&(t(e),je(e,t))}function lr(r){let t=[],e=n=>{for(let s of n.children)s.tag==="#text"?t.push(s.value||""):(t.push(" "),e(s),t.push(" "))};return e(r),ze(t.join(""))}function Tm(r){let t=[],e=n=>{for(let s of n.children)s.tag==="#text"?t.push({value:s.value||"",start:s.start,parent:n}):s.tag!=="pre"&&s.tag!=="code"&&e(s)};return e(r),t}function bt(r){let t={};for(let e of String(r||"").split(";")){let n=e.indexOf(":");n<0||(t[e.slice(0,n).trim().toLowerCase()]=e.slice(n+1).trim().replace(/\s*!important$/i,""))}return t}function Om(r){let t=[];return je(r,e=>{if(e.tag!=="style"||!e.raw)return;let n=e.raw.replace(/@[a-z-]+[^{]*\{/gi," "),s=/([^{}]+)\{([^{}]*)\}/g,i;for(;(i=s.exec(n))!==null;){let o=bt(i[2]);for(let a of i[1].split(",")){let c=a.trim();if(!c||/[\s>+~:[\]*]/.test(c))continue;let l=[],d=null,p=null,u=!0,m=/([.#]?)([A-Za-z_][-\w]*)/g,h;for(;(h=m.exec(c))!==null;)if(h[1]===".")l.push(h[2].toLowerCase());else if(h[1]==="#")d=h[2];else if(h.index===0)p=h[2].toLowerCase();else{u=!1;break}u&&(p||d||l.length)&&t.push({classes:l,id:d,tag:p,decls:o})}}}),t}function Xi(r){return String(r.attrs.class||"").split(/\s+/).filter(Boolean).map(t=>t.toLowerCase())}function Am(r,t,e){if(r.tag&&r.tag!==t.tag||r.id&&r.id!==t.attrs.id)return!1;for(let n of r.classes)if(e.indexOf(n)<0)return!1;return!0}function he(r,t,e){let n=bt(r.attrs.style)[t];if(n!=null&&n!=="")return n.toLowerCase();let s=Xi(r),i=null;for(let o of e){if(!Am(o,r,s))continue;let a=o.decls[t];a!=null&&a!==""&&(i=a.toLowerCase())}return i}function Zi(r,t){let e=he(r,"display",t);return e||(Sm.has(r.tag)?"inline":"block")}function rn(r){if(!r)return null;let t=/^(-?\d+(?:\.\d+)?)px$/.exec(String(r).trim());return t?Number(t[1]):null}function Qi(r){if(!r)return null;let t=/^(-?\d+(?:\.\d+)?)%$/.exec(String(r).trim());return t?Number(t[1]):null}function cr(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function Rm(r){if(!r.length||!cr(r[0]))return r.map(n=>n==null?"":String(n));let t=null,e=0;for(let n of Object.keys(r[0])){let s=r.map(o=>cr(o)&&o[n]!=null?String(o[n]):"");if(s.some(o=>o.length<2))continue;let i=new Set(s.map(ze)).size;if(i>e&&(e=i,t=s),i===r.length)break}return t||r.map((n,s)=>String(cr(n)?Object.values(n)[0]==null?s:Object.values(n)[0]:n))}function Em(r){let t=[],e=[],n=new Set,s=(o,a)=>{if(!(a.length<2)){if(a.every(cr)){t.push({path:o,records:a,identities:Rm(a)});let c=Object.keys(a[0]),l=c.filter(p=>a.every(u=>typeof u[p]=="number"&&Number.isFinite(u[p]))),d=c.filter(p=>a.every(u=>typeof u[p]=="string"));l.length===1&&d.length>=1&&e.push({path:o,labels:a.map(p=>String(p[d[0]])),values:a.map(p=>Number(p[l[0]]))});return}a.every(c=>typeof c=="number"&&Number.isFinite(c))&&e.push({path:o,labels:a.map((c,l)=>`#${l}`),values:a.slice()})}},i=(o,a,c)=>{if(!(c>6||o==null||typeof o!="object"||n.has(o))){if(n.add(o),Array.isArray(o)){s(a,o);for(let l=0;l<o.length&&l<200;l+=1)i(o[l],`${a}[${l}]`,c+1);return}for(let l of Object.keys(o))i(o[l],a?`${a}.${l}`:l,c+1)}};return i(r,"",0),{collections:t,series:e}}function xm(r){let t=String(r||"").match(/[MmLlHhVvZz]|-?\d*\.?\d+(?:e-?\d+)?/gi);if(!t)return null;let e=0,n=0,s="",i=1/0,o=-1/0,a=1/0,c=-1/0,l=()=>{!Number.isFinite(e)||!Number.isFinite(n)||(e<i&&(i=e),e>o&&(o=e),n<a&&(a=n),n>c&&(c=n))},d=0,p=0;for(;d<t.length&&p++<2e4;){let u=t[d];if(/[A-Za-z]/.test(u)&&(s=u,d+=1,s==="Z"||s==="z"))continue;if(d>=t.length)break;let m=()=>{let h=Number(t[d]);return d+=1,h};switch(s){case"M":e=m(),n=m(),l(),s="L";break;case"m":e+=m(),n+=m(),l(),s="l";break;case"L":e=m(),n=m(),l();break;case"l":e+=m(),n+=m(),l();break;case"H":e=m(),l();break;case"h":e+=m(),l();break;case"V":n=m(),l();break;case"v":n+=m(),l();break;default:d+=1;break}}return!Number.isFinite(i)||!Number.isFinite(a)?null:{w:o-i,h:c-a}}var Lm=/(^|[-_])(bar|gauge|meter|fill|progress|track)([-_]|$)/i;function jm(r){let t=r.parent;for(let e=0;t&&e<3;e+=1,t=t.parent){let n=lr(t);if(n)return n}return""}function eo(r,t){if(Xi(r).some(s=>Lm.test(s)))return!0;let e=bt(r.attrs.style);return!!(e.background||e["background-color"]||he(r,"background",t)||he(r,"background-color",t))&&lr(r)===""}function $m(r){let t=new Map;for(let n of r)for(let s=n.node.parent;s;s=s.parent)t.set(s,(t.get(s)||0)+1);let e=new Map;for(let n of r){let s=null;for(let i=n.node.parent;i;i=i.parent)if((t.get(i)||0)>=2){s=i;break}s&&(e.has(s)||e.set(s,[]),e.get(s).push(n))}return[...e.values()].filter(n=>n.length>=2)}function Pm(r,t){let e=new Map,n=[];je(r,i=>{if(i.tag==="path"||i.tag==="rect"){let d=i.attrs.ecmeta_series_index;if(d==null)return;let p=null;if(i.tag==="rect"){let h=Number(i.attrs.width),f=Number(i.attrs.height);Number.isFinite(h)&&Number.isFinite(f)&&(p={w:h,h:f})}else p=xm(i.attrs.d||"");if(!p)return;let u=i.attrs.ecmeta_data_index,m=String(d);e.has(m)||e.set(m,[]),e.get(m).push({bar:{node:i,extent:NaN,unit:"user",dataIndex:u==null||u===""?null:Number(u),context:"",start:i.start},box:p});return}if(nn.has(i.tag)||i.tag==="svg")return;let o=bt(i.attrs.style),a=o.width==null?o["inline-size"]:o.width;if(a==null||a==="")return;let c=Qi(a),l=rn(a);c==null&&l==null||eo(i,t)&&n.push({node:i,extent:c??l,unit:c==null?"px":"%",dataIndex:null,context:jm(i),start:i.start})});let s=[];for(let i of e.values()){if(i.length<2)continue;let o=l=>Math.max(...l)-Math.min(...l),a=o(i.map(l=>l.box.h))>=o(i.map(l=>l.box.w));for(let l of i)l.bar.extent=a?l.box.h:l.box.w;let c=i.map(l=>l.bar).sort((l,d)=>l.dataIndex!=null&&d.dataIndex!=null?l.dataIndex-d.dataIndex:l.start-d.start);s.push(c)}for(let i of $m(n)){let o=i.filter(l=>l.unit==="%"),a=i.filter(l=>l.unit==="px"),c=o.length>=a.length?o:a;c.length>=2&&s.push(c)}return s}function Cm(r){let t=[];return je(r,e=>{if(e.tag!=="table")return;let n=[];je(e,s=>{if(s.tag!=="tr")return;let i=s.children.filter(o=>o.tag==="td"||o.tag==="th");i.length&&i.every(o=>o.tag==="th")||n.push(s)}),t.push({node:e,rows:n,rowTexts:n.map(lr),start:e.start})}),t}function Um(r,t,e,n,s,i,o){let a=lr(t);for(let c of n){let l=c.records.length;if(l<3)continue;let d=[],p=0;for(let y of c.identities){let _=ze(y);!_||_.length<2||(p+=1,a.includes(_)||d.push(String(y)))}if(p<3)continue;let u=p-d.length,m=p?u/p:1,h=null,f=0;for(let y of e){if(!y.rows.length)continue;let _=0,g=new Set;for(let k of y.rowTexts){let T=!1;c.identities.forEach((M,ye)=>{let O=ze(M);O.length>=2&&k.indexOf(O)>=0&&(T=!0,g.add(ye))}),T&&(_+=1)}_<Math.max(2,Math.ceil(y.rows.length*.5))||g.size<Math.ceil(_*.8)||_>f&&(f=_,h=y)}let b=h!=null;o.push({path:c.path||"(root)",records:l,identitiesSearched:p,presentInPage:u,renderedFraction:Number(m.toFixed(3)),boundTableRows:b?h.rows.length:null}),!(m<bm)&&(d.length&&ce(s,i,{code:Q.ROW_MISSING,line:b?ae(r,h.start):1,message:`The data at \`${c.path||"(root)"}\` has ${l} records but ${d.length} of them appear NOWHERE on the page: ${d.slice(0,6).map(y=>JSON.stringify(String(y).slice(0,40))).join(", ")}${d.length>6?`, +${d.length-6} more`:""}.`,hint:"Render every record you were given, or say in the page that it is a partial view and how many were left out. A silently truncated table reads as the complete answer."}),d.length===0&&b&&h.rows.length!==l&&ce(s,i,{code:Q.ROW_COUNT,line:ae(r,h.start),message:`The table renders ${h.rows.length} body row(s) but the data at \`${c.path||"(root)"}\` has ${l} records \u2014 ${Math.abs(l-h.rows.length)} ${l>h.rows.length?"missing":"extra"}.`,hint:'Emit exactly one <tr> per record. If you meant to show only some of them, state the cut ("top 10 of 23") in the page itself.'}))}}function Bm(r,t){let e=new Array(r.length).fill(-1);if(r.every(i=>i.dataIndex!=null)){let i=0;if(r.forEach((o,a)=>{let c=o.dataIndex;c>=0&&c<t.values.length&&(e[a]=c,i+=1)}),i===r.length)return e}e.fill(-1);let n=new Set,s=0;if(r.forEach((i,o)=>{for(let a=0;a<t.labels.length;a+=1){if(n.has(a))continue;let c=ze(t.labels[a]);if(c.length>=2&&i.context.indexOf(c)>=0){e[o]=a,n.add(a),s+=1;break}}}),s===r.length)return e;if(r.length!==t.values.length)return null;for(let i=0;i<r.length;i+=1)e[i]=i;return e}function Dm(r,t){let e=null,n=0;for(let i of t){let o=i.labels.filter(a=>{let c=ze(a);return c.length>=2&&r.some(l=>l.context.indexOf(c)>=0)}).length;o>n&&(n=o,e=i)}if(n>=2)return e;let s=t.filter(i=>i.values.length===r.length);return s.length===1?s[0]:null}function Jm(r,t,e,n,s,i){i.barGroups=t.map(o=>o.length),i.boundBars=0;for(let o of t){let a=Dm(o,e);if(!a)continue;if(a.values.length!==o.length){ce(n,s,{code:Q.BAR_COUNT,line:ae(r,o[0].start),message:`The chart draws ${o.length} bar(s) but the series at \`${a.path||"(root)"}\` has ${a.values.length} value(s).`,hint:"Draw one bar per value. A dropped bar silently removes a whole category from the reader's view of the data."});continue}let c=Bm(o,a);if(!c||c.some(u=>u<0))continue;i.boundBars+=o.length;let l=[];for(let u=0;u<o.length;u+=1)o[u].extent>0&&a.values[c[u]]>0&&l.push(u);if(l.length>=_m){let u=l.map(y=>o[y].extent/a.values[c[y]]).sort((y,_)=>y-_),m=Math.floor(u.length/2),h=u.length%2?u[m]:(u[m-1]+u[m])/2,f=Math.max(...a.values.map(y=>Math.abs(y))),b=h*f;if(h>0&&b>0)for(let y of l){let _=a.values[c[y]],g=h*_,k=Math.abs(o[y].extent-g)/b;if(k<=gm)continue;let T=o[y].unit==="%"?"%":"";ce(n,s,{code:Q.BAR_PROPORTION,line:ae(r,o[y].start),message:`The bar for ${JSON.stringify(a.labels[c[y]])} (value ${_}) is drawn at ${Wi(o[y].extent)}${T}, but every other bar in this chart puts it at ${Wi(g)}${T} \u2014 off by ${Math.round(k*100)}% of the full-scale bar. The chart misrepresents the data.`,hint:"Every bar in one chart must use the SAME value\u2192length scale. Compute each length from its datum with one formula (value / max * 100), never by writing the numbers out by hand."})}}let d=a.values.reduce((u,m)=>u+m,0),p=Math.max(...a.values.map(u=>Math.abs(u)));for(let u=0;u<o.length;u+=1){let m=a.values[c[u]],h=o[u].context;if(!h)continue;let f=(h.match(/-?\d[\d,]*(?:\.\d+)?/g)||[]).map(b=>Number(b.replace(/,/g,""))).filter(b=>Number.isFinite(b));f.length&&(f.some(b=>Math.abs(b-m)<1e-9)||d>0&&f.some(b=>Math.abs(b-m/d*100)<.6)||p>0&&f.some(b=>Math.abs(b-m/p*100)<.6)||ce(n,s,{code:Q.VALUE_MISMATCH,line:ae(r,o[u].start),message:`The row for ${JSON.stringify(a.labels[c[u]])} prints ${f.slice(0,3).join(", ")} but its datum is ${m}.`,hint:"Print the figure your tools returned, unchanged, and use that same figure everywhere it appears on the page."}))}}}var Mm=/^(flex|inline-flex|grid|inline-grid)$/;function qm(r,t,e,n,s,i){let o=0;je(t,a=>{if(nn.has(a.tag))return;let c=bt(a.attrs.style).width;if(!c)return;let l=Qi(c);if(l==null||l<=0||!eo(a,e))return;o+=1;let d=Zi(a,e);if(d==="none"){ce(n,s,{code:Q.ZERO_WIDTH,line:ae(r,a.start),message:`<${a.tag}> is given style="width:${c}" but its effective display is \`none\` \u2014 it is not rendered at all.`,hint:"Remove the display:none rule that matches this element, or remove the element. A width on a display:none box is dead code."});return}if(d!=="inline")return;let p=a.parent;if(p&&p.tag!=="#root"&&Mm.test(Zi(p,e)))return;let u=he(a,"position",e);if(u==="absolute"||u==="fixed")return;let m=he(a,"float",e);m==="left"||m==="right"||ce(n,s,{code:Q.ZERO_WIDTH,line:ae(r,a.start),message:`<${a.tag}${a.attrs.class?` class="${a.attrs.class}"`:""}> is given style="width:${c}" but its effective display is \`inline\` \u2014 CSS IGNORES width on a non-replaced inline box, so this bar renders with no length at all. The source looks right; the page will not.`,hint:"Give the bar display:block or display:inline-block (or make its container display:flex). A <span> is inline by DEFAULT \u2014 that alone is enough to swallow the width."})}),i.percentWidthBars=o}function Fm(r,t,e,n,s){je(t,i=>{let o=rn(he(i,"width",e));if(!(o==null||o<=0))for(let a=i.parent;a&&a.tag!=="#root";a=a.parent){let c=rn(he(a,"width",e));if(c==null||c<=0)continue;if(o<=c)return;let l=he(a,"overflow",e)||he(a,"overflow-x",e);if(l!=="hidden"&&l!=="clip")return;ce(n,s,{code:Q.OVERFLOW,line:ae(r,i.start),message:`<${i.tag}> is ${o}px wide inside a ${c}px ancestor with overflow:${l} \u2014 ${Math.round(o-c)}px of it is clipped and can never be seen.`,hint:"Size the child from its container (a percentage, or max-width:100%), or widen the container. Content the reader cannot see is content you did not publish."});return}})}var Km=[{re:/\[object (?:Object|Array|Promise|Map|Set|Null|Undefined)\]/g,what:"an object stringified instead of a field being picked off it"},{re:/\$\{[^}\n]{0,80}\}/g,what:"an un-substituted JavaScript template placeholder"},{re:/\{\{[^}\n]{0,80}\}\}/g,what:"an un-substituted moustache placeholder"},{re:/(?:^|[^\w.])(NaN)(?![\w])/g,what:"NaN \u2014 an arithmetic result that was never a number"},{re:/(?:^|[^\w.])(-?Infinity)(?![\w])/g,what:"Infinity \u2014 a division by zero reached the page"}],Gm=/^(undefined|null)$/i,Hm=new Set(["td","th","li","span","div","strong","em","b"]);function Ym(r,t,e,n,s){let i=0;for(let o of Tm(t)){let a=o.value;i+=a.length;for(let l of Km){l.re.lastIndex=0;let d;for(;(d=l.re.exec(a))!==null;){let p=d[1]==null?d[0]:d[1];ce(e,n,{code:Q.PLACEHOLDER_TEXT,line:ae(r,o.start+d.index+d[0].indexOf(p)),message:`The page prints ${JSON.stringify(p.slice(0,60))} as VISIBLE TEXT \u2014 ${l.what}. A reader sees this literally.`,hint:"Format the value before it reaches the page: pick the field you meant off the object, and guard the arithmetic so a missing input renders as an em dash rather than NaN."}),d.index===l.re.lastIndex&&(l.re.lastIndex+=1)}}let c=Vi(a).trim();Gm.test(c)&&Hm.has(o.parent.tag)&&ce(e,n,{code:Q.PLACEHOLDER_TEXT,line:ae(r,o.start),message:`A <${o.parent.tag}> contains only the literal text "${c}" \u2014 the value it was meant to hold was ${c}.`,hint:'Render an em dash (\u2014) or "n/a" for a missing value; never let the JavaScript literal reach the reader.'})}s.textCharsScanned=i}function dr({html:r,data:t}){let e=typeof r=="string"?r:"",n=[],s={};if(!e.trim())return{ok:!1,defects:[{code:"empty-content",line:1,message:"No html was passed to the check.",hint:"Pass the exact page source you are about to publish."}],checked:{tables:0,bodyRows:0,bars:0,barGroups:[],boundBars:0,seriesInData:0,collections:[]}};let i=Nm(e),o=Om(i),a=Cm(i),c=Pm(i,o),l=Em(t),d={tables:a.length,bodyRows:a.reduce((p,u)=>p+u.rows.length,0),bars:c.reduce((p,u)=>p+u.length,0),barGroups:[],boundBars:0,seriesInData:l.series.length,collections:[]};return Um(e,i,a,l.collections,n,s,d.collections),Jm(e,c,l.series,n,s,d),qm(e,i,o,n,s,d),Fm(e,i,o,n,s),Ym(e,i,n,s,d),n.sort((p,u)=>(p.line||0)-(u.line||0)),{ok:n.length===0,defects:n,checked:d}}function zm(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=um(hm(import.meta.url)),t=mm(r,"..","bin","mcp-skill.mjs");return pm(t)?t:null}var to={id:"report-check",serverName:"report_check",allowedTools:["mcp__report_check__*"],envKeys:[],description:"Report check \u2014 verify a rendered report page against the DATA it was built from (row counts, bar proportionality, collapsed bars, placeholder residue) before publishing it.",promptFragment:`## Report Check (run this BEFORE you publish a data page)
|
|
791
|
+
store (or a file tool on either, etc.) is rejected.`,resolve(){let r=gh();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=qe(e?.store);if(t.error)return JSON.stringify({error:t.error});let n=typeof e?.agent=="string"&&e.agent.trim()?e.agent.trim():xo(),s={record:e.record,agent:n};typeof e?.description=="string"&&e.description.trim()&&(s.description=e.description.trim());let i=await _e(t.storeId,"append",s);return JSON.stringify({...i,store:t.name,storeId:t.storeId})}case"dataset_query":{let t=qe(e?.store);if(t.error)return JSON.stringify({error:t.error});let n={};for(let i of["select","where","groupBy","orderBy","limit","since","until","agent"])e?.[i]!=null&&(n[i]=e[i]);let s=await _e(t.storeId,"query",n);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"ensure_store":{let t=typeof e?.name=="string"?e.name.trim():"";if(!t)return JSON.stringify({error:"name is required"});let n=typeof e?.type=="string"&&e.type.trim()?e.type.trim().toLowerCase():"sqlite",s=typeof e?.description=="string"?e.description.trim():"",i=await _h({name:t,type:n,description:s,namespace:xo()});return i?.storeId&&(Po[t]=i.storeId),JSON.stringify({...i,store:t})}case"file_put":{let t=qe(e?.store);if(t.error)return JSON.stringify({error:t.error});if(typeof e?.path!="string"||!e.path.trim())return JSON.stringify({error:'path is required (a relative file path like "reports/2026-07.json")'});let n=typeof e?.content=="string",s=typeof e?.contentBase64=="string"&&e.contentBase64.length>0;if(!n&&!s)return JSON.stringify({error:"content (text) or contentBase64 (base64 bytes) is required"});let i=e.path.trim(),o=typeof e?.contentType=="string"&&e.contentType.trim()?e.contentType.trim():"",a=n?Buffer.from(e.content,"utf8"):Buffer.from(String(e.contentBase64).replace(/\s+/g,""),"base64");if(a.length>kh){let d=o||(n?"text/plain; charset=utf-8":"application/octet-stream"),p=await wh(t.storeId,i,a,d);return JSON.stringify({...p,store:t.name,storeId:t.storeId})}let c={path:i};n?c.content=e.content:c.contentBase64=e.contentBase64,o&&(c.contentType=o);let l=await _e(t.storeId,"put",c);return JSON.stringify({...l,store:t.name,storeId:t.storeId})}case"file_get":{let t=qe(e?.store);if(t.error)return JSON.stringify({error:t.error});if(typeof e?.path!="string"||!e.path.trim())return JSON.stringify({error:"path is required"});let n=e.path.trim(),s;try{s=await _e(t.storeId,"get",{path:n})}catch(c){if(!/failed \(413\)/.test(c?.message||""))throw c;let l=await Sh(t.storeId,n);s={path:n,size:l.buf.length,contentType:l.contentType,lastModified:null,contentBase64:l.buf.toString("base64")}}let i={ok:!0,store:t.name,storeId:t.storeId,path:s.path,size:s.size,contentType:s.contentType,lastModified:s.lastModified},o=Buffer.from(s.contentBase64||"","base64"),a=o.toString("utf8");return Buffer.compare(Buffer.from(a,"utf8"),o)===0&&!a.includes("\0")?(i.content=a,i.encoding="utf8"):(i.contentBase64=s.contentBase64,i.encoding="base64"),JSON.stringify(i)}case"file_list":{let t=qe(e?.store);if(t.error)return JSON.stringify({error:t.error});let n={};typeof e?.prefix=="string"&&e.prefix.trim()&&(n.prefix=e.prefix.trim()),e?.limit!=null&&(n.limit=e.limit),typeof e?.cursor=="string"&&e.cursor&&(n.cursor=e.cursor);let s=await _e(t.storeId,"list",n);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"file_delete":{let t=qe(e?.store);if(t.error)return JSON.stringify({error:t.error});if(typeof e?.path!="string"||!e.path.trim())return JSON.stringify({error:"path is required"});let n=await _e(t.storeId,"delete",{path:e.path.trim()});return JSON.stringify({...n,store:t.name,storeId:t.storeId})}case"sqlite_exec":case"sqlite_query":{let t=qe(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};r==="sqlite_query"&&(n.readOnly=!0),Array.isArray(e?.params)&&(n.params=e.params);let s=await _e(t.storeId,"sql",n);return JSON.stringify({...s,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","file"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics. "file" = arbitrary file/blob storage by relative path (file_put/file_get/file_list/file_delete).'},description:{type:"string",description:"What this store is for (shown in the Storage UI)."}},required:["name"]}},{name:"sqlite_exec",description:"For SQLITE-type stores: run SQL that CHANGES data \u2014 CREATE TABLE (use IF NOT EXISTS), INSERT, UPDATE, DELETE (one or more statements in one call). The store is a real, mutable SQLite database that persists across your stateless runs. Returns { rowsModified, wrote }. Use this to build schema on the fly and to update rows / track changing state (e.g. a queue with a status column).",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:'The SQL to run. May contain multiple statements separated by ";". Prefer CREATE TABLE IF NOT EXISTS for idempotent schema.'},params:{type:"array",description:'Optional positional bind params for a SINGLE parameterized statement (safe binding of values), e.g. sql "UPDATE t SET s=? WHERE id=?" with params ["done", 1].'}},required:["sql"]}},{name:"sqlite_query",description:"For SQLITE-type stores: run a read-only SELECT (optionally with `params` for safe binding) against the store's SQLite database. Returns { columns, rows }. Never changes data. Use to read back rows/state you stored earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:"A single SELECT statement. Use ? placeholders + `params` for any values."},params:{type:"array",description:'Optional positional bind params for the SELECT, e.g. ["linkedin_personal"].'}},required:["sql"]}},{name:"file_put",description:"For FILE-type stores: write (or overwrite) ONE file at a relative path \u2014 raw JSON dumps, CSVs, images, snapshots, any blob you want to keep across your stateless runs. Text goes in `content`; binary goes base64-encoded in `contentBase64` (pass exactly one). SIZE: there is no practical limit \u2014 anything over ~3.5 MiB is streamed straight to object storage via a presigned URL automatically, so do NOT gzip, base64-wrap, chunk or split a file just to make it fit. Non-ASCII paths (e.g. \u4E2A\u4EBA\u62A5\u544A.html) are fine \u2014 do not transliterate. Overwriting the same path UPDATES the file. Returns { ok, path, size }.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},path:{type:"string",description:'Relative file path, e.g. "dumps/run-42.json" or "img/chart.png". Letters, digits, ".", "_", "-" and "/" only; no "..", no leading "/".'},content:{type:"string",description:"Text content (UTF-8). Use for JSON/CSV/text files."},contentBase64:{type:"string",description:"Base64-encoded binary content (images etc.). Alternative to `content`."},contentType:{type:"string",description:'Optional MIME type (e.g. "application/json", "image/png"). Defaults sensibly.'}},required:["path"]}},{name:"file_get",description:'For FILE-type stores: read ONE stored file back by its relative path. Text files come back as `content` (encoding "utf8"); binary files come back as `contentBase64` (encoding "base64"). Returns { path, size, contentType, lastModified, content|contentBase64, encoding }.',input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},path:{type:"string",description:"The relative file path to fetch (as listed by file_list / used in file_put)."}},required:["path"]}},{name:"file_list",description:'For FILE-type stores: list the stored files \u2014 each entry has { path, size, lastModified }. Optionally filter by a path `prefix` (e.g. "dumps/"). Paginated via `cursor` when there are more results.',input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},prefix:{type:"string",description:'Optional path prefix filter, e.g. "dumps/" or "reports/2026".'},limit:{type:"number",description:"Max entries to return (default/max 1000)."},cursor:{type:"string",description:"Pagination cursor from a previous file_list response (nextCursor)."}},required:[]}},{name:"file_delete",description:"For FILE-type stores: delete ONE stored file by its relative path. Returns { ok, path, deleted }. Errors if the path does not exist.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a file-type store from AVAILABLE STORES). If exactly one store is bound you may omit this."},path:{type:"string",description:"The relative file path to delete."}},required:["path"]}}]};import{SKILL_META as cf}from"@zibby/skill-ids";import{existsSync as ta,readFileSync as lf}from"node:fs";import{homedir as df}from"node:os";import{join as pf,dirname as uf,resolve as mf}from"node:path";import{fileURLToPath as hf}from"node:url";import{existsSync as vh}from"node:fs";import{dirname as Ih,resolve as Th}from"node:path";import{fileURLToPath as Nh}from"node:url";var re={ZERO_WIDTH:"zero-width-bar",ROW_COUNT:"data-row-count",ROW_MISSING:"data-row-missing",BAR_COUNT:"data-bar-count",BAR_PROPORTION:"bar-proportion",VALUE_MISMATCH:"data-value-mismatch",PLACEHOLDER_TEXT:"placeholder-text",OVERFLOW:"overflow-clipped"},Oh=5,Ah=20,Rh=.04,Eh=3,xh=.5;function ue(r,e){if(e==null||e<0)return null;let t=1;for(let n=0;n<e&&n<r.length;n+=1)r.charCodeAt(n)===10&&(t+=1);return t}function me(r,e,t){let n=e[t.code]||0;n>=Oh||r.length>=Ah||(e[t.code]=n+1,r.push(t))}var Lh={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026"};function Do(r){return String(r).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi,(e,t)=>{if(t[0]==="#"){let s=t[1]==="x"||t[1]==="X"?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Number.isFinite(s)?String.fromCodePoint(s):e}let n=Lh[String(t).toLowerCase()];return n??e})}function ot(r){return Do(String(r??"")).replace(/\s+/g," ").trim().toLowerCase()}function Uo(r){return Math.round(r*10)/10}var $h=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),En=new Set(["script","style","textarea"]),jh=new Set(["span","a","em","strong","b","i","u","s","small","code","label","abbr","cite","q","sub","sup","mark","time","var","kbd","samp","font","tt"]),Ph=/^<\s*(\/?)\s*([a-zA-Z][a-zA-Z0-9:_.-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/;function Ch(r){let e={},t=/([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'=<>`]+))|([a-zA-Z_:][-a-zA-Z0-9_:.]*)/g,n;for(;(n=t.exec(r))!==null;)n[1]?e[n[1].toLowerCase()]=n[3]!=null?n[3]:n[4]!=null?n[4]:n[5]==null?"":n[5]:n[6]&&(e[n[6].toLowerCase()]="");return e}function Uh(r){let e={tag:"#root",attrs:{},children:[],parent:null,start:0},t=e,n=[e],s=0,i=(o,a)=>{if(a<=o)return;let c=r.slice(o,a);c.trim()&&t.children.push({tag:"#text",attrs:{},children:[],parent:t,start:o,value:c})};for(;s<r.length;){let o=r.indexOf("<",s);if(o<0){i(s,r.length);break}if(i(s,o),r.startsWith("<!--",o)){let p=r.indexOf("-->",o);s=p<0?r.length:p+3;continue}if(r.startsWith("<!",o)||r.startsWith("<?",o)){let p=r.indexOf(">",o);s=p<0?r.length:p+1;continue}let a=Ph.exec(r.slice(o));if(!a){s=o+1;continue}let c=a[0],l=a[2].toLowerCase();if(a[1]){for(let p=n.length-1;p>0;p-=1)if(n[p].tag===l){n.length=p,t=n[p-1];break}s=o+c.length;continue}let d={tag:l,attrs:Ch(a[3]||""),children:[],parent:t,start:o};if(t.children.push(d),s=o+c.length,!(a[4]||$h.has(l))){if(En.has(l)){let p=r.slice(s),u=new RegExp(`</\\s*${l}\\s*>`,"i").exec(p);d.raw=u?p.slice(0,u.index):p,s+=u?u.index+u[0].length:p.length;continue}n.push(d),t=d}}return e}function Ge(r,e){for(let t of r.children)t.tag!=="#text"&&(e(t),Ge(t,e))}function Nr(r){let e=[],t=n=>{for(let s of n.children)s.tag==="#text"?e.push(s.value||""):(e.push(" "),t(s),e.push(" "))};return t(r),ot(e.join(""))}function Bh(r){let e=[],t=n=>{for(let s of n.children)s.tag==="#text"?e.push({value:s.value||"",start:s.start,parent:n}):s.tag!=="pre"&&s.tag!=="code"&&t(s)};return t(r),e}function Lt(r){let e={};for(let t of String(r||"").split(";")){let n=t.indexOf(":");n<0||(e[t.slice(0,n).trim().toLowerCase()]=t.slice(n+1).trim().replace(/\s*!important$/i,""))}return e}function Dh(r){let e=[];return Ge(r,t=>{if(t.tag!=="style"||!t.raw)return;let n=t.raw.replace(/@[a-z-]+[^{]*\{/gi," "),s=/([^{}]+)\{([^{}]*)\}/g,i;for(;(i=s.exec(n))!==null;){let o=Lt(i[2]);for(let a of i[1].split(",")){let c=a.trim();if(!c||/[\s>+~:[\]*]/.test(c))continue;let l=[],d=null,p=null,u=!0,m=/([.#]?)([A-Za-z_][-\w]*)/g,h;for(;(h=m.exec(c))!==null;)if(h[1]===".")l.push(h[2].toLowerCase());else if(h[1]==="#")d=h[2];else if(h.index===0)p=h[2].toLowerCase();else{u=!1;break}u&&(p||d||l.length)&&e.push({classes:l,id:d,tag:p,decls:o})}}}),e}function Mo(r){return String(r.attrs.class||"").split(/\s+/).filter(Boolean).map(e=>e.toLowerCase())}function Mh(r,e,t){if(r.tag&&r.tag!==e.tag||r.id&&r.id!==e.attrs.id)return!1;for(let n of r.classes)if(t.indexOf(n)<0)return!1;return!0}function ke(r,e,t){let n=Lt(r.attrs.style)[e];if(n!=null&&n!=="")return n.toLowerCase();let s=Mo(r),i=null;for(let o of t){if(!Mh(o,r,s))continue;let a=o.decls[e];a!=null&&a!==""&&(i=a.toLowerCase())}return i}function Bo(r,e){let t=ke(r,"display",e);return t||(jh.has(r.tag)?"inline":"block")}function Rn(r){if(!r)return null;let e=/^(-?\d+(?:\.\d+)?)px$/.exec(String(r).trim());return e?Number(e[1]):null}function Jo(r){if(!r)return null;let e=/^(-?\d+(?:\.\d+)?)%$/.exec(String(r).trim());return e?Number(e[1]):null}function Tr(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function Jh(r){if(!r.length||!Tr(r[0]))return r.map(n=>n==null?"":String(n));let e=null,t=0;for(let n of Object.keys(r[0])){let s=r.map(o=>Tr(o)&&o[n]!=null?String(o[n]):"");if(s.some(o=>o.length<2))continue;let i=new Set(s.map(ot)).size;if(i>t&&(t=i,e=s),i===r.length)break}return e||r.map((n,s)=>String(Tr(n)?Object.values(n)[0]==null?s:Object.values(n)[0]:n))}function qh(r){let e=[],t=[],n=new Set,s=(o,a)=>{if(!(a.length<2)){if(a.every(Tr)){e.push({path:o,records:a,identities:Jh(a)});let c=Object.keys(a[0]),l=c.filter(p=>a.every(u=>typeof u[p]=="number"&&Number.isFinite(u[p]))),d=c.filter(p=>a.every(u=>typeof u[p]=="string"));l.length===1&&d.length>=1&&t.push({path:o,labels:a.map(p=>String(p[d[0]])),values:a.map(p=>Number(p[l[0]]))});return}a.every(c=>typeof c=="number"&&Number.isFinite(c))&&t.push({path:o,labels:a.map((c,l)=>`#${l}`),values:a.slice()})}},i=(o,a,c)=>{if(!(c>6||o==null||typeof o!="object"||n.has(o))){if(n.add(o),Array.isArray(o)){s(a,o);for(let l=0;l<o.length&&l<200;l+=1)i(o[l],`${a}[${l}]`,c+1);return}for(let l of Object.keys(o))i(o[l],a?`${a}.${l}`:l,c+1)}};return i(r,"",0),{collections:e,series:t}}function Gh(r){let e=String(r||"").match(/[MmLlHhVvZz]|-?\d*\.?\d+(?:e-?\d+)?/gi);if(!e)return null;let t=0,n=0,s="",i=1/0,o=-1/0,a=1/0,c=-1/0,l=()=>{!Number.isFinite(t)||!Number.isFinite(n)||(t<i&&(i=t),t>o&&(o=t),n<a&&(a=n),n>c&&(c=n))},d=0,p=0;for(;d<e.length&&p++<2e4;){let u=e[d];if(/[A-Za-z]/.test(u)&&(s=u,d+=1,s==="Z"||s==="z"))continue;if(d>=e.length)break;let m=()=>{let h=Number(e[d]);return d+=1,h};switch(s){case"M":t=m(),n=m(),l(),s="L";break;case"m":t+=m(),n+=m(),l(),s="l";break;case"L":t=m(),n=m(),l();break;case"l":t+=m(),n+=m(),l();break;case"H":t=m(),l();break;case"h":t+=m(),l();break;case"V":n=m(),l();break;case"v":n+=m(),l();break;default:d+=1;break}}return!Number.isFinite(i)||!Number.isFinite(a)?null:{w:o-i,h:c-a}}var Kh=/(^|[-_])(bar|gauge|meter|fill|progress|track)([-_]|$)/i;function Fh(r){let e=r.parent;for(let t=0;e&&t<3;t+=1,e=e.parent){let n=Nr(e);if(n)return n}return""}function qo(r,e){if(Mo(r).some(s=>Kh.test(s)))return!0;let t=Lt(r.attrs.style);return!!(t.background||t["background-color"]||ke(r,"background",e)||ke(r,"background-color",e))&&Nr(r)===""}function Hh(r){let e=new Map;for(let n of r)for(let s=n.node.parent;s;s=s.parent)e.set(s,(e.get(s)||0)+1);let t=new Map;for(let n of r){let s=null;for(let i=n.node.parent;i;i=i.parent)if((e.get(i)||0)>=2){s=i;break}s&&(t.has(s)||t.set(s,[]),t.get(s).push(n))}return[...t.values()].filter(n=>n.length>=2)}function zh(r,e){let t=new Map,n=[];Ge(r,i=>{if(i.tag==="path"||i.tag==="rect"){let d=i.attrs.ecmeta_series_index;if(d==null)return;let p=null;if(i.tag==="rect"){let h=Number(i.attrs.width),y=Number(i.attrs.height);Number.isFinite(h)&&Number.isFinite(y)&&(p={w:h,h:y})}else p=Gh(i.attrs.d||"");if(!p)return;let u=i.attrs.ecmeta_data_index,m=String(d);t.has(m)||t.set(m,[]),t.get(m).push({bar:{node:i,extent:NaN,unit:"user",dataIndex:u==null||u===""?null:Number(u),context:"",start:i.start},box:p});return}if(En.has(i.tag)||i.tag==="svg")return;let o=Lt(i.attrs.style),a=o.width==null?o["inline-size"]:o.width;if(a==null||a==="")return;let c=Jo(a),l=Rn(a);c==null&&l==null||qo(i,e)&&n.push({node:i,extent:c??l,unit:c==null?"px":"%",dataIndex:null,context:Fh(i),start:i.start})});let s=[];for(let i of t.values()){if(i.length<2)continue;let o=l=>Math.max(...l)-Math.min(...l),a=o(i.map(l=>l.box.h))>=o(i.map(l=>l.box.w));for(let l of i)l.bar.extent=a?l.box.h:l.box.w;let c=i.map(l=>l.bar).sort((l,d)=>l.dataIndex!=null&&d.dataIndex!=null?l.dataIndex-d.dataIndex:l.start-d.start);s.push(c)}for(let i of Hh(n)){let o=i.filter(l=>l.unit==="%"),a=i.filter(l=>l.unit==="px"),c=o.length>=a.length?o:a;c.length>=2&&s.push(c)}return s}function Yh(r){let e=[];return Ge(r,t=>{if(t.tag!=="table")return;let n=[];Ge(t,s=>{if(s.tag!=="tr")return;let i=s.children.filter(o=>o.tag==="td"||o.tag==="th");i.length&&i.every(o=>o.tag==="th")||n.push(s)}),e.push({node:t,rows:n,rowTexts:n.map(Nr),start:t.start})}),e}function Wh(r,e,t,n,s,i,o){let a=Nr(e);for(let c of n){let l=c.records.length;if(l<3)continue;let d=[],p=0;for(let f of c.identities){let b=ot(f);!b||b.length<2||(p+=1,a.includes(b)||d.push(String(f)))}if(p<3)continue;let u=p-d.length,m=p?u/p:1,h=null,y=0;for(let f of t){if(!f.rows.length)continue;let b=0,g=new Set;for(let k of f.rowTexts){let v=!1;c.identities.forEach((x,V)=>{let R=ot(x);R.length>=2&&k.indexOf(R)>=0&&(v=!0,g.add(V))}),v&&(b+=1)}b<Math.max(2,Math.ceil(f.rows.length*.5))||g.size<Math.ceil(b*.8)||b>y&&(y=b,h=f)}let _=h!=null;o.push({path:c.path||"(root)",records:l,identitiesSearched:p,presentInPage:u,renderedFraction:Number(m.toFixed(3)),boundTableRows:_?h.rows.length:null}),!(m<xh)&&(d.length&&me(s,i,{code:re.ROW_MISSING,line:_?ue(r,h.start):1,message:`The data at \`${c.path||"(root)"}\` has ${l} records but ${d.length} of them appear NOWHERE on the page: ${d.slice(0,6).map(f=>JSON.stringify(String(f).slice(0,40))).join(", ")}${d.length>6?`, +${d.length-6} more`:""}.`,hint:"Render every record you were given, or say in the page that it is a partial view and how many were left out. A silently truncated table reads as the complete answer."}),d.length===0&&_&&h.rows.length!==l&&me(s,i,{code:re.ROW_COUNT,line:ue(r,h.start),message:`The table renders ${h.rows.length} body row(s) but the data at \`${c.path||"(root)"}\` has ${l} records \u2014 ${Math.abs(l-h.rows.length)} ${l>h.rows.length?"missing":"extra"}.`,hint:'Emit exactly one <tr> per record. If you meant to show only some of them, state the cut ("top 10 of 23") in the page itself.'}))}}function Zh(r,e){let t=new Array(r.length).fill(-1);if(r.every(i=>i.dataIndex!=null)){let i=0;if(r.forEach((o,a)=>{let c=o.dataIndex;c>=0&&c<e.values.length&&(t[a]=c,i+=1)}),i===r.length)return t}t.fill(-1);let n=new Set,s=0;if(r.forEach((i,o)=>{for(let a=0;a<e.labels.length;a+=1){if(n.has(a))continue;let c=ot(e.labels[a]);if(c.length>=2&&i.context.indexOf(c)>=0){t[o]=a,n.add(a),s+=1;break}}}),s===r.length)return t;if(r.length!==e.values.length)return null;for(let i=0;i<r.length;i+=1)t[i]=i;return t}function Vh(r,e){let t=null,n=0;for(let i of e){let o=i.labels.filter(a=>{let c=ot(a);return c.length>=2&&r.some(l=>l.context.indexOf(c)>=0)}).length;o>n&&(n=o,t=i)}if(n>=2)return t;let s=e.filter(i=>i.values.length===r.length);return s.length===1?s[0]:null}function Xh(r,e,t,n,s,i){i.barGroups=e.map(o=>o.length),i.boundBars=0;for(let o of e){let a=Vh(o,t);if(!a)continue;if(a.values.length!==o.length){me(n,s,{code:re.BAR_COUNT,line:ue(r,o[0].start),message:`The chart draws ${o.length} bar(s) but the series at \`${a.path||"(root)"}\` has ${a.values.length} value(s).`,hint:"Draw one bar per value. A dropped bar silently removes a whole category from the reader's view of the data."});continue}let c=Zh(o,a);if(!c||c.some(u=>u<0))continue;i.boundBars+=o.length;let l=[];for(let u=0;u<o.length;u+=1)o[u].extent>0&&a.values[c[u]]>0&&l.push(u);if(l.length>=Eh){let u=l.map(f=>o[f].extent/a.values[c[f]]).sort((f,b)=>f-b),m=Math.floor(u.length/2),h=u.length%2?u[m]:(u[m-1]+u[m])/2,y=Math.max(...a.values.map(f=>Math.abs(f))),_=h*y;if(h>0&&_>0)for(let f of l){let b=a.values[c[f]],g=h*b,k=Math.abs(o[f].extent-g)/_;if(k<=Rh)continue;let v=o[f].unit==="%"?"%":"";me(n,s,{code:re.BAR_PROPORTION,line:ue(r,o[f].start),message:`The bar for ${JSON.stringify(a.labels[c[f]])} (value ${b}) is drawn at ${Uo(o[f].extent)}${v}, but every other bar in this chart puts it at ${Uo(g)}${v} \u2014 off by ${Math.round(k*100)}% of the full-scale bar. The chart misrepresents the data.`,hint:"Every bar in one chart must use the SAME value\u2192length scale. Compute each length from its datum with one formula (value / max * 100), never by writing the numbers out by hand."})}}let d=a.values.reduce((u,m)=>u+m,0),p=Math.max(...a.values.map(u=>Math.abs(u)));for(let u=0;u<o.length;u+=1){let m=a.values[c[u]],h=o[u].context;if(!h)continue;let y=(h.match(/-?\d[\d,]*(?:\.\d+)?/g)||[]).map(_=>Number(_.replace(/,/g,""))).filter(_=>Number.isFinite(_));y.length&&(y.some(_=>Math.abs(_-m)<1e-9)||d>0&&y.some(_=>Math.abs(_-m/d*100)<.6)||p>0&&y.some(_=>Math.abs(_-m/p*100)<.6)||me(n,s,{code:re.VALUE_MISMATCH,line:ue(r,o[u].start),message:`The row for ${JSON.stringify(a.labels[c[u]])} prints ${y.slice(0,3).join(", ")} but its datum is ${m}.`,hint:"Print the figure your tools returned, unchanged, and use that same figure everywhere it appears on the page."}))}}}var Qh=/^(flex|inline-flex|grid|inline-grid)$/;function ef(r,e,t,n,s,i){let o=0;Ge(e,a=>{if(En.has(a.tag))return;let c=Lt(a.attrs.style).width;if(!c)return;let l=Jo(c);if(l==null||l<=0||!qo(a,t))return;o+=1;let d=Bo(a,t);if(d==="none"){me(n,s,{code:re.ZERO_WIDTH,line:ue(r,a.start),message:`<${a.tag}> is given style="width:${c}" but its effective display is \`none\` \u2014 it is not rendered at all.`,hint:"Remove the display:none rule that matches this element, or remove the element. A width on a display:none box is dead code."});return}if(d!=="inline")return;let p=a.parent;if(p&&p.tag!=="#root"&&Qh.test(Bo(p,t)))return;let u=ke(a,"position",t);if(u==="absolute"||u==="fixed")return;let m=ke(a,"float",t);m==="left"||m==="right"||me(n,s,{code:re.ZERO_WIDTH,line:ue(r,a.start),message:`<${a.tag}${a.attrs.class?` class="${a.attrs.class}"`:""}> is given style="width:${c}" but its effective display is \`inline\` \u2014 CSS IGNORES width on a non-replaced inline box, so this bar renders with no length at all. The source looks right; the page will not.`,hint:"Give the bar display:block or display:inline-block (or make its container display:flex). A <span> is inline by DEFAULT \u2014 that alone is enough to swallow the width."})}),i.percentWidthBars=o}function tf(r,e,t,n,s){Ge(e,i=>{let o=Rn(ke(i,"width",t));if(!(o==null||o<=0))for(let a=i.parent;a&&a.tag!=="#root";a=a.parent){let c=Rn(ke(a,"width",t));if(c==null||c<=0)continue;if(o<=c)return;let l=ke(a,"overflow",t)||ke(a,"overflow-x",t);if(l!=="hidden"&&l!=="clip")return;me(n,s,{code:re.OVERFLOW,line:ue(r,i.start),message:`<${i.tag}> is ${o}px wide inside a ${c}px ancestor with overflow:${l} \u2014 ${Math.round(o-c)}px of it is clipped and can never be seen.`,hint:"Size the child from its container (a percentage, or max-width:100%), or widen the container. Content the reader cannot see is content you did not publish."});return}})}var rf=[{re:/\[object (?:Object|Array|Promise|Map|Set|Null|Undefined)\]/g,what:"an object stringified instead of a field being picked off it"},{re:/\$\{[^}\n]{0,80}\}/g,what:"an un-substituted JavaScript template placeholder"},{re:/\{\{[^}\n]{0,80}\}\}/g,what:"an un-substituted moustache placeholder"},{re:/(?:^|[^\w.])(NaN)(?![\w])/g,what:"NaN \u2014 an arithmetic result that was never a number"},{re:/(?:^|[^\w.])(-?Infinity)(?![\w])/g,what:"Infinity \u2014 a division by zero reached the page"}],nf=/^(undefined|null)$/i,sf=new Set(["td","th","li","span","div","strong","em","b"]);function of(r,e,t,n,s){let i=0;for(let o of Bh(e)){let a=o.value;i+=a.length;for(let l of rf){l.re.lastIndex=0;let d;for(;(d=l.re.exec(a))!==null;){let p=d[1]==null?d[0]:d[1];me(t,n,{code:re.PLACEHOLDER_TEXT,line:ue(r,o.start+d.index+d[0].indexOf(p)),message:`The page prints ${JSON.stringify(p.slice(0,60))} as VISIBLE TEXT \u2014 ${l.what}. A reader sees this literally.`,hint:"Format the value before it reaches the page: pick the field you meant off the object, and guard the arithmetic so a missing input renders as an em dash rather than NaN."}),d.index===l.re.lastIndex&&(l.re.lastIndex+=1)}}let c=Do(a).trim();nf.test(c)&&sf.has(o.parent.tag)&&me(t,n,{code:re.PLACEHOLDER_TEXT,line:ue(r,o.start),message:`A <${o.parent.tag}> contains only the literal text "${c}" \u2014 the value it was meant to hold was ${c}.`,hint:'Render an em dash (\u2014) or "n/a" for a missing value; never let the JavaScript literal reach the reader.'})}s.textCharsScanned=i}function Or({html:r,data:e}){let t=typeof r=="string"?r:"",n=[],s={};if(!t.trim())return{ok:!1,defects:[{code:"empty-content",line:1,message:"No html was passed to the check.",hint:"Pass the exact page source you are about to publish."}],checked:{tables:0,bodyRows:0,bars:0,barGroups:[],boundBars:0,seriesInData:0,collections:[]}};let i=Uh(t),o=Dh(i),a=Yh(i),c=zh(i,o),l=qh(e),d={tables:a.length,bodyRows:a.reduce((p,u)=>p+u.rows.length,0),bars:c.reduce((p,u)=>p+u.length,0),barGroups:[],boundBars:0,seriesInData:l.series.length,collections:[]};return Wh(t,i,a,l.collections,n,s,d.collections),Xh(t,c,l.series,n,s,d),ef(t,i,o,n,s,d),tf(t,i,o,n,s),of(t,i,n,s,d),n.sort((p,u)=>(p.line||0)-(u.line||0)),{ok:n.length===0,defects:n,checked:d}}function af(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ih(Nh(import.meta.url)),e=Th(r,"..","bin","mcp-skill.mjs");return vh(e)?e:null}var Go={id:"report-check",serverName:"report_check",allowedTools:["mcp__report_check__*"],envKeys:[],description:"Report check \u2014 verify a rendered report page against the DATA it was built from (row counts, bar proportionality, collapsed bars, placeholder residue) before publishing it.",promptFragment:`## Report Check (run this BEFORE you publish a data page)
|
|
794
792
|
When you are about to publish a page that RENDERS DATA \u2014 a table of records, a
|
|
795
793
|
bar chart, a set of meters \u2014 call \`report_check\` first with the exact \`html\`
|
|
796
794
|
you are about to publish and the \`data\` you built it from (the raw tool
|
|
@@ -806,9 +804,9 @@ from the data by itself.
|
|
|
806
804
|
|
|
807
805
|
Then READ the \`checked\` block in the result: it says how many tables, rows and
|
|
808
806
|
bars were actually found. If it reports 0 bars for a page full of bars, the check
|
|
809
|
-
never saw your chart and a clean verdict means nothing.`,resolve(){let r=
|
|
810
|
-
${
|
|
811
|
-
`)}`}function
|
|
807
|
+
never saw your chart and a clean verdict means nothing.`,resolve(){let r=af();return r?{type:"stdio",command:"node",args:[r,"../dist/reportCheck.js","reportCheckSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,e){if(r!=="report_check")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=typeof e?.html=="string"?e.html:"";if(!t.trim())return JSON.stringify({error:"html is required \u2014 pass the exact page source you are about to publish."});let n=e?.data;if(typeof n=="string")try{n=JSON.parse(n)}catch{return JSON.stringify({error:"data was a string but not valid JSON \u2014 pass the data as a JSON object."})}return n==null?JSON.stringify({error:"data is required \u2014 pass the tool results the page was built from, unchanged."}):JSON.stringify(Or({html:t,data:n}))}catch(t){return JSON.stringify({error:`report_check failed: ${t.message}`})}},tools:[{name:"report_check",description:'Pre-flight a data page BEFORE publishing it: compares the rendered HTML against the DATA it was built from and reports every place they disagree. Catches what the publish validator structurally cannot \u2014 a table that renders fewer rows than the data has records, a bar drawn at a length that is not proportional to its value, a number printed beside a bar that is not that bar\'s datum, a bar whose width is silently nullified by the CSS cascade, and placeholder residue ([object Object], NaN, an un-substituted ${\u2026}) left in visible text. Pass the data UNCHANGED, exactly as your tools returned it (wrap a bare array as {"rows": [...]}) \u2014 the check discovers the collections and series inside it and derives what must be true on its own. Do NOT write your own expectations. Returns { ok, defects:[{code,line,message,hint}], checked }. Always read `checked`: it reports how many tables, rows and bars were found, so a clean `ok:true` with `bars: 0` on a chart page tells you the check never saw your chart.',input_schema:{type:"object",properties:{html:{type:"string",description:"The exact HTML you are about to publish (the same string you would pass to artifact_publish)."},data:{type:"object",description:'The data the page was built from, as JSON \u2014 the raw tool results. Any shape: arrays of records and label/value series are found automatically. Wrap a bare top-level array as {"rows": [...]}.'}},required:["html","data"]}}]};function ff(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=uf(hf(import.meta.url)),e=mf(r,"..","bin","mcp-skill.mjs");return ta(e)?e:null}function jt(){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=pf(df(),".zibby","config.json");return ta(r)&&JSON.parse(lf(r,"utf-8")).sessionToken||null}catch{return null}}function Pt(){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 yf(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function ra(r){return`${yf()}:artifact:${r}`}var at="headings, paragraphs, **bold**, *italic*, `inline code`, fenced code blocks, bullet + numbered lists, blockquotes, horizontal rules, links, and GitHub-style pipe tables (including |---:| alignment)",Rr="raw HTML (tags are escaped and print as literal text), images, nested lists, footnotes and strikethrough",Ko='It is read in a list next to everything else you and your teammates have ever published, so it must say WHAT THIS ONE IS \u2014 the subject, not the genre. "Vikunja label sort toggle \u2014 3 of 5 checks failed" survives that list; "Exploration Report" does not, and three of those in a row are indistinguishable. Name the specific thing: the ticket, the feature, the file, the finding.',Fo='A self-explanatory Markdown STORY shown UNDER the artifact on its page \u2014 a recording or a screenshot cannot explain itself: without this the whole page says `video/webm \xB7 3.8 MB \xB7 Download`. Structure it as: (1) ONE opening sentence of context + goal \u2014 what task this artifact is about and what it is meant to show or prove, written for a reader who knows nothing; (2) the STORY \u2014 what was done and what happened, in plain prose or short bullets; (3) ONE closing sentence \u2014 what the reader should conclude. Complete sentences, Markdown formatting (short paragraphs, bullets) welcome. NEVER compressed arrow-chains ("A \u2192 B \u2192 C"), bare procedure logs, or unexplained jargon \u2014 a step list with no goal and no conclusion explains nothing.',$t=2,ct=0;function Ln(r,e){return JSON.stringify({published:!1,stop:!0,attemptsUsed:$t,defects:e||[],error:r,instruction:`STOP. You have used both publish attempts and the page is still rejected. Do NOT call artifact_publish or artifact_update again in this turn. Tell the user plainly that you could not produce a clean page, say in one line what was wrong, and give them the content directly in the chat instead. A broken link is worse than an honest "I couldn't".`})}function gf(r,e,t){return JSON.stringify({published:!1,stop:!1,attemptsRemaining:$t-ct,defects:t||[],error:e,instruction:"The page was NOT published and no URL exists. Fix EXACTLY the defects listed above and call once more \u2014 you get ONE more attempt, then this tool will stop you."+(r==="html"?` You are on the \`html\` path, where you author the entire document and every mistake ships. Unless this page genuinely needs a custom visual layout, the fastest and most reliable fix is to re-send the SAME content as \`markdown\` \u2014 Zibby then generates the document skeleton, CSS and tables for you and these defects become impossible. Markdown supports ${at}.`:` Markdown supports ${at}; it does NOT support ${Rr}.`)})}var Ho="The page WAS published and the url is valid. This only means the data\u2194render pre-flight could not reach a verdict \u2014 nothing is known to be wrong. Open the page yourself if the figures matter.";function bf(r){let e=new Set,t=(r||[]).map((s,i)=>{let o=s.line?` line ${s.line}:`:"",a="";return s.hint&&!e.has(s.code)&&(e.add(s.code),a=` \u2014 ${s.hint}`),`${i+1}. [${s.code}]${o} ${s.message}${a}`}),n=t.length;return`Artifact NOT published and NOTHING was sent \u2014 the page was checked against the \`data\` you passed and disagrees with it in ${n} place${n===1?"":"s"}:
|
|
808
|
+
${t.join(`
|
|
809
|
+
`)}`}function _f(r,e){let t;try{t=Or({html:r,data:e})}catch(i){return{unverified:{status:"unverified",reason:`the data\u2194render pre-flight threw and was skipped: ${String(i?.message||i).slice(0,200)}`,note:Ho}}}if(!t?.ok)return{rejected:{message:bf(t?.defects),defects:t?.defects||[]}};let n=t.checked||{};return(Number(n.tables)||0)+(Number(n.bars)||0)===0?{unverified:{status:"unverified",reason:"the pre-flight found no tables and no bars in this page, so it had nothing to compare against your data \u2014 a clean result here proves nothing",checked:n,note:Ho}}:null}function zo(r,e,t){return ct+=1,{__rejected:!0,payload:ct>=$t?Ln(e,t):gf(r,e,t)}}async function kf(r){let e=jt();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let t=await w(`${Pt()}/credits/artifacts`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)},{kind:"api",what:"artifact publish"});if(!t.ok){let n=await t.text().catch(()=>""),s=null;try{s=JSON.parse(n)}catch{}let i=new Error(t.status===422&&s?.error?s.error:`artifact write failed (${t.status}): ${n.slice(0,300)}`);throw i.status=t.status,Array.isArray(s?.defects)&&(i.defects=s.defects),i}return t.json()}async function Yo(r,e,t){let n=t?_f(t.html,t.data):null;if(n?.rejected)return zo(e,n.rejected.message,n.rejected.defects);try{let s=await kf(r);return ct=0,n?.unverified&&(s.__preflightNote=n.unverified),s}catch(s){if(s?.status!==422)throw s;return zo(e,s.message,s.defects)}}async function na(r){let e=jt();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let t=await w(`${Pt()}/credits/artifacts/${encodeURIComponent(r)}`,{method:"GET",headers:{Authorization:`Bearer ${e}`}},{kind:"api",what:`artifact read ${r}`});if(!t.ok){let n=await t.text().catch(()=>"");throw new Error(`artifact get failed (${t.status}): ${n.slice(0,300)}`)}return t.json()}async function Wo(r,e,t={}){let n=jt();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let s=await w(`${Pt()}/credits/artifacts/${encodeURIComponent(r)}/${e}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)},{kind:"api",what:`artifact ${e} ${r}`});if(!s.ok){let i=await s.text().catch(()=>""),o=null;try{o=JSON.parse(i)}catch{}throw new Error(o?.error||`artifact ${e} failed (${s.status}): ${i.slice(0,300)}`)}return s.json()}var xn=60;function Zo(r,e){let t=Math.max(0,e-Math.floor(xn/2)),s=r.slice(t,t+xn).replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");return(t>0?"\u2026":"")+s+(t+xn<r.length?"\u2026":"")}function wf(r,e){if(r===e)return null;let t=Math.min(r.length,e.length),n=0;for(;n<t&&r[n]===e[n];)n+=1;return{kind:n===t?e.length<r.length?"truncated":"longer":"diverged",sentChars:r.length,storedChars:e.length,delta:e.length-r.length,firstDiffAt:n,sentExcerpt:Zo(r,n),storedExcerpt:Zo(e,n)}}var Ar="Read-back compares the STORED SOURCE with what was sent (transport/storage integrity only). It does NOT check that the page renders correctly.";async function Vo(r,e){let t;try{t=await na(r)}catch(i){return{status:"unverified",scope:Ar,reason:`read-back request failed: ${String(i?.message||i).slice(0,200)}`,note:"The page WAS published and the url is valid \u2014 this only means the extra integrity check could not run. No action needed."}}let n=t?.content;if(typeof n!="string")return{status:"unverified",scope:Ar,reason:"read-back returned no content field",note:"The page WAS published and the url is valid \u2014 this only means the extra integrity check could not run. No action needed."};if(n===""&&e!=="")return{status:"unverified",scope:Ar,reason:"read-back returned empty content, which the backend also returns when its object-store read errors \u2014 indistinguishable, so this is inconclusive rather than a mismatch",note:"The page WAS published and the url is valid. If the page looks blank when opened, re-send the same content with artifact_update."};let s=wf(e,n);return s?{status:"mismatch",scope:Ar,...s,note:`The stored page source is NOT what was sent (${s.kind}: sent ${s.sentChars} chars, stored ${s.storedChars}, first difference at character ${s.firstDiffAt}). The url exists and the page is live, so do NOT re-publish a new one. You may call artifact_update ONCE with the identical content to rewrite the blob; if it differs again, stop and tell the user the published page may be incomplete rather than retrying.`}:null}async function Xo(r,e){let t=jt();if(!t)return;let n=await w(`${Pt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:"store",scope:ra(r),content:JSON.stringify(e)})},{kind:"api",what:"artifact index store"});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`artifact index write failed (${n.status}): ${s.slice(0,200)}`)}}async function Sf(r){let e=jt();if(!e)return null;let t=await w(`${Pt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:"recall",scope:ra(r)})},{kind:"api",what:"artifact index recall"});if(!t.ok)return null;let n=await t.json().catch(()=>null);if(!n?.found||!n?.memory?.content)return null;try{return JSON.parse(n.memory.content)}catch{return null}}function Qo(r){let e=typeof r?.html=="string"&&r.html.length>0,t=typeof r?.markdown=="string"&&r.markdown.length>0,n=typeof r?.text=="string"&&r.text.length>0;return n&&(e||t)?{error:"Pass exactly ONE of markdown, html or text \u2014 text is raw source stored as-is (code/logs/JSON/CSV); markdown and html are rendered documents."}:e&&t?{error:"Pass EITHER markdown OR html, not both \u2014 they are different rendering paths. Use markdown unless the page needs a custom visual layout."}:t?{format:"markdown",content:r.markdown}:e?{format:"html",content:r.html}:n?{format:"text",content:r.text}:null}function ea(r,e){let t=r?.data;if(t==null)return null;if(!e||e.format!=="html")return{error:"`data` is only meaningful together with `html`. The pre-flight reads a rendered HTML document (tables, bars, CSS), so on the markdown path it would check nothing while reporting a clean page \u2014 that is worse than not checking. Re-send WITHOUT `data`. Do NOT switch to `html` just to get the check: on the markdown path Zibby generates the document, so the collapsed-bar and broken-geometry defects it looks for cannot happen there in the first place."};let n=t;if(typeof n=="string")try{n=JSON.parse(n)}catch{return{error:'`data` was a string but not valid JSON \u2014 pass the tool results as a JSON object (wrap a bare array as {"rows": [...]}).'}}return{preflight:{html:e.content,data:n}}}var sa={id:"artifact",callsBackend:!0,meta:cf.artifact,serverName:"artifact",allowedTools:["mcp__artifact__*"],description:"Artifacts \u2014 publish a self-contained, shareable HTML/Markdown page to Zibby and get back a URL; the index of what you published is your memory.",promptFragment:`## Artifacts (publish a shareable page, remember what you made)
|
|
812
810
|
You can PUBLISH a standalone page \u2014 a status report, a plan, a comparison table,
|
|
813
811
|
a dashboard-y summary, a diagram, a "here's what I found" write-up \u2014 and get back
|
|
814
812
|
a shareable URL.
|
|
@@ -816,7 +814,7 @@ a shareable URL.
|
|
|
816
814
|
### WRITE IT AS MARKDOWN. That is the default, and it is not a stylistic hint.
|
|
817
815
|
Pass \`markdown\` and Zibby generates the whole document for you \u2014 doctype, head,
|
|
818
816
|
CSS, typography, dark mode, table styling. You supply only the CONTENT. Markdown
|
|
819
|
-
supports ${
|
|
817
|
+
supports ${at}. It does NOT support ${Rr}.
|
|
820
818
|
|
|
821
819
|
Pass \`html\` ONLY when the page genuinely needs a visual layout Markdown cannot
|
|
822
820
|
express \u2014 a bar chart, a gauge, a custom grid, an SVG diagram. On the html path
|
|
@@ -830,9 +828,9 @@ credentials), so on the html path keep ALL CSS/JS/images INLINE (inline
|
|
|
830
828
|
load. NEVER escape the document: send real tags, not \`<div>\`.
|
|
831
829
|
|
|
832
830
|
### NAME IT FOR SOMEONE SCROLLING A LIST OF FIFTY, and CAPTION IT.
|
|
833
|
-
The \`title\`: ${
|
|
831
|
+
The \`title\`: ${Ko}
|
|
834
832
|
|
|
835
|
-
Then pass \`description\`: ${
|
|
833
|
+
Then pass \`description\`: ${Fo} Headings, bullets and
|
|
836
834
|
tables are all fine. Write one for every artifact a human will open.
|
|
837
835
|
|
|
838
836
|
The SAME two rules govern an artifact a TOOL creates for you \u2014 a browser
|
|
@@ -922,7 +920,7 @@ sharing it silently.
|
|
|
922
920
|
To recall WHAT YOU HAVE ALREADY PUBLISHED, use your kv-memory tool
|
|
923
921
|
kv_recall_prefix with keyPrefix "artifact:" \u2014 each entry is the index record
|
|
924
922
|
{ id, title, url, kind, createdAt, summary } for a page you made. (Publishing
|
|
925
|
-
records this automatically; you don't store it yourself.)`,resolve(){let r=rh();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/artifact.js","artifactSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(r,t){try{switch(r){case"artifact_publish":{if(Ze>=kt)return on("Publish budget already spent this turn.",[]);let e=typeof t?.title=="string"?t.title.trim():"";if(!e)return JSON.stringify({error:"title is required"});let n=uo(t);if(!n)return JSON.stringify({error:"provide exactly one of markdown (preferred) or html or text (non-empty string)"});if(n.error)return JSON.stringify({error:n.error});let s=mo(t,n);if(s?.error)return JSON.stringify({error:s.error});if(n.format==="text"&&!(typeof t?.contentType=="string"?t.contentType.trim():""))return JSON.stringify({error:"contentType is required with text \u2014 text/plain for code/logs, application/json for JSON data, text/csv for CSV"});let i={title:e,[n.format]:n.content};n.format==="text"&&(i.contentType=t.contentType.trim()),typeof t?.kind=="string"&&t.kind.trim()&&(i.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(i.favicon=t.favicon.trim()),typeof t?.description=="string"&&t.description.trim()&&(i.description=t.description),t?.share===!0&&(i.share=!0);let o=await oo(i,n.format,s?.preflight);if(o?.__rejected)return o.payload;let a=o?.id,c=o?.url;if(!a||!c)return JSON.stringify({error:"artifact write returned no id/url",response:o});let l={id:a,url:c};typeof o.rn=="string"&&o.rn&&(l.rn=o.rn),o.shared&&(l.shared=!0,l.shareUrl=o.shareUrl,l.password=o.password,l.instruction="Send BOTH the shareUrl and the password in your reply. Copy the password EXACTLY \u2014 it is case-sensitive, shown once, and cannot be looked up again (artifact_share issues a new one, which kills this one)."),o.__preflightNote&&(l.preflight=o.__preflightNote);let d=await lo(a,n.content);d&&(l.readBack=d);let p={id:a,title:e,url:c,kind:i.kind||null,createdAt:o.createdAt||new Date().toISOString(),summary:typeof t?.summary=="string"&&t.summary.trim()?t.summary.trim():e};n.format==="text"?(p.contentType=typeof o.contentType=="string"?o.contentType:i.contentType,p.bytes=typeof o.bytes=="number"?o.bytes:Buffer.byteLength(n.content,"utf8")):(p.format=n.format,p.bytes=Buffer.byteLength(n.content,"utf8"));try{await po(a,p)}catch(u){l.indexWarning=u.message}return JSON.stringify(l)}case"artifact_update":{if(Ze>=kt)return on("Publish budget already spent this turn.",[]);let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=uo(t);if(n?.error)return JSON.stringify({error:n.error});let s=typeof t?.title=="string"?t.title.trim():"",i=typeof t?.description=="string"&&t.description.trim();if(!n&&!s&&!i)return JSON.stringify({error:"nothing to update \u2014 pass a new title, description, and/or markdown|html"});let o=mo(t,n);if(o?.error)return JSON.stringify({error:o.error});let a={id:e};s&&(a.title=s),n&&(a[n.format]=n.content),typeof t?.kind=="string"&&t.kind.trim()&&(a.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(a.favicon=t.favicon.trim()),i&&(a.description=t.description);let c=await oo(a,n?.format,o?.preflight);if(c?.__rejected)return c.payload;let l=c?.url;if(!l)return JSON.stringify({error:"artifact update returned no url",response:c});let d={id:e,url:l};if(typeof c.rn=="string"&&c.rn&&(d.rn=c.rn),c.__preflightNote&&(d.preflight=c.__preflightNote),n){let m=await lo(e,n.content);m&&(d.readBack=m)}let p=await lh(e)||{},u={...p,id:e,url:l,title:s||p.title||"Untitled",kind:a.kind||p.kind||null,createdAt:p.createdAt||c.createdAt||new Date().toISOString(),updatedAt:c.updatedAt||new Date().toISOString()};n&&(n.format==="text"?(u.contentType=typeof c.contentType=="string"?c.contentType:p.contentType||null,u.bytes=typeof c.bytes=="number"?c.bytes:Buffer.byteLength(n.content,"utf8")):(u.format=n.format,u.bytes=Buffer.byteLength(n.content,"utf8"))),typeof t?.summary=="string"&&t.summary.trim()?u.summary=t.summary.trim():u.summary||(u.summary=u.title);try{await po(e,u)}catch(m){d.indexWarning=m.message}return JSON.stringify(d)}case"artifact_get":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=await yo(e);return JSON.stringify(n)}case"artifact_share":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=await ao(e,"protect");return JSON.stringify({id:n.id,url:n.url,password:n.password,shared:!0,instruction:"Send BOTH the url and the password to the person who asked. Copy the password EXACTLY \u2014 it is case-sensitive and cannot be recovered later (call artifact_share again to issue a new one)."})}case"artifact_unshare":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let n=await ao(e,"unprotect");return JSON.stringify({id:n.id,shared:!1,wasShared:n.wasShared})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"artifact_publish",description:`Publish a NEW self-contained, shareable page (report/plan/table/dashboard/diagram/write-up) and get back a shareable URL. USE \`markdown\` \u2014 it is the default path and Zibby generates the entire document for you (doctype, head, CSS, dark mode, table styling); you supply only the content, so the page cannot come out malformed. Markdown supports ${We}; it does NOT support ${ur}. Use \`html\` ONLY when the page needs a visual layout Markdown cannot express (a bar chart, a gauge, a custom grid, an SVG diagram) \u2014 on that path you author the whole document and every mistake ships verbatim. Never pass both. Use \`text\` (+ required \`contentType\`) to publish RAW SOURCE as-is \u2014 code, a script, logs, JSON data, CSV. It is stored verbatim, never rendered as a page, and shown in a read-only code viewer with a download link. contentType: text/plain for code/logs/scripts, application/json for JSON data, text/csv for CSV. For code, put the FILENAME in \`title\` (e.g. "deploy.sh") \u2014 viewers derive the language label from the extension \u2014 and set kind: "code". Exactly one of markdown|html|text per call. Every figure on the page must come from a tool result or this conversation \u2014 do not do arithmetic in prose and print the result, and use the same number everywhere it appears. The content MUST come from the current conversation or data you fetched this turn; if you are not sure what the page should be about, ASK instead of calling this tool, and never publish a demo/sample/placeholder or an account-overview page as a stand-in. On the html path keep all CSS/JS/images INLINE (inline <style>/<script>, data: URIs) and send real tags (never <escaped> markup) \u2014 the page is sandboxed on view with no network at all, so every external URL is dead. PASS \`data\` WHENEVER THE HTML PAGE RENDERS A DATASET \u2014 a table of records, a bar chart, a row of meters. Give it the raw tool results the page was built from, unchanged; the page is then checked AGAINST that data before anything is sent, catching a table short of rows, a bar drawn at the wrong length, and leftover \${\u2026} or [object Object]. It costs you nothing when the page is right. Skip it for prose pages, and never pass it with \`markdown\` (that is an error, not a no-op). The content is VALIDATED before any URL exists: if it is broken \u2014 by that data check or by the server \u2014 you get the exact defects and line numbers back, you get ONE retry, and then the tool stops you. Both kinds of rejection share the SAME two attempts. Returns { id, url }. PASS \`share: true\` WHEN THE READERS HAVE NO ZIBBY ACCOUNT \u2014 you get back { shareUrl, password } in this same call, instead of publishing a link they cannot open and then having to call artifact_share. The password is GENERATED; you never invent one. Without \`share\` the page is member-only, which is the default and is correct for anything internal.`,input_schema:{type:"object",properties:{title:{type:"string",description:`The page title (also the browser tab title). ${ro}`},markdown:{type:"string",description:`PREFERRED. The page content as Markdown \u2014 Zibby renders it into a styled, self-contained document, so you never author a skeleton. Supports ${We}. Does NOT support ${ur}. Provide this OR html, never both.`},html:{type:"string",description:"The EXCEPTION path \u2014 only for a layout Markdown cannot express (bar chart, gauge, custom grid, SVG diagram). A self-contained HTML document or fragment, served VERBATIM: you own the doctype, head, CSS and every tag. All assets must be inline (<style>/<script>, data: URIs). Provide this OR markdown, never both."},text:{type:"string",description:'RAW SOURCE published as-is \u2014 code, a script, logs, JSON data, CSV. Stored verbatim (never rendered as an HTML page) and shown in a read-only code viewer with a download link. Requires `contentType`. For code, make `title` the filename (e.g. "deploy.sh" \u2014 the viewer derives the language from the extension) and set kind: "code". Provide this OR markdown OR html.'},contentType:{type:"string",description:"REQUIRED with `text`, meaningless otherwise. One of: text/plain (code, scripts, logs), application/json (JSON data), text/csv (CSV). Nothing else is accepted \u2014 HTML and Markdown are published through their own fields, never as text."},data:{type:"object",description:'Optional, and worth passing WHENEVER the html page renders a dataset (a table of records, a bar chart, meters): the raw tool results the page was built from, as JSON, UNCHANGED \u2014 do not summarise it and do not write your own expectations, the check derives what must be true by itself (wrap a bare array as {"rows": [...]}). The page is then verified against it BEFORE publishing: row counts, bar lengths vs their values, bars whose width the CSS throws away, and placeholder residue. If they disagree nothing is sent and you get the defects back, using one of your two attempts. Only valid with `html` \u2014 passing it with `markdown` is an error.'},kind:{type:"string",description:'Optional label for what this is, e.g. "report", "plan", "dashboard", "diagram". Stored in your index.'},favicon:{type:"string",description:'Optional emoji used as the browser-tab icon, e.g. "\u{1F4CA}".'},summary:{type:"string",description:"Optional one-line summary for your own index (defaults to the title). Helps you recall later what this page was."},description:{type:"string",description:`Optional. ${no} This is the artifact's caption, NOT its content: the page/file itself is the content, and a reader who opens it should be able to understand what they are looking at without asking you. Write it as a short report with headings, bullets and tables (same Markdown subset as the \`markdown\` field, 16 KB max).`},share:{type:"boolean",description:"Set true to publish the page WITH a password link in one step \u2014 the response then also carries { shareUrl, password }, which you send together. Use it whenever the people who asked are in a chat channel and have no Zibby account. Omit it (the default) for anything internal: the page is then readable only by logged-in members of this project, and no password exists."}},required:["title"]}},{name:"artifact_update",description:"Revise an EXISTING artifact by id \u2014 the shareable URL stays the same, the content is replaced (new version). Pass the fields to change (title and/or markdown|html|text). `text` only replaces an artifact that was PUBLISHED as text, and it keeps its original contentType \u2014 the server refuses a type change and any doc\u2194text conversion. Prefer `markdown` for the same reason artifact_publish does: Zibby generates the document, so it cannot come out malformed. An update is validated exactly like a publish \u2014 including the optional `data` check when you send new `html` that renders a dataset \u2014 and if the new content is broken it is REFUSED, the page keeps its last good version, and the rejection shares the same two attempts as publish. Returns { id, url }.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to update (from a prior artifact_publish, or your kv-memory "artifact:" index).'},title:{type:"string",description:"New title (optional)."},markdown:{type:"string",description:`PREFERRED. New Markdown content (optional) \u2014 Zibby renders the document skeleton. Supports ${We}. Provide this OR html.`},html:{type:"string",description:"New HTML content (optional), served verbatim \u2014 only for layouts Markdown cannot express. Provide this OR markdown."},text:{type:"string",description:"New raw text content (optional) \u2014 only for an artifact that was PUBLISHED as text. It keeps its original contentType; the server refuses a type change or a doc\u2194text conversion. Provide at most one of markdown|html|text."},data:{type:"object",description:"Optional \u2014 same as on artifact_publish: when the new `html` renders a dataset, pass the raw tool results it was built from and the page is checked against them before anything is sent. Only valid alongside new `html`."},kind:{type:"string",description:"Optional updated kind label."},favicon:{type:"string",description:"Optional updated emoji favicon."},summary:{type:"string",description:"Optional updated one-line index summary."},description:{type:"string",description:"Optional updated Markdown note shown under the artifact on its detail page. You may pass this ALONE to add or rewrite the explanation without touching the artifact itself \u2014 the content keeps its current version."}},required:["id"]}},{name:"artifact_get",description:'Fetch ONE artifact you published, by id \u2192 { metadata, content }. Use to reuse / edit / re-publish a page. To LIST what you have published, use your kv-memory tool kv_recall_prefix with keyPrefix "artifact:".',input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id."}},required:["id"]}},{name:"artifact_share",description:"Make an artifact viewable WITHOUT a Zibby login, by password. Returns { url, password } \u2014 a link anyone can open plus the password that opens it. USE THIS when the people who need to read the page do not have Zibby accounts \u2014 the usual case is a Lark or Slack channel where you were asked for something and the channel members are not Zibby users. The normal artifact url only opens for logged-in members of this project, so for those recipients it is a dead link; this is what makes it readable. You MUST then send BOTH the url and the password in your reply, and copy the password EXACTLY (it is case-sensitive). It is shown ONCE and cannot be looked up afterwards \u2014 if it is lost, call this again to issue a new one, which also stops the old one working. Works on any artifact you published, old or new. Calling it again on an already-shared artifact replaces the password. Use artifact_unshare to revoke.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to share (from artifact_publish, or your kv-memory "artifact:" index).'}},required:["id"]}},{name:"artifact_unshare",description:`REMOVE an artifact's password \u2014 this is the tool for "take the password off", "remove the password", "stop sharing" and "revoke the link", which are all the same act. The page goes back to the DEFAULT it was published with: viewable only by logged-in members of this project, with no password anywhere. Immediate and total: anyone who already entered the password loses access too, not just new visitors. Safe to call on an artifact that was never shared. Note what this does NOT do: there is no way to leave a page open to anyone with the link and no password. Removing the password closes the anonymous door; it does not prop it open. Say that plainly if you are asked for a passwordless public link.`,input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id to stop sharing."}},required:["id"]}}]};import{createRequire as dh}from"node:module";import{randomBytes as ph}from"node:crypto";import{existsSync as So,mkdirSync as uh,writeFileSync as _o}from"node:fs";import{dirname as vo,join as Ve,resolve as Io}from"node:path";import{fileURLToPath as No}from"node:url";var To=dh(import.meta.url),an=null;function mh(){return an||(an=To("echarts")),an}var cn=null;function hh(){return cn||(cn=To("@resvg/resvg-js")),cn}var fh=800,yh=600,gh=4096,_h=16,bo=60,Oo="Noto Sans",ko=256*1024;function bh(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=vo(No(import.meta.url)),t=Io(r,"..","bin","mcp-skill.mjs");return So(t)?t:null}function kh(){let r=vo(No(import.meta.url)),t=Io(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(e=>Ve(t,e)).filter(e=>So(e))}function wh(){let r=process.env.ZIBBY_NODE_SESSION_PATH,t=process.env.ZIBBY_SESSION_PATH,e=r||(t?Ve(t,"chart-render"):Ve(process.cwd(),".zibby","output","charts"));return uh(e,{recursive:!0}),e}function $e(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function wo(r,t){let e=Number(r);return Number.isFinite(e)?Math.max(_h,Math.min(gh,Math.round(e))):t}function ln(r){return typeof r!="string"||r.length<=bo?r:`${r.slice(0,bo-1)}\u2026`}function mr(r){if(Array.isArray(r))for(let t=0;t<r.length;t++){let e=r[t];typeof e=="string"?r[t]=ln(e):$e(e)&&typeof e.name=="string"&&(e.name=ln(e.name))}}function Sh(r){for(let n of["xAxis","yAxis"]){let s=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let i of s)$e(i)&&mr(i.data)}let t=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of t)$e(n)&&mr(n.indicator);$e(r.legend)&&mr(r.legend.data);let e=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of e)$e(n)&&(typeof n.name=="string"&&(n.name=ln(n.name)),mr(n.data))}function vh(r){let t=JSON.parse(JSON.stringify(r));return t.animation=!1,t.backgroundColor==null&&(t.backgroundColor="#fff"),$e(t.textStyle)||(t.textStyle={}),t.textStyle.fontFamily==null&&(t.textStyle.fontFamily=Oo),Sh(t),t}function Ih(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Nh(r,t,e){let s=mh().init(null,null,{renderer:"svg",ssr:!0,width:t,height:e});try{return s.setOption(r),s.renderToSVGString()}finally{s.dispose()}}function Th(r){return r.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"")}function Oh(r,t){return r.replace(/id="zr\d+-/g,`id="${t}-`).replace(/url\(#zr\d+-/g,`url(#${t}-`).replace(/class="zr\d+-/g,`class="${t}-`)}function Ah(r){let t=[];for(let e of r.matchAll(/(?:xlink:)?href\s*=\s*"([^"]*)"/gi)){let n=e[1].trim();n&&!n.startsWith("#")&&!/^data:/i.test(n)&&t.push(n)}for(let e of r.matchAll(/url\(\s*['"]?([^'")]*)['"]?\s*\)/gi)){let n=e[1].trim();n&&!n.startsWith("#")&&!/^data:/i.test(n)&&t.push(n)}return/@import/i.test(r)&&t.push("@import"),/<script\b/i.test(r)&&t.push("<script>"),/<foreignObject\b/i.test(r)&&t.push("<foreignObject>"),t}function Rh(r){let t=Oh(Th(r),`chart-${ph(4).toString("hex")}`),e=Ah(t);if(e.length){let n=[...new Set(e)].slice(0,3).join(", ");throw new Error(`the rendered chart references external resources (${n}), which a self-contained HTML page blocks. Remove image:// symbols / external image fills from the spec (use plain colors or a data: URI), or use output:'svg' to write a file instead.`)}return t}function Eh(r){let{Resvg:t}=hh();return new t(r,{font:{fontFiles:kh(),loadSystemFonts:!0,defaultFontFamily:Oo}}).render().asPng()}var Ao={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)
|
|
923
|
+
records this automatically; you don't store it yourself.)`,resolve(){let r=ff();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/artifact.js","artifactSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"artifact_publish":{if(ct>=$t)return Ln("Publish budget already spent this turn.",[]);let t=typeof e?.title=="string"?e.title.trim():"";if(!t)return JSON.stringify({error:"title is required"});let n=Qo(e);if(!n)return JSON.stringify({error:"provide exactly one of markdown (preferred) or html or text (non-empty string)"});if(n.error)return JSON.stringify({error:n.error});let s=ea(e,n);if(s?.error)return JSON.stringify({error:s.error});if(n.format==="text"&&!(typeof e?.contentType=="string"?e.contentType.trim():""))return JSON.stringify({error:"contentType is required with text \u2014 text/plain for code/logs, application/json for JSON data, text/csv for CSV"});let i={title:t,[n.format]:n.content};n.format==="text"&&(i.contentType=e.contentType.trim()),typeof e?.kind=="string"&&e.kind.trim()&&(i.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(i.favicon=e.favicon.trim()),typeof e?.description=="string"&&e.description.trim()&&(i.description=e.description),e?.share===!0&&(i.share=!0);let o=await Yo(i,n.format,s?.preflight);if(o?.__rejected)return o.payload;let a=o?.id,c=o?.url;if(!a||!c)return JSON.stringify({error:"artifact write returned no id/url",response:o});let l={id:a,url:c};typeof o.rn=="string"&&o.rn&&(l.rn=o.rn),o.shared&&(l.shared=!0,l.shareUrl=o.shareUrl,l.password=o.password,l.instruction="Send BOTH the shareUrl and the password in your reply. Copy the password EXACTLY \u2014 it is case-sensitive, shown once, and cannot be looked up again (artifact_share issues a new one, which kills this one)."),o.__preflightNote&&(l.preflight=o.__preflightNote);let d=await Vo(a,n.content);d&&(l.readBack=d);let p={id:a,title:t,url:c,kind:i.kind||null,createdAt:o.createdAt||new Date().toISOString(),summary:typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():t};n.format==="text"?(p.contentType=typeof o.contentType=="string"?o.contentType:i.contentType,p.bytes=typeof o.bytes=="number"?o.bytes:Buffer.byteLength(n.content,"utf8")):(p.format=n.format,p.bytes=Buffer.byteLength(n.content,"utf8"));try{await Xo(a,p)}catch(u){l.indexWarning=u.message}return JSON.stringify(l)}case"artifact_update":{if(ct>=$t)return Ln("Publish budget already spent this turn.",[]);let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let n=Qo(e);if(n?.error)return JSON.stringify({error:n.error});let s=typeof e?.title=="string"?e.title.trim():"",i=typeof e?.description=="string"&&e.description.trim();if(!n&&!s&&!i)return JSON.stringify({error:"nothing to update \u2014 pass a new title, description, and/or markdown|html"});let o=ea(e,n);if(o?.error)return JSON.stringify({error:o.error});let a={id:t};s&&(a.title=s),n&&(a[n.format]=n.content),typeof e?.kind=="string"&&e.kind.trim()&&(a.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(a.favicon=e.favicon.trim()),i&&(a.description=e.description);let c=await Yo(a,n?.format,o?.preflight);if(c?.__rejected)return c.payload;let l=c?.url;if(!l)return JSON.stringify({error:"artifact update returned no url",response:c});let d={id:t,url:l};if(typeof c.rn=="string"&&c.rn&&(d.rn=c.rn),c.__preflightNote&&(d.preflight=c.__preflightNote),n){let m=await Vo(t,n.content);m&&(d.readBack=m)}let p=await Sf(t)||{},u={...p,id:t,url:l,title:s||p.title||"Untitled",kind:a.kind||p.kind||null,createdAt:p.createdAt||c.createdAt||new Date().toISOString(),updatedAt:c.updatedAt||new Date().toISOString()};n&&(n.format==="text"?(u.contentType=typeof c.contentType=="string"?c.contentType:p.contentType||null,u.bytes=typeof c.bytes=="number"?c.bytes:Buffer.byteLength(n.content,"utf8")):(u.format=n.format,u.bytes=Buffer.byteLength(n.content,"utf8"))),typeof e?.summary=="string"&&e.summary.trim()?u.summary=e.summary.trim():u.summary||(u.summary=u.title);try{await Xo(t,u)}catch(m){d.indexWarning=m.message}return JSON.stringify(d)}case"artifact_get":{let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let n=await na(t);return JSON.stringify(n)}case"artifact_share":{let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let n=await Wo(t,"protect");return JSON.stringify({id:n.id,url:n.url,password:n.password,shared:!0,instruction:"Send BOTH the url and the password to the person who asked. Copy the password EXACTLY \u2014 it is case-sensitive and cannot be recovered later (call artifact_share again to issue a new one)."})}case"artifact_unshare":{let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let n=await Wo(t,"unprotect");return JSON.stringify({id:n.id,shared:!1,wasShared:n.wasShared})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"artifact_publish",description:`Publish a NEW self-contained, shareable page (report/plan/table/dashboard/diagram/write-up) and get back a shareable URL. USE \`markdown\` \u2014 it is the default path and Zibby generates the entire document for you (doctype, head, CSS, dark mode, table styling); you supply only the content, so the page cannot come out malformed. Markdown supports ${at}; it does NOT support ${Rr}. Use \`html\` ONLY when the page needs a visual layout Markdown cannot express (a bar chart, a gauge, a custom grid, an SVG diagram) \u2014 on that path you author the whole document and every mistake ships verbatim. Never pass both. Use \`text\` (+ required \`contentType\`) to publish RAW SOURCE as-is \u2014 code, a script, logs, JSON data, CSV. It is stored verbatim, never rendered as a page, and shown in a read-only code viewer with a download link. contentType: text/plain for code/logs/scripts, application/json for JSON data, text/csv for CSV. For code, put the FILENAME in \`title\` (e.g. "deploy.sh") \u2014 viewers derive the language label from the extension \u2014 and set kind: "code". Exactly one of markdown|html|text per call. Every figure on the page must come from a tool result or this conversation \u2014 do not do arithmetic in prose and print the result, and use the same number everywhere it appears. The content MUST come from the current conversation or data you fetched this turn; if you are not sure what the page should be about, ASK instead of calling this tool, and never publish a demo/sample/placeholder or an account-overview page as a stand-in. On the html path keep all CSS/JS/images INLINE (inline <style>/<script>, data: URIs) and send real tags (never <escaped> markup) \u2014 the page is sandboxed on view with no network at all, so every external URL is dead. PASS \`data\` WHENEVER THE HTML PAGE RENDERS A DATASET \u2014 a table of records, a bar chart, a row of meters. Give it the raw tool results the page was built from, unchanged; the page is then checked AGAINST that data before anything is sent, catching a table short of rows, a bar drawn at the wrong length, and leftover \${\u2026} or [object Object]. It costs you nothing when the page is right. Skip it for prose pages, and never pass it with \`markdown\` (that is an error, not a no-op). The content is VALIDATED before any URL exists: if it is broken \u2014 by that data check or by the server \u2014 you get the exact defects and line numbers back, you get ONE retry, and then the tool stops you. Both kinds of rejection share the SAME two attempts. Returns { id, url }. PASS \`share: true\` WHEN THE READERS HAVE NO ZIBBY ACCOUNT \u2014 you get back { shareUrl, password } in this same call, instead of publishing a link they cannot open and then having to call artifact_share. The password is GENERATED; you never invent one. Without \`share\` the page is member-only, which is the default and is correct for anything internal.`,input_schema:{type:"object",properties:{title:{type:"string",description:`The page title (also the browser tab title). ${Ko}`},markdown:{type:"string",description:`PREFERRED. The page content as Markdown \u2014 Zibby renders it into a styled, self-contained document, so you never author a skeleton. Supports ${at}. Does NOT support ${Rr}. Provide this OR html, never both.`},html:{type:"string",description:"The EXCEPTION path \u2014 only for a layout Markdown cannot express (bar chart, gauge, custom grid, SVG diagram). A self-contained HTML document or fragment, served VERBATIM: you own the doctype, head, CSS and every tag. All assets must be inline (<style>/<script>, data: URIs). Provide this OR markdown, never both."},text:{type:"string",description:'RAW SOURCE published as-is \u2014 code, a script, logs, JSON data, CSV. Stored verbatim (never rendered as an HTML page) and shown in a read-only code viewer with a download link. Requires `contentType`. For code, make `title` the filename (e.g. "deploy.sh" \u2014 the viewer derives the language from the extension) and set kind: "code". Provide this OR markdown OR html.'},contentType:{type:"string",description:"REQUIRED with `text`, meaningless otherwise. One of: text/plain (code, scripts, logs), application/json (JSON data), text/csv (CSV). Nothing else is accepted \u2014 HTML and Markdown are published through their own fields, never as text."},data:{type:"object",description:'Optional, and worth passing WHENEVER the html page renders a dataset (a table of records, a bar chart, meters): the raw tool results the page was built from, as JSON, UNCHANGED \u2014 do not summarise it and do not write your own expectations, the check derives what must be true by itself (wrap a bare array as {"rows": [...]}). The page is then verified against it BEFORE publishing: row counts, bar lengths vs their values, bars whose width the CSS throws away, and placeholder residue. If they disagree nothing is sent and you get the defects back, using one of your two attempts. Only valid with `html` \u2014 passing it with `markdown` is an error.'},kind:{type:"string",description:'Optional label for what this is, e.g. "report", "plan", "dashboard", "diagram". Stored in your index.'},favicon:{type:"string",description:'Optional emoji used as the browser-tab icon, e.g. "\u{1F4CA}".'},summary:{type:"string",description:"Optional one-line summary for your own index (defaults to the title). Helps you recall later what this page was."},description:{type:"string",description:`Optional. ${Fo} This is the artifact's caption, NOT its content: the page/file itself is the content, and a reader who opens it should be able to understand what they are looking at without asking you. Write it as a short report with headings, bullets and tables (same Markdown subset as the \`markdown\` field, 16 KB max).`},share:{type:"boolean",description:"Set true to publish the page WITH a password link in one step \u2014 the response then also carries { shareUrl, password }, which you send together. Use it whenever the people who asked are in a chat channel and have no Zibby account. Omit it (the default) for anything internal: the page is then readable only by logged-in members of this project, and no password exists."}},required:["title"]}},{name:"artifact_update",description:"Revise an EXISTING artifact by id \u2014 the shareable URL stays the same, the content is replaced (new version). Pass the fields to change (title and/or markdown|html|text). `text` only replaces an artifact that was PUBLISHED as text, and it keeps its original contentType \u2014 the server refuses a type change and any doc\u2194text conversion. Prefer `markdown` for the same reason artifact_publish does: Zibby generates the document, so it cannot come out malformed. An update is validated exactly like a publish \u2014 including the optional `data` check when you send new `html` that renders a dataset \u2014 and if the new content is broken it is REFUSED, the page keeps its last good version, and the rejection shares the same two attempts as publish. Returns { id, url }.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to update (from a prior artifact_publish, or your kv-memory "artifact:" index).'},title:{type:"string",description:"New title (optional)."},markdown:{type:"string",description:`PREFERRED. New Markdown content (optional) \u2014 Zibby renders the document skeleton. Supports ${at}. Provide this OR html.`},html:{type:"string",description:"New HTML content (optional), served verbatim \u2014 only for layouts Markdown cannot express. Provide this OR markdown."},text:{type:"string",description:"New raw text content (optional) \u2014 only for an artifact that was PUBLISHED as text. It keeps its original contentType; the server refuses a type change or a doc\u2194text conversion. Provide at most one of markdown|html|text."},data:{type:"object",description:"Optional \u2014 same as on artifact_publish: when the new `html` renders a dataset, pass the raw tool results it was built from and the page is checked against them before anything is sent. Only valid alongside new `html`."},kind:{type:"string",description:"Optional updated kind label."},favicon:{type:"string",description:"Optional updated emoji favicon."},summary:{type:"string",description:"Optional updated one-line index summary."},description:{type:"string",description:"Optional updated Markdown note shown under the artifact on its detail page. You may pass this ALONE to add or rewrite the explanation without touching the artifact itself \u2014 the content keeps its current version."}},required:["id"]}},{name:"artifact_get",description:'Fetch ONE artifact you published, by id \u2192 { metadata, content }. Use to reuse / edit / re-publish a page. To LIST what you have published, use your kv-memory tool kv_recall_prefix with keyPrefix "artifact:".',input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id."}},required:["id"]}},{name:"artifact_share",description:"Make an artifact viewable WITHOUT a Zibby login, by password. Returns { url, password } \u2014 a link anyone can open plus the password that opens it. USE THIS when the people who need to read the page do not have Zibby accounts \u2014 the usual case is a Lark or Slack channel where you were asked for something and the channel members are not Zibby users. The normal artifact url only opens for logged-in members of this project, so for those recipients it is a dead link; this is what makes it readable. You MUST then send BOTH the url and the password in your reply, and copy the password EXACTLY (it is case-sensitive). It is shown ONCE and cannot be looked up afterwards \u2014 if it is lost, call this again to issue a new one, which also stops the old one working. Works on any artifact you published, old or new. Calling it again on an already-shared artifact replaces the password. Use artifact_unshare to revoke.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to share (from artifact_publish, or your kv-memory "artifact:" index).'}},required:["id"]}},{name:"artifact_unshare",description:`REMOVE an artifact's password \u2014 this is the tool for "take the password off", "remove the password", "stop sharing" and "revoke the link", which are all the same act. The page goes back to the DEFAULT it was published with: viewable only by logged-in members of this project, with no password anywhere. Immediate and total: anyone who already entered the password loses access too, not just new visitors. Safe to call on an artifact that was never shared. Note what this does NOT do: there is no way to leave a page open to anyone with the link and no password. Removing the password closes the anonymous door; it does not prop it open. Say that plainly if you are asked for a passwordless public link.`,input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id to stop sharing."}},required:["id"]}}]};import{createRequire as vf}from"node:module";import{randomBytes as If}from"node:crypto";import{existsSync as la,mkdirSync as Tf,writeFileSync as ia}from"node:fs";import{dirname as da,join as lt,resolve as pa}from"node:path";import{fileURLToPath as ua}from"node:url";var ma=vf(import.meta.url),$n=null;function Nf(){return $n||($n=ma("echarts")),$n}var jn=null;function Of(){return jn||(jn=ma("@resvg/resvg-js")),jn}var Af=800,Rf=600,Ef=4096,xf=16,oa=60,ha="Noto Sans",aa=256*1024;function Lf(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=da(ua(import.meta.url)),e=pa(r,"..","bin","mcp-skill.mjs");return la(e)?e:null}function $f(){let r=da(ua(import.meta.url)),e=pa(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>lt(e,t)).filter(t=>la(t))}function jf(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?lt(e,"chart-render"):lt(process.cwd(),".zibby","output","charts"));return Tf(t,{recursive:!0}),t}function Ke(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function ca(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(xf,Math.min(Ef,Math.round(t))):e}function Pn(r){return typeof r!="string"||r.length<=oa?r:`${r.slice(0,oa-1)}\u2026`}function Er(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=Pn(t):Ke(t)&&typeof t.name=="string"&&(t.name=Pn(t.name))}}function Pf(r){for(let n of["xAxis","yAxis"]){let s=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let i of s)Ke(i)&&Er(i.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of e)Ke(n)&&Er(n.indicator);Ke(r.legend)&&Er(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=Pn(n.name)),Er(n.data))}function Cf(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=ha),Pf(e),e}function Uf(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Bf(r,e,t){let s=Nf().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return s.setOption(r),s.renderToSVGString()}finally{s.dispose()}}function Df(r){return r.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"")}function Mf(r,e){return r.replace(/id="zr\d+-/g,`id="${e}-`).replace(/url\(#zr\d+-/g,`url(#${e}-`).replace(/class="zr\d+-/g,`class="${e}-`)}function Jf(r){let e=[];for(let t of r.matchAll(/(?:xlink:)?href\s*=\s*"([^"]*)"/gi)){let n=t[1].trim();n&&!n.startsWith("#")&&!/^data:/i.test(n)&&e.push(n)}for(let t of r.matchAll(/url\(\s*['"]?([^'")]*)['"]?\s*\)/gi)){let n=t[1].trim();n&&!n.startsWith("#")&&!/^data:/i.test(n)&&e.push(n)}return/@import/i.test(r)&&e.push("@import"),/<script\b/i.test(r)&&e.push("<script>"),/<foreignObject\b/i.test(r)&&e.push("<foreignObject>"),e}function qf(r){let e=Mf(Df(r),`chart-${If(4).toString("hex")}`),t=Jf(e);if(t.length){let n=[...new Set(t)].slice(0,3).join(", ");throw new Error(`the rendered chart references external resources (${n}), which a self-contained HTML page blocks. Remove image:// symbols / external image fills from the spec (use plain colors or a data: URI), or use output:'svg' to write a file instead.`)}return e}function Gf(r){let{Resvg:e}=Of();return new e(r,{font:{fontFiles:$f(),loadSystemFonts:!0,defaultFontFamily:ha}}).render().asPng()}var fa={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)
|
|
926
924
|
You can render charts LOCALLY with the chart_render tool \u2014 pass a standard
|
|
927
925
|
Apache ECharts option object as \`spec\` (any chart type: bar, line, pie,
|
|
928
926
|
radar, scatter, heatmap, \u2026). No browser, no external chart service \u2014 the data
|
|
@@ -937,7 +935,7 @@ Pick the destination with \`output\`:
|
|
|
937
935
|
compute the geometry from the data so the bars cannot come out wrong.
|
|
938
936
|
- **Attaching a chart to the run \u2192 \`output:'png'\` (default), \`'svg'\` or
|
|
939
937
|
\`'both'\`.** Writes files to the run's output folder (auto-uploaded as run
|
|
940
|
-
artifacts) and returns the paths. Default 800\xD7600.`,resolve({sessionPath:r,nodeName:
|
|
938
|
+
artifacts) and returns the paths. Default 800\xD7600.`,resolve({sessionPath:r,nodeName:e}={}){let t=Lf();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},s=r&&e?lt(r,e):null;s&&(n.ZIBBY_NODE_SESSION_PATH=s),r&&(n.ZIBBY_SESSION_PATH=r);for(let i of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[i]&&process.env[i]&&(n[i]=process.env[i]);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=ca(e?.width,Af),s=ca(e?.height,Rf),i=["svg","png","both","svg-inline"].includes(e?.output)?e.output:"png",o=Uf(e?.filename)||`chart-${Date.now()}`,a;try{a=Bf(Cf(t),n,s)}catch(d){return JSON.stringify({error:`Chart render failed: ${d.message}. The spec must be a valid Apache ECharts option (check series[].type, and that xAxis/yAxis/radar match the series type). Fix the spec and retry.`})}if(typeof a!="string"||!a.includes("<svg"))return JSON.stringify({error:"Chart render produced no SVG \u2014 the spec likely describes an empty chart (no series?). Add at least one series and retry."});if(i==="svg-inline"){let d;try{d=qf(a)}catch(u){return JSON.stringify({error:`Chart cannot be inlined: ${u.message}`})}let p=Buffer.byteLength(d,"utf-8");return p>aa?JSON.stringify({error:`Rendered SVG is ${Math.round(p/1024)}KB, over the ${Math.round(aa/1024)}KB inline limit. Inline SVG is returned through the conversation and pasted into the page, so it must stay small. Aggregate or sample the data down (a readable chart rarely needs >1000 points), or use output:'svg' to write a file instead.`}):JSON.stringify({ok:!0,width:n,height:s,svg:d,bytes:p,files:[]})}let c=jf(),l=[];if(i==="svg"||i==="both"){let d=lt(c,`${o}.svg`);ia(d,a,"utf-8"),l.push({path:d,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}if(i==="png"||i==="both"){let d;try{d=Gf(a)}catch(u){return JSON.stringify({error:`PNG rasterization failed: ${u.message}. Retry with output:'svg' if you only need the vector.`})}let p=lt(c,`${o}.png`);ia(p,d),l.push({path:p,format:"png",bytes:d.length})}return JSON.stringify({ok:!0,width:n,height:s,files:l})}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. Pass the raw ECharts option as \`spec\` \u2014 every ECharts chart type works (bar, line, pie, radar, scatter, heatmap, \u2026). USE output:'svg-inline' WHEN BUILDING AN HTML PAGE, ARTIFACT OR REPORT: it returns the chart as an \`svg\` string (self-contained, no external refs) to paste directly into your HTML \u2014 a published page blocks external hosts, so a file path will not render there, and hand-written bar markup is never needed because ECharts computes the geometry. Otherwise output 'png' (default) / 'svg' / 'both' writes files to the run output folder and returns their paths. animation is forced off; background defaults to white. Bar example: {"xAxis":{"type":"category","data":["Q1","Q2"]},"yAxis":{},"series":[{"type":"bar","data":[12,30]}]}. Radar example: {"legend":{"data":["A","B"]},"radar":{"indicator":[{"name":"speed","max":10},{"name":"cost","max":10},{"name":"quality","max":10}]},"series":[{"type":"radar","data":[{"name":"A","value":[7,4,9]},{"name":"B","value":[5,8,6]}]}]}.`,input_schema:{type:"object",properties:{spec:{type:"object",description:"The Apache ECharts option object, passed through as-is (series, xAxis/yAxis, radar, legend, title, \u2026)."},width:{type:"number",description:"Image width in px (default 800, max 4096)."},height:{type:"number",description:"Image height in px (default 600, max 4096)."},output:{type:"string",enum:["svg","png","both","svg-inline"],description:"Destination. 'svg-inline' writes NO file and returns the SVG markup in the result for pasting into an HTML page/artifact \u2014 use this whenever you are building HTML. 'png' (default) / 'svg' / 'both' write files to the run output folder and return their paths."},filename:{type:"string",description:"Optional file basename (no extension); defaults to chart-<timestamp>."}},required:["spec"]}}]};import{existsSync as Kf}from"fs";import{fileURLToPath as Ff}from"url";import{dirname as Hf,resolve as zf}from"path";function Yf(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Hf(Ff(import.meta.url)),e=zf(r,"..","bin","mcp-skill.mjs");return Kf(e)?e:null}var Wf=[{name:"trivial",max:5},{name:"small",max:30},{name:"medium",max:150},{name:"large",max:600},{name:"huge",max:1/0}];function Zf(r,e){let t=(Number(r)||0)+(Number(e)||0);for(let n of Wf)if(t<=n.max)return n.name;return"huge"}function Vf(r){let t=String(r||"").toLowerCase().split("/").pop()||"",n=t.match(/\.(test|spec)\.[a-z0-9]+$/);if(n)return`.${n[1]}`;let s=t.lastIndexOf(".");return s<=0?/^(dockerfile|makefile|jenkinsfile|procfile|gemfile|rakefile)$/i.test(t)?t.toLowerCase():"":t.slice(s)}var Xf={code:[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".rb",".php",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".scala",".m",".dart",".ex",".exs",".clj",".sh",".bash"],test:[".test",".spec"],docs:[".md",".mdx",".rst",".txt",".adoc"],config:[".json",".yml",".yaml",".toml",".ini",".env",".cfg",".conf",".lock",".xml",".properties","dockerfile","makefile","jenkinsfile","procfile",".tf",".gradle"],style:[".css",".scss",".sass",".less",".styl"],data:[".csv",".tsv",".sql",".parquet",".proto",".graphql",".gql"]},Qf=(()=>{let r={};for(let[e,t]of Object.entries(Xf))for(let n of t)r[n]=e;return r})();function ey(r){return Qf[String(r||"").toLowerCase()]||"other"}function ty(r,e={}){let t=Array.isArray(r)?r:[],n=[],s={},i={code:0,test:0,docs:0,config:0,style:0,data:0,other:0},o=0,a=0,c={path:"",changed:-1};for(let m of t){if(!m||typeof m!="object")continue;let h=String(m.path||m.newPath||m.filename||m.new_path||"").trim();if(!h)continue;n.push(h);let y=Number(m.additions??m.add??0)||0,_=Number(m.deletions??m.del??0)||0;o+=y,a+=_;let f=Vf(h);s[f||"(none)"]=(s[f||"(none)"]||0)+1,i[ey(f)]+=1;let b=y+_;b>c.changed&&(c={path:h,changed:b})}let l=Number(e.additions),d=Number(e.deletions),p=Number.isFinite(l)?l:o,u=Number.isFinite(d)?d:a;return{filesChanged:n.length,filePaths:n,extCounts:s,kindCounts:i,additions:p,deletions:u,sizeBucket:Zf(p,u),largestFile:c.path||null,dirs:[...new Set(n.map(m=>m.includes("/")?m.split("/")[0]:"(root)"))].sort()}}function ry(r){let e="",t=String(r||"");for(let n=0;n<t.length;n++){let s=t[n];s==="*"?t[n+1]==="*"?(e+=".*",n++,t[n+1]==="/"&&n++):e+="[^/]*":s==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(s)?e+=`\\${s}`:e+=s}return new RegExp(`^${e}$`)}function ny(r,e){let t=Array.isArray(r)?r.map(String):[],n=(Array.isArray(e)?e:[]).filter(Boolean).map(ry);if(!n.length)return{total:t.length,hits:0,ratio:0,matched:[]};let s=t.filter(i=>n.some(o=>o.test(i)));return{total:t.length,hits:s.length,ratio:t.length?Number((s.length/t.length).toFixed(4)):0,matched:s}}function sy(r,e){let t=(Array.isArray(r)?r:[]).map(Number).filter(i=>Number.isFinite(i)),n=Number(e);if(!t.length||!Number.isFinite(n))return null;let s=t.filter(i=>i<=n).length;return Number((s/t.length*100).toFixed(1))}var ya={id:"code-stats",serverName:"code_stats",allowedTools:["mcp__code_stats__*"],description:"Deterministic code statistics \u2014 pure, reproducible facts from changed-file lists + numbers (extension/work-kind mix, size bucket, core-path glob coverage, percentile rank). Zero LLM, zero network.",promptFragment:`## Code Stats (DETERMINISTIC facts \u2014 pure, reproducible, zero-LLM)
|
|
941
939
|
These tools COMPUTE reproducible facts from data you already have. Use them so
|
|
942
940
|
your numbers are auditable and survive challenge (same input \u2192 same output).
|
|
943
941
|
|
|
@@ -955,7 +953,7 @@ Tools:
|
|
|
955
953
|
reproducible "works in the core vs the edges" number.
|
|
956
954
|
- code_stats_percentile: Given \`values\` (a cohort's numbers) + a \`value\`,
|
|
957
955
|
returns the 0-100 percentile rank. Use to express every metric as a rank
|
|
958
|
-
within the team (reproducible + comparable across teams), not a raw number.`,resolve(){let r=
|
|
956
|
+
within the team (reproducible + comparable across teams), not a raw number.`,resolve(){let r=Yf();return r?{type:"stdio",command:"node",args:[r,"../dist/codeStats.js","codeStatsSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,e){try{switch(r){case"code_stats_commit_facts":return JSON.stringify(ty(e?.files,{additions:e?.additions,deletions:e?.deletions}));case"code_stats_glob_hit":return JSON.stringify(ny(e?.paths,e?.globs));case"code_stats_percentile":return JSON.stringify({percentile:sy(e?.values,e?.value)});default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"code_stats_commit_facts",description:"Deterministic per-commit facts from its changed-file list. Pass files: [{path, additions, deletions}] (gitlab_get_commit / github_get_commit shape). Returns filePaths, extCounts, kindCounts (code/test/docs/config/style/data/other), additions, deletions, sizeBucket (trivial/small/medium/large/huge), largestFile, dirs. Pure \u2014 same input always same output.",input_schema:{type:"object",properties:{files:{type:"array",description:"Changed files. Each { path (or newPath/filename), additions?, deletions? }.",items:{type:"object",properties:{path:{type:"string"},additions:{type:"number"},deletions:{type:"number"}}}},additions:{type:"number",description:"Optional commit-level total additions override (else summed from files)."},deletions:{type:"number",description:"Optional commit-level total deletions override."}},required:["files"]}},{name:"code_stats_glob_hit",description:"How many of paths match ANY of globs (supports **, *, ?). Returns { total, hits, ratio, matched }. Use for reproducible core-path coverage against the caller's own core globs.",input_schema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"File paths to test."},globs:{type:"array",items:{type:"string"},description:'Glob patterns, e.g. ["src/payment/**", "auth/**"].'}},required:["paths","globs"]}},{name:"code_stats_percentile",description:'The 0-100 percentile rank of value within values (cumulative "% at or below"). Reproducible + cross-team comparable. Empty cohort \u2192 null.',input_schema:{type:"object",properties:{values:{type:"array",items:{type:"number"},description:"The cohort's numbers."},value:{type:"number",description:"The value to rank."}},required:["values","value"]}}]};import{existsSync as iy}from"fs";import{fileURLToPath as oy}from"url";import{dirname as ay,resolve as cy}from"path";function ly(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ay(oy(import.meta.url)),e=cy(r,"..","bin","mcp-skill.mjs");return iy(e)?e:null}function dy(r={}){let e=String(r.provider||process.env.ZIBBY_PROGRESS_PROVIDER||(process.env.LARK_RECEIVE_ID?"lark":process.env.SLACK_CHANNEL||process.env.SLACK_BOT_TOKEN?"slack":"")).toLowerCase(),t=String(r.chatId||r.channel||process.env.ZIBBY_PROGRESS_CHAT_ID||(e==="lark"?process.env.LARK_RECEIVE_ID:process.env.SLACK_CHANNEL)||"").trim(),n=String(r.mention||process.env.ZIBBY_PROGRESS_MENTION||"").trim();return{provider:e,chatId:t,mention:n}}var ga={id:"chat-progress",serverName:"chat_progress",allowedTools:["mcp__chat_progress__*"],envKeys:[...U.envKeys||[],...F.envKeys||[],"ZIBBY_PROGRESS_PROVIDER","ZIBBY_PROGRESS_CHAT_ID","ZIBBY_PROGRESS_MENTION","SLACK_CHANNEL","LARK_RECEIVE_ID"],description:"Report progress back to the triggering chat during a long-running job \u2014 a one-line status the human sees while the work runs. General + reusable; fire-and-forget.",promptFragment:`## Chat Progress (tell the human you're still working \u2014 long jobs only)
|
|
959
957
|
When a run is LONG (many API pages, a shard-capped backfill, dozens of scored
|
|
960
958
|
items), the human who triggered it can't see the middle \u2014 only the final
|
|
961
959
|
notify. Post brief milestones so they know it's alive:
|
|
@@ -965,11 +963,11 @@ notify. Post brief milestones so they know it's alive:
|
|
|
965
963
|
commits, continuing\u2026"). Pass the chat target from your \`notify\` input when
|
|
966
964
|
you have it (provider + chatId); otherwise it resolves from the runtime.
|
|
967
965
|
Fire-and-forget \u2014 if it can't post, just keep working; never treat a failed
|
|
968
|
-
progress ping as an error.`,resolve(){let r=
|
|
969
|
-
`),height:a}}function
|
|
970
|
-
${
|
|
966
|
+
progress ping as an error.`,resolve(){let r=ly();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","SLACK_BOT_TOKEN","SLACK_TEAM_ID","ZIBBY_PROGRESS_PROVIDER","ZIBBY_PROGRESS_CHAT_ID","ZIBBY_PROGRESS_MENTION","SLACK_CHANNEL","LARK_RECEIVE_ID"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/chatProgress.js","chatProgressSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="report_progress")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=String(e?.message||"").trim().slice(0,2e3);if(!t)return JSON.stringify({ok:!1,skipped:"empty message"});let{provider:n,chatId:s,mention:i}=dy(e);if(!n||!s)return JSON.stringify({ok:!1,skipped:"no chat target"});let o=i&&n==="slack"?`<@${i}> ${t}`:t,a;n==="lark"?a=await F.handleToolCall("lark_send_message",{receive_id:s,text:t}):a=await U.handleToolCall("slack_post_message",{channel:s,text:o});let c=null;try{c=JSON.parse(a)}catch{}return c&&c.error?JSON.stringify({ok:!1,skipped:`post failed: ${c.error}`}):JSON.stringify({ok:!0,provider:n,posted:!0})}catch(t){return JSON.stringify({ok:!1,skipped:`error: ${t.message}`})}},tools:[{name:"report_progress",description:"Post a ONE-LINE progress status to the chat that triggered this run (so the human sees the long job is alive). Fire-and-forget \u2014 never fails the run. Target resolves from your notify input (provider + chatId) or the runtime; you usually just pass the message.",input_schema:{type:"object",properties:{message:{type:"string",description:'A short human status line, e.g. "Scored 60/188 commits, continuing\u2026".'},provider:{type:"string",enum:["lark","slack"],description:"Optional \u2014 the chat provider (from your notify input). Defaults from the runtime."},chatId:{type:"string",description:"Optional \u2014 the target chat/channel id (from your notify input). Defaults from the runtime."}},required:["message"]}}]};import{createRequire as py}from"node:module";import{existsSync as wa,mkdirSync as uy,writeFileSync as ba}from"node:fs";import{dirname as Sa,join as pt,resolve as va}from"node:path";import{fileURLToPath as Ia}from"node:url";var my=py(import.meta.url),Cn=null;function hy(){return Cn||(Cn=my("@resvg/resvg-js")),Cn}var Ta=1200,fy=627,yy=4096,gy=320,by="#3b82f6",Fe="Noto Sans",_y=3;function ky(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Sa(Ia(import.meta.url)),e=va(r,"..","bin","mcp-skill.mjs");return wa(e)?e:null}function wy(){let r=Sa(Ia(import.meta.url)),e=va(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>pt(e,t)).filter(t=>wa(t))}function Sy(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?pt(e,"social-card"):pt(process.cwd(),".zibby","output","social-cards"));return uy(t,{recursive:!0}),t}function _a(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(gy,Math.min(yy,Math.round(t))):e}function dt(r){return String(r??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function vy(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Iy(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 Na(r,e,t){return String(r).length*e*t}function Un(r,e,t,n){let s=String(r).trim().split(/\s+/).filter(Boolean),i=[],o="";for(let a of s){let c=o?`${o} ${a}`:a;o&&Na(c,t,n)>e?(i.push(o),o=a):o=c}return o&&i.push(o),i.length?i:[""]}function Ty(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 ka(r,e,t,n,s){let i=(Array.isArray(r)?r:[]).map(_=>String(_??"").trim()).filter(Boolean).slice(0,_y);if(i.length<2)return null;let o=24,a=54,c=26,l=90,d=17,p=i.map(_=>Math.max(96,Na(_,o,.58)+c*2)),u=p.reduce((_,f)=>_+f,0)+l*(i.length-1),m=e-u/2,h=t+a/2,y=[];for(let _=0;_<i.length;_++){let f=p[_];if(y.push(`<rect x="${m.toFixed(1)}" y="${t}" width="${f.toFixed(1)}" height="${a}" rx="${a/2}" fill="${s}" fill-opacity="0.12" stroke="${s}" stroke-opacity="0.55" stroke-width="1.5"/>`,`<text x="${(m+f/2).toFixed(1)}" y="${(h+o*.35).toFixed(1)}" text-anchor="middle" font-family="${Fe}" font-size="${o}" font-weight="700" fill="${n.pillText}">${dt(i[_])}</text>`),m+=f,_<i.length-1){let b=m,g=m+l,k=(b+g)/2;y.push(`<line x1="${b.toFixed(1)}" y1="${h}" x2="${g.toFixed(1)}" y2="${h}" stroke="${s}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${k.toFixed(1)}" cy="${h}" r="${d}" fill="${s}"/>`,`<path d="M ${(k-8).toFixed(1)} ${h.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:y.join(`
|
|
967
|
+
`),height:a}}function Ny(r){let{width:e,height:t,theme:n,accent:s}=r,i=Ty(n),o=e/2,a=Math.round(e*.07),c=e-a*2,l=String(r.headline).trim(),d=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",p=r.subhead?String(r.subhead).trim():"",u=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",h=e/Ta,y=Math.round(22*h),_=Math.round(29*h),f=p?Un(p,c,_,.52):[],b=Math.round(_*1.28),g=4,k=Math.round(26*h),v=Math.round(20*h),x=Math.round(24*h),V=Math.round(30*h),R=!!(u||m),A=a,K=R?Math.round(110*h):a,j=t-A-K,Ee=ka(r.diagram,o,0,i,s),Qn=(B,Se)=>{let mt=g+k;return d&&(mt+=y+v),mt+=Se.length*Math.round(B*1.16),f.length&&(mt+=x+f.length*b),Ee&&(mt+=V+Ee.height),mt},Dr=[76,66,58,50,44,38].map(B=>Math.round(B*h)),lc=4,ze=Dr[Dr.length-1],Mr=Un(l,c,ze,.6);for(let B of Dr){let Se=Un(l,c,B,.6);if(Se.length<=lc&&Qn(B,Se)<=j){ze=B,Mr=Se;break}}let dc=Math.round(ze*1.16),pc=Qn(ze,Mr),X=A+Math.max(0,(j-pc)/2),he=[];he.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${i.bg}"/>`);let es=Math.round(60*h);he.push(`<rect x="${(o-es/2).toFixed(1)}" y="${X}" width="${es}" height="${g}" rx="2" fill="${s}"/>`),X+=g+k,d&&(he.push(`<text x="${o}" y="${(X+y*.82).toFixed(1)}" text-anchor="middle" font-family="${Fe}" font-size="${y}" font-weight="700" letter-spacing="3" fill="${s}">${dt(d)}</text>`),X+=y+v);for(let B of Mr)he.push(`<text x="${o}" y="${(X+ze*.82).toFixed(1)}" text-anchor="middle" font-family="${Fe}" font-size="${ze}" font-weight="700" fill="${i.fg}">${dt(B)}</text>`),X+=dc;if(f.length){X+=x;for(let B of f)he.push(`<text x="${o}" y="${(X+_*.82).toFixed(1)}" text-anchor="middle" font-family="${Fe}" font-size="${_}" font-weight="400" fill="${i.muted}">${dt(B)}</text>`),X+=b}if(Ee){X+=V;let B=ka(r.diagram,o,X,i,s);B&&he.push(B.svg)}if(R){let B=Math.round(24*h),Se=t-Math.round(46*h);m&&he.push(`<text x="${a}" y="${Se}" text-anchor="start" font-family="${Fe}" font-size="${B}" font-weight="400" fill="${i.muted}">${dt(m)}</text>`),u&&he.push(`<text x="${e-a}" y="${Se}" text-anchor="end" font-family="${Fe}" font-size="${B}" font-weight="700" fill="${s}">${dt(u)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
|
|
968
|
+
${he.join(`
|
|
971
969
|
`)}
|
|
972
|
-
</svg>`}function
|
|
970
|
+
</svg>`}function Oy(r){let{Resvg:e}=hy();return new e(r,{font:{fontFiles:wy(),loadSystemFonts:!0,defaultFontFamily:Fe}}).render().asPng()}var Oa={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)
|
|
973
971
|
You can render a BRANDED concept card PNG with the social_card_render tool \u2014 the
|
|
974
972
|
clean, high-signal LinkedIn "concept card" style (bold headline + small uppercase
|
|
975
973
|
eyebrow + optional stat/footer + optional A\u2014\u2713\u2014B diagram). Give it STRUCTURED
|
|
@@ -983,15 +981,15 @@ fields that capture the ONE key idea of your post:
|
|
|
983
981
|
It renders server-side to a PNG in the run's output folder and returns
|
|
984
982
|
{ ok:true, files:[{ path, format:'png', bytes }] }. Pass the returned \`path\` as
|
|
985
983
|
\`imagePath\` when you draft/publish a LinkedIn post to ATTACH the card as the
|
|
986
|
-
post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:
|
|
987
|
-
`)){let s=n.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!i||typeof i!="object")continue;let o=i.location||{};
|
|
984
|
+
post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=ky();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},s=r&&e?pt(r,e):null;s&&(n.ZIBBY_NODE_SESSION_PATH=s),r&&(n.ZIBBY_SESSION_PATH=r);for(let i of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[i]&&process.env[i]&&(n[i]=process.env[i]);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=_a(e?.width,Ta),s=_a(e?.height,fy),i=e?.theme==="light"?"light":"dark",o=Iy(e?.accent,by),a;try{a=Ny({width:n,height:s,theme:i,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=Oy(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let l=Sy(),d=vy(e?.filename)||`social-card-${Date.now()}`,p=pt(l,`${d}.png`);ba(p,c);let u=[{path:p,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=pt(l,`${d}.svg`);ba(m,a,"utf-8"),u.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:s,theme:i,files:u})}catch(t){return JSON.stringify({error:`social_card_render failed: ${t.message}`})}},tools:[{name:"social_card_render",description:'Render a BRANDED "concept card" PNG LOCALLY (no external service) from structured fields \u2014 the clean LinkedIn concept-card style: bold headline + small uppercase eyebrow + optional supporting subhead, stat, footer, and an A\u2014\u2713\u2014B diagram. Returns { ok:true, files:[{ path, format:"png", bytes }] }. Pass the returned `path` as `imagePath` to a LinkedIn post tool to attach it as the post image. Example: { "headline":"No more copy-paste between AI tools", "eyebrow":"MY WORKFLOW", "stat":"11.8k stars", "footer":"Apache 2.0", "diagram":["Claude Code","Codex"] }.',input_schema:{type:"object",properties:{headline:{type:"string",description:"REQUIRED. The big, bold line \u2014 the single key idea/takeaway. Word-wrapped + auto-sized."},eyebrow:{type:"string",description:'Small uppercase kicker above the headline (e.g. "MY WORKFLOW", "OPEN SOURCE"). Rendered uppercased in the accent color.'},subhead:{type:"string",description:"One supporting line under the headline (muted)."},stat:{type:"string",description:'Optional stat, shown bottom-right in the accent color (e.g. "11.8k stars", "3x faster").'},footer:{type:"string",description:'Optional footer, shown bottom-left (muted) (e.g. "Apache 2.0", a repo name).'},diagram:{type:"array",items:{type:"string"},description:'Optional 2-3 short labels rendered as a chain of pills joined by a checkmark (A \u2014\u2713\u2014 B), e.g. ["Claude Code","Codex"].'},theme:{type:"string",enum:["dark","light"],description:"Card theme (default 'dark' \u2014 near-black bg, off-white text)."},accent:{type:"string",description:'Accent hex color (e.g. "#f97316"). Defaults to a tasteful blue (#3b82f6).'},width:{type:"number",description:"Image width in px (default 1200 \u2014 LinkedIn 1.91:1 link image)."},height:{type:"number",description:"Image height in px (default 627)."},filename:{type:"string",description:"Optional file basename (no extension); defaults to social-card-<timestamp>."},output:{type:"string",enum:["png","both"],description:"Which file(s) to write (default 'png'; 'both' also writes the .svg)."}},required:["headline"]}}]};import{spawnSync as Ay}from"node:child_process";import{existsSync as G,readdirSync as Ea,statSync as xa,writeFileSync as Dn,mkdirSync as Mn}from"node:fs";import{dirname as Bn,extname as jr,join as D,relative as Ry,resolve as $r}from"node:path";import{tmpdir as Jn}from"node:os";import{fileURLToPath as Ey}from"node:url";import{SKILL_META as xy}from"@zibby/skill-ids";import{binPath as Ly}from"@zibby/bin-oxlint";import{binPath as $y}from"@zibby/bin-semgrep";function jy(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=Ly();if(r&&G(r))return r}catch{}return"oxlint"}function Py(){if(process.env.SEMGREP_CORE_BIN)return process.env.SEMGREP_CORE_BIN;try{let r=$y();if(r&&G(r))return r}catch{}return"semgrep-core"}function Cy(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Bn(Ey(import.meta.url)),e=$r(r,"..","bin","mcp-skill.mjs");return G(e)?e:null}var La=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),Uy=400,By={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"}},Dy=[".oxlintrc.json",".oxlintrc","oxlint.json"],xr=null;function My(){if(xr&&G(xr))return xr;try{let r=D(Jn(),"zibby-code-scan");Mn(r,{recursive:!0});let e=D(r,"oxlintrc.curated.json");return Dn(e,JSON.stringify(By),"utf-8"),xr=e,e}catch{return null}}var $a={".java":"java",".py":"python",".go":"go",".rb":"ruby",".php":"php"},Aa=Object.keys($a),ja={rules:[{id:"zibby-java-command-injection",languages:["java"],severity:"ERROR",message:"Command execution (Runtime.exec / ProcessBuilder) \u2014 command injection risk if the argument is attacker-influenced. Validate/allow-list the input or avoid a shell.",patterns:[{"pattern-either":[{pattern:"Runtime.getRuntime().exec(...)"},{pattern:"new ProcessBuilder(...)"}]}]},{id:"zibby-python-subprocess-shell",languages:["python"],severity:"ERROR",message:"subprocess call with shell=True \u2014 command injection risk. Pass an argv list and shell=False.",pattern:"subprocess.$F(..., shell=True, ...)"},{id:"zibby-python-yaml-load",languages:["python"],severity:"WARNING",message:"yaml.load without a safe loader can instantiate arbitrary Python objects. Use yaml.safe_load.",pattern:"yaml.load(...)"},{id:"zibby-go-command-injection",languages:["go"],severity:"WARNING",message:"os/exec with a non-constant command \u2014 verify the value is not attacker-controlled (command injection).",pattern:"exec.Command($CMD, ...)"},{id:"zibby-ruby-command-injection",languages:["ruby"],severity:"ERROR",message:"Shell/eval execution (system / eval) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...)"},{pattern:"eval(...)"}]}]},{id:"zibby-php-command-injection",languages:["php"],severity:"ERROR",message:"Shell/eval execution (system / exec / shell_exec) \u2014 command injection risk if the argument is attacker-influenced.",patterns:[{"pattern-either":[{pattern:"system(...);"},{pattern:"exec(...);"},{pattern:"shell_exec(...);"}]}]}]},Jy=[".semgrep.yml",".semgrep.yaml","semgrep.yml","semgrep.yaml"],Lr=null;function qy(){if(Lr&&G(Lr))return Lr;try{let r=D(Jn(),"zibby-code-scan");Mn(r,{recursive:!0});let e=D(r,"semgrep.curated.rules.json");return Dn(e,JSON.stringify(ja),"utf-8"),Lr=e,e}catch{return null}}function Gy(r){return Jy.map(t=>D(r,t)).find(t=>G(t))||qy()}function Ky(r){let e=[];for(let t of Array.isArray(r)?r:[]){if(typeof t!="string"||!t)continue;let n=$a[jr(t).toLowerCase()];if(!n)continue;let s=t.replace(/\\/g,"/");e.push(["CodeTarget",{path:{fpath:s,ppath:`/${s.replace(/^\/+/,"")}`},analyzer:n,products:["sast"]}])}return["Targets",e]}var Fy=0;function Hy(r){let e=Ky(r),t=e[1].length,n=D(Jn(),"zibby-code-scan");Mn(n,{recursive:!0});let s=D(n,`semgrep.targets.${process.pid}.${Fy++}.json`);return Dn(s,JSON.stringify(e),"utf-8"),{path:s,count:t}}function Ra(r){let e=typeof r=="string"?r.toUpperCase():"";return e==="ERROR"?"error":e==="INFO"||e==="INVENTORY"||e==="EXPERIMENT"?"info":"warning"}var zy=Object.fromEntries(ja.rules.map(r=>[r.id,r.severity]));function Yy(r,e){if(e)return Ra(e);let t=zy[r];return t?Ra(t):"warning"}function Wy(r){let e=String(r||""),t=e.indexOf("{");if(t<0)return[];let n;try{n=JSON.parse(e.slice(t))}catch{return[]}return(n&&Array.isArray(n.results)?n.results:[]).map(i=>{if(!i||typeof i!="object")return null;let o=i.start&&typeof i.start=="object"?i.start:{},a=i.extra&&typeof i.extra=="object"?i.extra:{};return{file:i.path||"",line:Number.isFinite(o.line)?o.line:"",severity:Yy(i.check_id,a.severity),rule:i.check_id||"",message:(a.message||"").trim()}}).filter(i=>i&&(i.file||i.message))}function Zy(r,e,t=4e3){let n=new Set(e.map(o=>o.toLowerCase())),s=[r],i=0;for(;s.length;){let o=s.pop(),a;try{a=Ea(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(++i>t)return!1;if(c.isDirectory())!La.has(c.name)&&!c.name.startsWith(".")&&s.push(D(o,c.name));else if(c.isFile()&&n.has(jr(c.name).toLowerCase()))return!0}}return!1}function Vy(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(s=>{if(!s||typeof s!="object")return null;let i=Array.isArray(s.labels)&&s.labels.length?s.labels[0]:null,o=i&&i.span?i.span:null;return{file:s.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""}}).filter(s=>s&&(s.file||s.message))}function Xy(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 Qy(r){let e=String(r||"").trim();if(!e)return[];let t=[];for(let n of e.split(`
|
|
985
|
+
`)){let s=n.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!i||typeof i!="object")continue;let o=i.location||{};t.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:i.severity||"warning",rule:i.code||"",message:i.message||""})}return t.filter(n=>n.file||n.message)}var eg=[{id:"oxlint",detect:r=>G(D(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>jy(),args:(r,e={})=>{let t=e.baseDir||".",s=Dy.some(o=>G(D(t,o)))?null:My();return["--format","json",...s?["--config",s]:[],...r]},parse:Vy},{id:"semgrep",detect:r=>Zy(r,Aa),langs:Aa,bin:()=>Py(),args:(r,e={})=>{let t=e.baseDir||".",n=Gy(t),{path:s}=Hy(r);return[...n?["-rules",n]:[],"-targets",s,"-json"]},parse:Wy},{id:"ruff",detect:r=>G(D(r,"pyproject.toml"))||G(D(r,"requirements.txt"))||G(D(r,"setup.py")),langs:[".py"],bin:()=>process.env.RUFF_BIN||"ruff",args:r=>["check","--output-format","json",...r],parse:Xy},{id:"staticcheck",detect:r=>G(D(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:Qy}];function tg(r,e,t){let n=[],s=new Set(e.map(o=>o.toLowerCase())),i=[r];for(;i.length&&n.length<t;){let o=i.pop(),a;try{a=Ea(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(n.length>=t)break;c.isDirectory()?!La.has(c.name)&&!c.name.startsWith(".")&&i.push(D(o,c.name)):c.isFile()&&s.has(jr(c.name).toLowerCase())&&n.push(D(o,c.name))}}return n}function rg(r,e,t){let n=t.map(a=>Ry(e,a)).filter(Boolean);if(!n.length)return{scanner:r.id,skipped:"no matching files"};let s=r.bin(),i=Ay(s,r.args(n,{baseDir:e}),{cwd:e,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(i.error){let a=i.error.code==="ENOENT"?`binary not installed (${s})`:String(i.error.message||i.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(i.stdout,i.stderr,i.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:n.length,findings:o}}var Pa={id:"code-scan",serverName:"code_scan",meta:xy["code-scan"],allowedTools:["mcp__code_scan__*"],description:"Code scan \u2014 run the RIGHT deterministic linter/analyzer for a checked-out repo (auto-detects the stack: JS/TS\u2192oxlint; Java/Python/Go/Ruby/PHP\u2192semgrep) and return structured findings. Fully local; the code never leaves the box.",promptFragment:`## Code Scan (deterministic linter, auto-detects the stack)
|
|
988
986
|
After you've cloned the repo, call \`scan_code\` to get DETERMINISTIC linter
|
|
989
987
|
findings for WHATEVER stack this repo is \u2014 it auto-detects (JS/TS\u2192oxlint;
|
|
990
988
|
Java/Python/Go/Ruby/PHP\u2192semgrep) and runs the matching tool. Pass \`files\` (the changed files, ideal for
|
|
991
989
|
a review) or \`dir\` (a directory to scan). Findings are GROUND-TRUTH CANDIDATES:
|
|
992
990
|
triage them for THIS change, verify each in context (false positives exist \u2014
|
|
993
991
|
trace before asserting), fold noise, and turn the real ones into inline
|
|
994
|
-
suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=
|
|
992
|
+
suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=Cy();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=$r(e.dir):t&&t.length?n=ng(t.map(a=>$r(a))):n=process.cwd(),!G(n)||!xa(n).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${n}`});let s=t?t.map(a=>$r(n,a)):null,i=[],o=0;for(let a of eg){let c=!1;try{c=!!a.detect(n)}catch{c=!1}if(!c)continue;let l=new Set(a.langs.map(u=>u.toLowerCase())),d=s?s.filter(u=>l.has(jr(u).toLowerCase())):tg(n,a.langs,Uy),p=rg(a,n,d);Array.isArray(p.findings)&&(o+=p.findings.length),i.push(p)}return i.length?JSON.stringify({ok:!0,baseDir:n,totalFindings:o,scanners:i}):JSON.stringify({ok:!0,baseDir:n,scanners:[],totalFindings:0,note:"No known stack detected (no package.json / pyproject / go.mod \u2026). Review by hand."})}catch(t){return JSON.stringify({error:`scan_code failed: ${t.message}`})}},tools:[{name:"scan_code",description:"Run the right deterministic linter for a checked-out repo and return structured findings. Auto-detects the stack (JS/TS \u2192 oxlint; Java/Python/Go/Ruby/PHP \u2192 semgrep OSS) and runs each matching tool, scoped to files in its languages. Pass `files` (e.g. the changed files of the PR \u2014 recommended for a review) OR `dir` (a directory to scan). Returns { scanners: [ { scanner, findings: [ { file, line, severity, rule, message } ] } ] }. Findings are CANDIDATES \u2014 verify each in context before asserting. Best-effort: a stack whose linter is not installed is skipped with a note.",input_schema:{type:"object",properties:{dir:{type:"string",description:"Absolute path to the checked-out repo (or subdirectory) to scan. Defaults to the current working directory."},files:{type:"array",items:{type:"string"},description:"Explicit list of files to scan (paths relative to `dir`, or absolute). Best for a code review \u2014 pass the PR's changed files. When omitted, the whole `dir` is walked (bounded)."}}}}]};function ng(r){if(!r.length)return process.cwd();if(r.length===1)return Bn(r[0]);let e=r.map(i=>i.split("/")),t=e[0],n=[];for(let i=0;i<t.length;i++){let o=t[i];if(e.every(a=>a[i]===o))n.push(o);else break}let s=n.join("/");return s&&G(s)&&xa(s).isDirectory()?s:Bn(r[0])}import{dirname as sg,resolve as ig}from"path";import{fileURLToPath as og}from"url";import{existsSync as ag}from"fs";function cg(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=sg(og(import.meta.url)),e=ig(r,"..","bin","mcp-skill.mjs");return ag(e)?e:null}function lg(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function dg(){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 pg={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:[]}},Ca={id:"trigger-agent",callsBackend:!0,serverName:"trigger",allowedTools:["mcp__trigger__*"],envKeys:[],description:"Trigger another Zibby workflow/agent run in this project (agent-driven, fire-and-forget; cloud + self-hosted).",promptFragment:"## Trigger another agent (agent-driven)\nYou can start another Zibby agent run yourself with the `trigger_agent`\ntool \u2014 and YOU decide when and how many times to call it. Each call starts ONE\nindependent run (fire-and-forget) and returns its executionId; it does NOT wait for\nthat run to finish.\n- To re-run THIS same agent (self-dispatch) \u2014 e.g. to hand an item to another of\n this agent's scenarios \u2014 OMIT `workflowType` and pass the `input` for that run.\n- To trigger a DIFFERENT agent in the project, pass its `workflowType` + `input`.\nCall it once per run you want to start (loop over your items and call it for each).\nIt never throws \u2014 a failure comes back as { ok:false, error }; log it and move on.",resolve(){let r=cg();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=lg(),s=typeof e.workflowType=="string"&&e.workflowType.trim()?e.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!t)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!n)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!s)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let i=`${dg()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(s)}/trigger`,o=await w(i,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({input:e.input&&typeof e.input=="object"?e.input:{}})},{kind:"api",what:`trigger agent ${s}`}),a=await o.text().catch(()=>""),c;try{c=a?JSON.parse(a):{}}catch{c={raw:a}}if(!o.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${o.status})`,detail:c&&(c.error||c.message)||a.slice(0,300)});let l=c.executionId||c.execution?.id||c.id||null;return JSON.stringify({ok:!0,workflowType:s,executionId:l,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[pg]};import{spawnSync as ug}from"node:child_process";import{existsSync as qn,mkdirSync as Ua,readdirSync as mg,writeFileSync as hg}from"node:fs";import{createHash as fg}from"node:crypto";import{join as Pr}from"node:path";import{SKILL_META as yg}from"@zibby/skill-ids";function Ba(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function Da(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?Pr(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function gg(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=Pr(r,".zibby","repos");try{if(qn(e)){let t=mg(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>Pr(e,n.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return null}function bg(r){return fg("sha256").update(r).digest("hex").slice(0,16)}var Ma={id:"codebase-memory",serverName:"codebase_memory",meta:yg["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)
|
|
995
993
|
The checked-out repository is indexed into a queryable code graph + semantic
|
|
996
994
|
index. Reach for these instead of blindly grepping when you need structure,
|
|
997
995
|
relationships, or "where does X live / what depends on Y":
|
|
@@ -1003,8 +1001,8 @@ relationships, or "where does X live / what depends on Y":
|
|
|
1003
1001
|
- get_code_snippet / search_code: pull the exact code for a node / text match.
|
|
1004
1002
|
- index_status / list_projects: confirm the index is present before querying.
|
|
1005
1003
|
The repo is indexed for you at the start of the run; if a query comes back
|
|
1006
|
-
empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=
|
|
1007
|
-
`)}catch{}}catch{}return{}}};import{existsSync as
|
|
1004
|
+
empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=Da();try{Ua(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:Ba(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=gg();if(!r)return{};let e=Da();try{Ua(e,{recursive:!0})}catch{}let t=Pr(e,`.cbm-indexed-${bg(r)}`);if(qn(t))return{};let n=Ba();if(!qn(n)&&!process.env.CBM_BIN)return{};let s=ug(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{hg(t,`${new Date().toISOString()} status=${s.status}
|
|
1005
|
+
`)}catch{}}catch{}return{}}};import{existsSync as Ja,readFileSync as _g}from"node:fs";import{homedir as kg}from"node:os";import{join as wg,dirname as Sg,resolve as vg}from"node:path";import{fileURLToPath as Ig}from"node:url";import{SKILL_META as Tg}from"@zibby/skill-ids";var Ng=3e4,Gn=1;function Og(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Sg(Ig(import.meta.url)),e=vg(r,"..","bin","mcp-skill.mjs");return Ja(e)?e:null}function Ag(){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=wg(kg(),".zibby","config.json");return Ja(r)&&JSON.parse(_g(r,"utf-8")).sessionToken||null}catch{return null}}function Rg(){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 Eg(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let s=typeof t=="string"?t.trim():"";s&&(r[n[1]]=s)}return r}function Kn(r){let e=Eg(),t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no knowledge-base store is bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function Fn(r,e,t){let n=Ag();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). The knowledge base is only available inside a Zibby run.");let s=`${Rg()}/datasets/stores/${encodeURIComponent(r)}/${e}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json"},o=JSON.stringify(t),a;for(let c=0;c<=Gn;c++){let l=new AbortController,d=setTimeout(()=>l.abort(),Ng);try{let p=await fetch(s,{method:"POST",headers:i,body:o,signal:l.signal}),u=await p.text().catch(()=>"");if(p.status>=500&&c<Gn){a=new Error(`store ${p.status}`);continue}if(!p.ok)throw new Error(`gbrain ${e} failed (${p.status}): ${u.slice(0,300)}`);try{return JSON.parse(u)}catch{throw new Error(`store returned non-JSON: ${u.slice(0,200)}`)}}catch(p){if(a=p,!((p?.name==="AbortError"||p?.code==="ECONNREFUSED"||/fetch failed|network/i.test(String(p?.message)))&&c<Gn))break}finally{clearTimeout(d)}}throw a||new Error(`gbrain ${e} request failed`)}var qa={id:"gbrain",callsBackend:!0,serverName:"gbrain",allowedTools:["mcp__gbrain__*"],meta:Tg.gbrain,description:"Knowledge base (GBrain) \u2014 ingest source documents into, semantically query, and prune a per-tenant Postgres/pgvector brain (a `postgres`-type store, brokered by the control-plane)",promptFragment:`## Knowledge Base (GBrain \u2014 per-tenant document brain)
|
|
1008
1006
|
You have a per-tenant KNOWLEDGE BASE (a Postgres + pgvector "brain"), bound as a
|
|
1009
1007
|
\`postgres\`-type store in the "AVAILABLE STORES" block below. Ingested documents
|
|
1010
1008
|
are addressed by a STABLE \`sourceId\` so re-ingesting the same source UPSERTS
|
|
@@ -1015,7 +1013,7 @@ Tools:
|
|
|
1015
1013
|
Pass deleted:true to remove a source that no longer exists upstream.
|
|
1016
1014
|
- gbrain_query({ query, topK, store? }): semantic search; returns the topK most
|
|
1017
1015
|
relevant document chunks with their sourceId and relevance score.
|
|
1018
|
-
- gbrain_delete({ sourceIds, store? }): remove documents by their stable sourceId(s).`,resolve(){let r=
|
|
1016
|
+
- gbrain_delete({ sourceIds, store? }): remove documents by their stable sourceId(s).`,resolve(){let r=Og();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);for(let t of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(t)&&process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/gbrain.js","gbrainSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gbrain_ingest":{let t=Array.isArray(e?.docs)?e.docs:null;if(!t)return JSON.stringify({error:"docs is required (array of { sourceId, markdown, deleted? })"});if(t.length===0)return JSON.stringify({ok:!0,upserted:0,deleted:0,chunks:0,note:"empty docs \u2014 nothing to ingest"});if(t.find(a=>!a||typeof a.sourceId!="string"||!a.sourceId.trim())!==void 0)return JSON.stringify({error:"every doc requires a non-empty string sourceId"});let s=t.find(a=>a.deleted!==!0&&(typeof a.markdown!="string"||!a.markdown.length));if(s!==void 0)return JSON.stringify({error:`doc "${s.sourceId}" has no markdown (required unless deleted:true)`});let i=Kn(e?.store);if(i.error)return JSON.stringify({error:i.error});let o=await Fn(i.storeId,"ingest",{docs:t});return JSON.stringify({...o,store:i.name,storeId:i.storeId})}case"gbrain_query":{let t=typeof e?.query=="string"?e.query.trim():"";if(!t)return JSON.stringify({error:"query is required"});let n=Kn(e?.store);if(n.error)return JSON.stringify({error:n.error});let s={query:t};Number.isInteger(e?.topK)&&e.topK>0&&(s.topK=Math.min(e.topK,50));let i=await Fn(n.storeId,"query",s);return JSON.stringify({...i,store:n.name,storeId:n.storeId})}case"gbrain_delete":{let t=Array.isArray(e?.sourceIds)?e.sourceIds.filter(i=>typeof i=="string"&&i.trim()):null;if(!t||t.length===0)return JSON.stringify({error:"sourceIds is required (non-empty array of strings)"});let n=Kn(e?.store);if(n.error)return JSON.stringify({error:n.error});let s=await Fn(n.storeId,"delete",{sourceIds:t});return JSON.stringify({...s,store:n.name,storeId:n.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:String(t?.message||t)})}},tools:[{name:"gbrain_ingest",description:'Upsert documents into the knowledge base. Each doc is { sourceId, markdown, deleted? }; sourceId is a STABLE id (e.g. "owner/repo#docs/x.md" or a Lark doc token) so re-ingesting the same source UPDATES in place instead of duplicating. Set deleted:true to remove a source.',input_schema:{type:"object",properties:{docs:{type:"array",description:"Documents to upsert.",items:{type:"object",properties:{sourceId:{type:"string",description:"Stable source id \u2014 the upsert/delete key."},markdown:{type:"string",description:"The normalized markdown content of the document."},deleted:{type:"boolean",description:"When true, remove this sourceId from the brain (markdown ignored)."}},required:["sourceId"]}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["docs"]}},{name:"gbrain_query",description:"Semantic-search the knowledge base and return the most relevant document chunks (each with its sourceId and relevance score).",input_schema:{type:"object",properties:{query:{type:"string",description:"Natural-language query."},topK:{type:"integer",description:"How many chunks to return (default 8, max 50)."},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["query"]}},{name:"gbrain_delete",description:"Remove documents from the knowledge base by their stable sourceId(s).",input_schema:{type:"object",properties:{sourceIds:{type:"array",description:"Stable source ids to delete.",items:{type:"string"}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["sourceIds"]}}]};import{existsSync as we,readFileSync as Ut,readdirSync as Hn,mkdirSync as xg,writeFileSync as ut,statSync as Fa}from"fs";import{join as L,resolve as zn,relative as Ha,dirname as za}from"path";import{fileURLToPath as Lg}from"url";import{createRequire as $g}from"module";var jg=$g(import.meta.url),Pg=`## Workflow Builder
|
|
1019
1017
|
|
|
1020
1018
|
You can help users build custom AI workflows using the Zibby workflow framework.
|
|
1021
1019
|
|
|
@@ -1125,9 +1123,9 @@ Call with no arguments to see all available topics.
|
|
|
1125
1123
|
- Workflow names must be kebab-case (e.g., ticket-triage, pr-review).
|
|
1126
1124
|
- State flows through: each node's validated output is stored under its name in state (e.g., state.classify_ticket).
|
|
1127
1125
|
- Downstream nodes reference upstream outputs in their prompt function (e.g., \\\`\\\${JSON.stringify(state.classify_ticket, null, 2)}\\\`).
|
|
1128
|
-
- Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,
|
|
1129
|
-
`),
|
|
1130
|
-
`),n=
|
|
1126
|
+
- Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,Ya=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function Wa(r){return`${r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function Ct(r){return`${r.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}Node`}function Cg(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 Ug(r){let e=zn(r,".zibby.config.mjs");if(!we(e))return{};try{return(await import(e)).default||{}}catch{return{}}}function Bg(){try{let r=za(jg.resolve("@zibby/core/package.json")),e=L(r,"templates","browser-test-automation"),t=Ut(L(e,"nodes","preflight.mjs"),"utf-8"),n=Ut(L(e,"graph.mjs"),"utf-8");return{preflight:t,graph:n}}catch{return null}}var Ga=za(Lg(import.meta.url));function Za(){let r=zn(Ga,"..","..","..","docsite","docs");if(we(r))return r;let e=zn(Ga,"..","docs");return we(e)?e:null}function Ka(){let r=Za();if(!r)return[];try{let e=(t,n="")=>{let s=[];for(let i of Hn(t)){let o=L(t,i);try{if(Fa(o).isDirectory())s=s.concat(e(o,`${n}${i}/`));else if(i.endsWith(".md")){let a=`${n}${i.replace(/\.md$/,"")}`;s.push(a)}}catch{}}return s};return e(r)}catch{return[]}}function Va(r){let e=Za();if(!e)return null;let t=L(e,`${r}.md`);if(!we(t))return null;try{return Ut(t,"utf-8")}catch{return null}}function Dg(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",l=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${a}. ${c}.${l?` ${l}`:""}`}).join(`
|
|
1127
|
+
`),t=r.edges.map(o=>o.condition?`- ${o.from} \u2192 ${o.to} (conditional: ${o.condition})`:`- ${o.from} \u2192 ${o.to}`).join(`
|
|
1128
|
+
`),n=Bg(),s=Va("custom-workflows"),i="";return n&&(i+=`
|
|
1131
1129
|
## Real working examples from the Zibby framework
|
|
1132
1130
|
|
|
1133
1131
|
### Example node (preflight.mjs) \u2014 a prompt-only node with Zod schema and onComplete hook:
|
|
@@ -1188,10 +1186,10 @@ ${i}
|
|
|
1188
1186
|
${r.description}
|
|
1189
1187
|
|
|
1190
1188
|
### Nodes
|
|
1191
|
-
${
|
|
1189
|
+
${e}
|
|
1192
1190
|
|
|
1193
1191
|
### Edges (flow)
|
|
1194
|
-
${
|
|
1192
|
+
${t}
|
|
1195
1193
|
|
|
1196
1194
|
## Output format
|
|
1197
1195
|
|
|
@@ -1204,34 +1202,34 @@ Return a JSON object with this exact structure:
|
|
|
1204
1202
|
}
|
|
1205
1203
|
}
|
|
1206
1204
|
|
|
1207
|
-
IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function
|
|
1205
|
+
IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function Xa(r,e){let t=await Ug(e),n=Cg(t);try{let{invokeAgent:s}=await import("@zibby/core"),i=Dg(r),o=await s(i,{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(s){return console.warn(`Agent code generation failed (${s.message}), using templates`),Mg(r)}}function Mg(r){let e={};for(let t of r.nodes){let n=Ct(t.name),s=`${t.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,i=t.outputFields?.length?t.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
|
|
1208
1206
|
`):` summary: z.string().describe('Summary of the result'),
|
|
1209
|
-
status: z.enum(['ok', 'warn', 'error']).describe('Overall status'),`,o=r.edges.filter(c=>c.to===
|
|
1210
|
-
`),a=o?`${
|
|
1207
|
+
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(`
|
|
1208
|
+
`),a=o?`${t.description}
|
|
1211
1209
|
|
|
1212
1210
|
Input:
|
|
1213
1211
|
\${JSON.stringify(state.input || {}, null, 2)}
|
|
1214
1212
|
|
|
1215
|
-
${o}`:`${
|
|
1213
|
+
${o}`:`${t.description}
|
|
1216
1214
|
|
|
1217
1215
|
Input:
|
|
1218
|
-
\${JSON.stringify(state.input || {}, null, 2)}`;t
|
|
1216
|
+
\${JSON.stringify(state.input || {}, null, 2)}`;e[t.name]={code:`import { z } from '@zibby/core';
|
|
1219
1217
|
|
|
1220
1218
|
const ${s} = z.object({
|
|
1221
1219
|
${i}
|
|
1222
1220
|
});
|
|
1223
1221
|
|
|
1224
1222
|
export const ${n} = {
|
|
1225
|
-
name: '${
|
|
1223
|
+
name: '${t.name}',
|
|
1226
1224
|
prompt: (state) => \`${a}\`,
|
|
1227
1225
|
outputSchema: ${s},
|
|
1228
1226
|
};
|
|
1229
|
-
`}}return{nodes:
|
|
1227
|
+
`}}return{nodes:e}}function Jg(r,e,t,n){let s=e.toLowerCase(),i=Wa(s),o=L(r,".zibby","workflows",s),a=L(o,"nodes");xg(a,{recursive:!0});let c=t.nodes.map(f=>f.name);for(let f of t.nodes){let b=n.nodes?.[f.name]?.code;b&&ut(L(a,`${f.name.replace(/_/g,"-")}.mjs`),b,"utf-8")}let l=c.map(f=>{let b=Ct(f),g=f.replace(/_/g,"-");return`export { ${b} } from './${g}.mjs';`});ut(L(a,"index.mjs"),`${l.join(`
|
|
1230
1228
|
`)}
|
|
1231
|
-
`,"utf-8");let d=c[0],p=c.map(
|
|
1232
|
-
`),m=
|
|
1233
|
-
${
|
|
1234
|
-
});`:` graph.addEdge('${
|
|
1229
|
+
`,"utf-8");let d=c[0],p=c.map(f=>Ct(f)).join(", "),u=c.map(f=>` graph.addNode('${f}', ${Ct(f)});`).join(`
|
|
1230
|
+
`),m=t.edges.map(f=>f.condition?` graph.addConditionalEdges('${f.from}', (state) => {
|
|
1231
|
+
${f.condition}
|
|
1232
|
+
});`:` graph.addEdge('${f.from}', '${f.to}');`).join(`
|
|
1235
1233
|
`),h=`import { WorkflowAgent, WorkflowGraph } from '@zibby/core';
|
|
1236
1234
|
import { ${p} } from './nodes/index.mjs';
|
|
1237
1235
|
|
|
@@ -1251,18 +1249,18 @@ ${m}
|
|
|
1251
1249
|
console.log(\`[${s}] workflow complete \u2014 success: \${result.success !== false}\`);
|
|
1252
1250
|
}
|
|
1253
1251
|
}
|
|
1254
|
-
`;
|
|
1255
|
-
`,"utf-8");let
|
|
1256
|
-
`,_=fe(f)?It(f,"utf-8"):"";return _.includes(b)||et(f,_+y,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${h}`,exportName:b,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function jy(r,t){let{name:e,projectId:n}=r,s=(e||"").toLowerCase();if(!s)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let i=E(t,".zibby","workflows",s);if(!fe(i))return JSON.stringify({error:`Workflow "${s}" not found at .zibby/workflows/${s}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${E(t,"packages/cli/bin/zibby.js")}" deploy ${s} --project ${n}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:a.trim()})}catch{try{let{execSync:a}=await import("child_process"),c=a(`npx zibby deploy ${s} --project ${n}`,{cwd:t,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:c.trim()})}catch(a){return JSON.stringify({error:`Deploy failed: ${a.message}`})}}}function $y(r){let t=E(r,".zibby","workflows");if(!fe(t))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=kn(t).filter(s=>{try{return sa(E(t,s)).isDirectory()}catch{return!1}}).map(s=>{let i=E(t,s,"workflow.json"),o={};try{o=JSON.parse(It(i,"utf-8"))}catch{}let a=E(t,s,"nodes"),c=0;try{c=kn(a).filter(l=>l.endsWith(".mjs")&&l!=="index.mjs").length}catch{}return{name:s,description:o.description||"",nodeCount:c,path:ia(r,E(t,s))}});return JSON.stringify({workflows:n})}var ua={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:vy,tools:[{name:"design_workflow",description:"Design a workflow spec (nodes, edges, descriptions) for the user to review before building. Call this after understanding requirements.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name in kebab-case (e.g., ticket-triage)"},description:{type:"string",description:"What the workflow does"},nodes:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Node name in snake_case (e.g., classify_ticket)"},description:{type:"string",description:"What this node does \u2014 be specific about input/output"},inputFields:{type:"array",items:{type:"string"},description:"Key fields this node reads from state"},outputFields:{type:"array",items:{type:"string"},description:"Key fields this node produces"}},required:["name","description"]},description:"Workflow nodes (processing steps)"},edges:{type:"array",items:{type:"object",properties:{from:{type:"string",description:"Source node name"},to:{type:"string",description:'Target node name (or "END")'},condition:{type:"string",description:"JS expression for conditional routing (optional)"}},required:["from","to"]},description:"Edges connecting nodes. If omitted, nodes are wired linearly."}},required:["name","description","nodes"]}},{name:"build_workflow",description:"Generate real workflow code on disk from a design spec. Uses the configured AI agent for high-quality code generation.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name (from design_workflow)"},spec:{type:"object",description:"The full spec object returned by design_workflow",properties:{name:{type:"string"},description:{type:"string"},nodes:{type:"array",items:{type:"object"}},edges:{type:"array",items:{type:"object"}}}}},required:["name","spec"]}},{name:"add_node",description:"Add a new node to an existing workflow. Generates the node file and updates the barrel export.",input_schema:{type:"object",properties:{workflowName:{type:"string",description:"Existing workflow name (kebab-case)"},nodeName:{type:"string",description:"New node name (snake_case)"},description:{type:"string",description:"What this node does"},inputFields:{type:"array",items:{type:"string"},description:"Fields read from state"},outputFields:{type:"array",items:{type:"string"},description:"Fields produced"}},required:["workflowName","nodeName","description"]}},{name:"deploy_workflow",description:"Deploy a workflow to Zibby Cloud. Returns the trigger URL.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name to deploy"},projectId:{type:"string",description:"Target project ID"}},required:["name","projectId"]}},{name:"list_workflows",description:"List all local workflows in .zibby/workflows/.",input_schema:{type:"object",properties:{}}},{name:"explore_framework_docs",description:"Read Zibby framework documentation on demand. Call this before building complex workflows or when you need details on advanced patterns (middleware, conditional routing, skills, deployment, CLI commands).",input_schema:{type:"object",properties:{topic:{type:"string",description:'Doc topic to read (e.g., "workflow", "custom-workflows", "cli-reference", "packages/core", "packages/skills", "integrations/jira"). Call with no topic to list all available docs.'}}}}],async handleToolCall(r,t,e){let n=e?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Ey(t);case"build_workflow":return await xy(t,n);case"add_node":return await Ly(t,n);case"deploy_workflow":return await jy(t,n);case"list_workflows":return $y(n);case"explore_framework_docs":{let s=(t.topic||"").trim();if(!s){let o=na();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let i=da(s);if(!i){let o=na();return JSON.stringify({error:`Doc "${s}" not found.`,available:o})}return JSON.stringify({topic:s,content:i})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(s){return JSON.stringify({error:s.message})}},resolve(){return null}};import{resolveIntegrationToken as Py}from"@zibby/core/backend-client.js";var vn=Object.freeze({id:"openai_billing",callsBackend:!0,requiresIntegration:S.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),In=Object.freeze({id:"anthropic_billing",callsBackend:!0,requiresIntegration:S.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),Nn=Object.freeze({id:"cursor_admin",callsBackend:!0,requiresIntegration:S.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function ma(r){return Math.floor(r/1e3)}function Sn(r){return new Date(r).toISOString().slice(0,10)}function ha(r){return new Date(r).toISOString()}async function Nt(r){let t=await Py(r);if(!t?.token)throw new Error(`${r} token resolver returned no token`);return t.token}async function fa({startMs:r,endMs:t,groupBy:e=["project_id","line_item"]}){let n=await Nt("openai_billing"),s=[],i=0,o=e.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let d=`https://api.openai.com/v1/organization/costs?${[`start_time=${ma(r)}`,`end_time=${ma(t)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(d,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){i+=1;let h=Sn((m.start_time||0)*1e3);for(let f of m.results||[])s.push({provider:"openai",day:h,costUsd:Number(f.amount?.value??0),projectId:f.project_id||void 0,apiKeyId:f.api_key_id||void 0,model:f.line_item||void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:s,rawBuckets:i}}async function Cy(){let r=await Nt("openai_billing"),e=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`OpenAI projects API ${e.status}: ${i.slice(0,200)}`)}let n=await e.json(),s=new Map;for(let i of n.data||[])s.set(i.id,i.name);return s}async function ya({startMs:r,endMs:t,groupBy:e=["workspace_id"]}){let n=await Nt("anthropic_billing"),s=[],i=0,o=e.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let d=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(ha(r))}`,`ending_at=${encodeURIComponent(ha(t))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(d,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){i+=1;let h=(m.starting_at||"").slice(0,10);for(let f of m.results||[])s.push({provider:"anthropic",day:h,costUsd:Number(f.amount??f.cost??0),workspaceId:f.workspace_id||void 0,apiKeyId:f.api_key_id||void 0,model:f.model||void 0,tokensIn:f.uncached_input_tokens!=null?Number(f.uncached_input_tokens):void 0,tokensOut:f.output_tokens!=null?Number(f.output_tokens):void 0,cachedTokens:f.cached_input_tokens!=null?Number(f.cached_input_tokens):void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:s,rawBuckets:i}}async function Uy(){let r=await Nt("anthropic_billing"),e=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`Anthropic workspaces ${e.status}: ${i.slice(0,200)}`)}let n=await e.json(),s=new Map;for(let i of n.data||[])s.set(i.id,i.name);return s}async function ga({startMs:r,endMs:t}){let e=await Nt("cursor_admin"),n=Sn(r),s=Sn(t),i=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${s}`,o=await fetch(i,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${d.slice(0,200)}`)}let a=await o.json(),c=[],l=0;for(let d of a.data||[]){l+=1;let p=d.date;for(let u of d.userMetrics||[]){for(let m of u.modelUsage||[]){let h=Number(m.acceptedLines??0),f=Number(m.suggestedLines??0);c.push({provider:"cursor",day:p,costUsd:Number(m.totalCents??0)/100,userEmail:u.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:f>0?h/f:void 0})}(!u.modelUsage||u.modelUsage.length===0)&&c.push({provider:"cursor",day:p,costUsd:Number(u.totalCents??0)/100,userEmail:u.email})}}return{ok:!0,items:c,rawBuckets:l}}async function By({startMs:r,endMs:t}){let[e,n,s]=await Promise.allSettled([fa({startMs:r,endMs:t}),ya({startMs:r,endMs:t}),ga({startMs:r,endMs:t})]),i=d=>d.status==="fulfilled"?d.value:{ok:!1,error:d.reason?.message||String(d.reason),items:[]},o=i(e),a=i(n),c=i(s),l=[{provider:"openai",totalUsd:o.items.reduce((d,p)=>d+(p.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((d,p)=>d+(p.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((d,p)=>d+(p.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:l}}function Dy(r,t){let e=new Map;for(let n of r){let s=t(n);if(!s)continue;let i=e.get(s)||{key:s,totalUsd:0,count:0};i.totalUsd+=n.costUsd||0,i.count+=1,e.set(s,i)}return[...e.values()].sort((n,s)=>s.totalUsd-n.totalUsd)}function Jy(r){if(!r.length)return{mean:0,stddev:0};let t=r.reduce((n,s)=>n+s,0)/r.length,e=r.reduce((n,s)=>n+(s-t)**2,0)/r.length;return{mean:t,stddev:Math.sqrt(e)}}import{SKILL_IDS as vS}from"@zibby/skill-ids";import{z as w}from"zod";var Tt=["ok","info","warn","critical"],My=w.object({primary:w.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:w.object({value:w.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:w.enum(["up","down","flat"]).optional(),severity:w.enum(Tt).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:w.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),qy=w.object({kind:w.literal("trend"),title:w.string().max(120).optional(),labels:w.array(w.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:w.array(w.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:w.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:w.enum(Tt).optional()}),Fy=w.object({kind:w.literal("table"),title:w.string().max(120).optional(),headers:w.array(w.string().max(40)).min(1).max(8),rows:w.array(w.array(w.union([w.string().max(200),w.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),Ky=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(Tt).default("info").optional(),items:w.array(w.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),Gy=w.object({kind:w.literal("breakdown"),title:w.string().max(120).optional(),rows:w.array(w.object({label:w.string().min(1).max(80),value:w.string().min(1).max(80),sub:w.string().max(120).optional(),severity:w.enum(Tt).optional()})).min(1).max(20)}),Hy=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),Yy=w.discriminatedUnion("kind",[qy,Fy,Ky,Gy,Hy]),Ot=w.object({title:w.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:w.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:My,sections:w.array(Yy).max(20).default([]).superRefine((r,t)=>{r.forEach((e,n)=>{e.kind==="trend"&&e.labels.length!==e.values.length&&t.addIssue({code:w.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),e.kind==="table"&&!e.rows.every(s=>s.length===e.headers.length)&&t.addIssue({code:w.ZodIssueCode.custom,path:[n,"rows"],message:"every row must have headers.length entries"})})}),footer:w.object({viewUrl:w.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:w.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),B=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),br=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),zy=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function kr(r,t,e=12){if(!Number.isFinite(r)||!Number.isFinite(t)||t<=0)return"";let n=Math.max(0,Math.min(1,r/t)),s=Math.round(n*e);return"\u2593".repeat(s)+"\u2591".repeat(e-s)}function At(r,t){let e=String(r);return e.length>=t?e:e+" ".repeat(t-e.length)}function wr(r,t){let e=String(r);return e.length>=t?e:" ".repeat(t-e.length)+e}function ka({headers:r,rows:t}){let e=r.map((o,a)=>{let c=Math.max(String(o).length,...t.map(l=>String(l[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>At(a,e[c])).join(" "),s=e.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),s,...t.map(o=>n(o))].join(`
|
|
1257
|
-
`)+"\n```"}function
|
|
1258
|
-
`+
|
|
1259
|
-
`)+"\n```"}});break}case"table":{
|
|
1252
|
+
`;ut(L(o,"graph.mjs"),h,"utf-8");let y={name:s,description:t.description||`${i} workflow`,entryClass:i,triggers:{api:!0}};ut(L(o,"workflow.json"),`${JSON.stringify(y,null,2)}
|
|
1253
|
+
`,"utf-8");let _=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(f=>`nodes/${f.replace(/_/g,"-")}.mjs`)];return{workflowDir:Ha(r,o),files:_,className:i,slug:s}}async function qg(r){let{name:e,description:t,nodes:n,edges:s}=r;if(!e||!Ya.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 i={name:e.toLowerCase(),description:t||`${Wa(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:s||[]};if(i.edges.length===0&&i.nodes.length>0){for(let o=0;o<i.nodes.length-1;o++)i.edges.push({from:i.nodes[o].name,to:i.nodes[o+1].name});i.edges.push({from:i.nodes[i.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:i,message:`Workflow "${i.name}" designed with ${i.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:i.nodes.map(o=>o.name),flow:i.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function Gg(r,e){let{name:t,spec:n}=r,s=(t||n?.name||"").toLowerCase();if(!s||!Ya.test(s))return JSON.stringify({error:`Invalid workflow name "${s}".`});if(!n||!n.nodes||n.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let i=L(e,".zibby","workflows",s);if(we(i))return JSON.stringify({error:`Workflow "${s}" already exists at .zibby/workflows/${s}/. Delete it first or choose a different name.`});let o=await Xa(n,e),a=Jg(e,s,n,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${s}" created at ${a.workflowDir}/`,nextSteps:[`Test locally: zibby start ${s}`,`Deploy to cloud: zibby deploy ${s} --project <project-id>`,`Tail logs: zibby logs --workflow ${s} --project <project-id>`]})}async function Kg(r,e){let{workflowName:t,nodeName:n,description:s,inputFields:i,outputFields:o}=r,a=(t||"").toLowerCase(),c=(n||"").replace(/-/g,"_"),l=L(e,".zibby","workflows",a);if(!we(l))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let d={name:a,description:"",nodes:[{name:c,description:s||`Process ${c}`,inputFields:i||[],outputFields:o||[]}],edges:[]},u=(await Xa(d,e)).nodes?.[c]?.code;if(!u)return JSON.stringify({error:"Failed to generate node code."});let m=L(l,"nodes"),h=`${c.replace(/_/g,"-")}.mjs`;ut(L(m,h),u,"utf-8");let y=L(m,"index.mjs"),_=Ct(c),f=`export { ${_} } from './${c.replace(/_/g,"-")}.mjs';
|
|
1254
|
+
`,b=we(y)?Ut(y,"utf-8"):"";return b.includes(_)||ut(y,b+f,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${h}`,exportName:_,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Fg(r,e){let{name:t,projectId:n}=r,s=(t||"").toLowerCase();if(!s)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let i=L(e,".zibby","workflows",s);if(!we(i))return JSON.stringify({error:`Workflow "${s}" not found at .zibby/workflows/${s}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${L(e,"packages/cli/bin/zibby.js")}" deploy ${s} --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 ${s} --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 Hg(r){let e=L(r,".zibby","workflows");if(!we(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=Hn(e).filter(s=>{try{return Fa(L(e,s)).isDirectory()}catch{return!1}}).map(s=>{let i=L(e,s,"workflow.json"),o={};try{o=JSON.parse(Ut(i,"utf-8"))}catch{}let a=L(e,s,"nodes"),c=0;try{c=Hn(a).filter(l=>l.endsWith(".mjs")&&l!=="index.mjs").length}catch{}return{name:s,description:o.description||"",nodeCount:c,path:Ha(r,L(e,s))}});return JSON.stringify({workflows:n})}var Qa={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:Pg,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 qg(e);case"build_workflow":return await Gg(e,n);case"add_node":return await Kg(e,n);case"deploy_workflow":return await Fg(e,n);case"list_workflows":return Hg(n);case"explore_framework_docs":{let s=(e.topic||"").trim();if(!s){let o=Ka();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let i=Va(s);if(!i){let o=Ka();return JSON.stringify({error:`Doc "${s}" not found.`,available:o})}return JSON.stringify({topic:s,content:i})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(s){return JSON.stringify({error:s.message})}},resolve(){return null}};import{resolveIntegrationToken as zg}from"@zibby/core/backend-client.js";var Wn=Object.freeze({id:"openai_billing",callsBackend:!0,requiresIntegration:I.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),Zn=Object.freeze({id:"anthropic_billing",callsBackend:!0,requiresIntegration:I.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),Vn=Object.freeze({id:"cursor_admin",callsBackend:!0,requiresIntegration:I.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function ec(r){return Math.floor(r/1e3)}function Yn(r){return new Date(r).toISOString().slice(0,10)}function tc(r){return new Date(r).toISOString()}async function Bt(r){let e=await zg(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function rc({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let n=await Bt("openai_billing"),s=[],i=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let d=`https://api.openai.com/v1/organization/costs?${[`start_time=${ec(r)}`,`end_time=${ec(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await w(d,{headers:{Authorization:`Bearer ${n}`}},{kind:"api",what:"OpenAI organization/costs"});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){i+=1;let h=Yn((m.start_time||0)*1e3);for(let y of m.results||[])s.push({provider:"openai",day:h,costUsd:Number(y.amount?.value??0),projectId:y.project_id||void 0,apiKeyId:y.api_key_id||void 0,model:y.line_item||void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:s,rawBuckets:i}}async function Yg(){let r=await Bt("openai_billing"),t=await w("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}},{kind:"api",what:"OpenAI organization/projects"});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${i.slice(0,200)}`)}let n=await t.json(),s=new Map;for(let i of n.data||[])s.set(i.id,i.name);return s}async function nc({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let n=await Bt("anthropic_billing"),s=[],i=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let d=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(tc(r))}`,`ending_at=${encodeURIComponent(tc(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await w(d,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}},{kind:"api",what:"Anthropic cost_report"});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){i+=1;let h=(m.starting_at||"").slice(0,10);for(let y of m.results||[])s.push({provider:"anthropic",day:h,costUsd:Number(y.amount??y.cost??0),workspaceId:y.workspace_id||void 0,apiKeyId:y.api_key_id||void 0,model:y.model||void 0,tokensIn:y.uncached_input_tokens!=null?Number(y.uncached_input_tokens):void 0,tokensOut:y.output_tokens!=null?Number(y.output_tokens):void 0,cachedTokens:y.cached_input_tokens!=null?Number(y.cached_input_tokens):void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:s,rawBuckets:i}}async function Wg(){let r=await Bt("anthropic_billing"),t=await w("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}},{kind:"api",what:"Anthropic workspaces"});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${i.slice(0,200)}`)}let n=await t.json(),s=new Map;for(let i of n.data||[])s.set(i.id,i.name);return s}async function sc({startMs:r,endMs:e}){let t=await Bt("cursor_admin"),n=Yn(r),s=Yn(e),i=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${s}`,o=await w(i,{headers:{Authorization:`Bearer ${t}`}},{kind:"api",what:"Cursor daily-usage-data"});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${d.slice(0,200)}`)}let a=await o.json(),c=[],l=0;for(let d of a.data||[]){l+=1;let p=d.date;for(let u of d.userMetrics||[]){for(let m of u.modelUsage||[]){let h=Number(m.acceptedLines??0),y=Number(m.suggestedLines??0);c.push({provider:"cursor",day:p,costUsd:Number(m.totalCents??0)/100,userEmail:u.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:y>0?h/y:void 0})}(!u.modelUsage||u.modelUsage.length===0)&&c.push({provider:"cursor",day:p,costUsd:Number(u.totalCents??0)/100,userEmail:u.email})}}return{ok:!0,items:c,rawBuckets:l}}async function Zg({startMs:r,endMs:e}){let[t,n,s]=await Promise.allSettled([rc({startMs:r,endMs:e}),nc({startMs:r,endMs:e}),sc({startMs:r,endMs:e})]),i=d=>d.status==="fulfilled"?d.value:{ok:!1,error:d.reason?.message||String(d.reason),items:[]},o=i(t),a=i(n),c=i(s),l=[{provider:"openai",totalUsd:o.items.reduce((d,p)=>d+(p.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((d,p)=>d+(p.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((d,p)=>d+(p.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:l}}function Vg(r,e){let t=new Map;for(let n of r){let s=e(n);if(!s)continue;let i=t.get(s)||{key:s,totalUsd:0,count:0};i.totalUsd+=n.costUsd||0,i.count+=1,t.set(s,i)}return[...t.values()].sort((n,s)=>s.totalUsd-n.totalUsd)}function Xg(r){if(!r.length)return{mean:0,stddev:0};let e=r.reduce((n,s)=>n+s,0)/r.length,t=r.reduce((n,s)=>n+(s-e)**2,0)/r.length;return{mean:e,stddev:Math.sqrt(t)}}import{SKILL_IDS as cI}from"@zibby/skill-ids";import{z as S}from"zod";var Dt=["ok","info","warn","critical"],Qg=S.object({primary:S.string().min(1).max(200).describe('Headline number or phrase (e.g. "$8,240"). Rendered in large/bold.'),delta:S.object({value:S.string().max(40).describe('Delta vs baseline (e.g. "+12% wow"). Free-form string.'),direction:S.enum(["up","down","flat"]).optional(),severity:S.enum(Dt).optional().describe("Color severity for the delta (warn/critical highlights regressions).")}).optional().describe("Optional comparison vs baseline. Renders inline next to primary."),summary:S.string().max(800).optional().describe('One-sentence narrative ("why this number"). Plain prose.')}),eb=S.object({kind:S.literal("trend"),title:S.string().max(120).optional(),labels:S.array(S.string().max(60)).min(2).max(20).describe('Bucket labels (e.g. ["Week-3", "Week-2", "Week-1", "This wk"]).'),values:S.array(S.number()).min(2).max(20).describe("Numeric values, one per label. Must match labels.length."),highlight:S.enum(["last","max","min","none"]).default("last").optional().describe("Which bucket to visually highlight in the rendered card."),severity:S.enum(Dt).optional()}),tb=S.object({kind:S.literal("table"),title:S.string().max(120).optional(),headers:S.array(S.string().max(40)).min(1).max(8),rows:S.array(S.array(S.union([S.string().max(200),S.number()])).min(1).max(8)).max(40).describe("2D matrix. Each inner array must have headers.length entries.")}),rb=S.object({kind:S.literal("callouts"),title:S.string().max(120).optional(),tone:S.enum(Dt).default("info").optional(),items:S.array(S.string().min(1).max(600)).min(1).max(10).describe("Each item renders as a bullet with a severity emoji.")}),nb=S.object({kind:S.literal("breakdown"),title:S.string().max(120).optional(),rows:S.array(S.object({label:S.string().min(1).max(80),value:S.string().min(1).max(80),sub:S.string().max(120).optional(),severity:S.enum(Dt).optional()})).min(1).max(20)}),sb=S.object({kind:S.literal("paragraph"),title:S.string().max(120).optional(),text:S.string().min(1).max(3e3)}),ib=S.discriminatedUnion("kind",[eb,tb,rb,nb,sb]),Mt=S.object({title:S.string().min(1).max(200).describe('Card title (e.g. "Weekly AI Spend Report").'),subtitle:S.string().max(200).optional().describe('Date range or smaller header (e.g. "May 13 \u2014 May 20").'),headline:Qg,sections:S.array(ib).max(20).default([]).superRefine((r,e)=>{r.forEach((t,n)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:S.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(s=>s.length===t.headers.length)&&e.addIssue({code:S.ZodIssueCode.custom,path:[n,"rows"],message:"every row must have headers.length entries"})})}),footer:S.object({viewUrl:S.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:S.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),M=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),Cr=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),ob=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Ur(r,e,t=12){if(!Number.isFinite(r)||!Number.isFinite(e)||e<=0)return"";let n=Math.max(0,Math.min(1,r/e)),s=Math.round(n*t);return"\u2593".repeat(s)+"\u2591".repeat(t-s)}function Jt(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function Br(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function ac({headers:r,rows:e}){let t=r.map((o,a)=>{let c=Math.max(String(o).length,...e.map(l=>String(l[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>Jt(a,t[c])).join(" "),s=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),s,...e.map(o=>n(o))].join(`
|
|
1255
|
+
`)+"\n```"}function ab(r){let e=Mt.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 i=Cr[e.headline.delta.direction]||"",o=e.headline.delta.severity?M[e.headline.delta.severity]:"";n.push(`${i} ${e.headline.delta.value} ${o}`.trim())}let s=n.join(" ");e.headline.summary&&(s+=`
|
|
1256
|
+
`+e.headline.summary),t.push({type:"section",text:{type:"mrkdwn",text:s}});for(let i of e.sections)switch(t.push({type:"divider"}),i.title&&t.push({type:"section",text:{type:"mrkdwn",text:`*${i.title}*`}}),i.kind){case"trend":{let o=Math.max(...i.values),a=i.labels.map((c,l)=>{let d=i.values[l],p=Ur(d,o),m=(i.highlight==="last"&&l===i.labels.length-1||i.highlight==="max"&&d===o||i.highlight==="min"&&d===Math.min(...i.values))&&i.severity?` ${M[i.severity]}`:"";return`${Jt(c,10)} ${Br(d.toLocaleString(),8)} ${p}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
|
|
1257
|
+
`)+"\n```"}});break}case"table":{t.push({type:"section",text:{type:"mrkdwn",text:ac(i)}});break}case"callouts":{let o=M[i.tone||"info"];t.push({type:"section",text:{type:"mrkdwn",text:i.items.map(a=>`${o} ${a}`).join(`
|
|
1260
1258
|
`)}});break}case"breakdown":{let o=i.rows.map(a=>({type:"mrkdwn",text:`*${a.label}*
|
|
1261
1259
|
${a.value}${a.sub?`
|
|
1262
|
-
_${a.sub}_`:""}${a.severity?` ${
|
|
1263
|
-
`+
|
|
1264
|
-
`)+"\n```"}});break}case"table":{
|
|
1265
|
-
`)}});break}case"breakdown":{let a=o.rows.map(c=>{let l=c.severity?` ${
|
|
1266
|
-
`)}});break}case"paragraph":{
|
|
1267
|
-
`)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:i.headers.map(c=>
|
|
1268
|
-
`)}import{createRequire as
|
|
1260
|
+
_${a.sub}_`:""}${a.severity?` ${M[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)t.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{t.push({type:"section",text:{type:"mrkdwn",text:i.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let i=[];e.footer.viewUrl&&i.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:e.footer.viewUrl,style:"primary"}),e.footer.rerunUrl&&i.push({type:"button",text:{type:"plain_text",text:"Run again"},url:e.footer.rerunUrl}),t.push({type:"divider"}),t.push({type:"actions",elements:i})}return t}function cb(r){let e=Mt.parse(r),t=[],n=[`**${e.headline.primary}**`];if(e.headline.delta){let o=Cr[e.headline.delta.direction]||"",a=e.headline.delta.severity?M[e.headline.delta.severity]:"";n.push(`${o} ${e.headline.delta.value} ${a}`.trim())}let s=n.join(" ");e.headline.summary&&(s+=`
|
|
1261
|
+
`+e.headline.summary),t.push({tag:"div",text:{tag:"lark_md",content:s}});for(let o of e.sections)switch(t.push({tag:"hr"}),o.title&&t.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let a=Math.max(...o.values),c=o.labels.map((l,d)=>{let p=o.values[d],u=Ur(p,a),h=(o.highlight==="last"&&d===o.labels.length-1||o.highlight==="max"&&p===a||o.highlight==="min"&&p===Math.min(...o.values))&&o.severity?` ${M[o.severity]}`:"";return`${Jt(l,10)} ${Br(p.toLocaleString(),8)} ${u}${h}`});t.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
|
|
1262
|
+
`)+"\n```"}});break}case"table":{t.push({tag:"div",text:{tag:"lark_md",content:ac(o)}});break}case"callouts":{let a=M[o.tone||"info"];t.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
|
|
1263
|
+
`)}});break}case"breakdown":{let a=o.rows.map(c=>{let l=c.severity?` ${M[c.severity]}`:"",d=c.sub?` *${c.sub}*`:"";return`**${c.label}** ${c.value}${d}${l}`});t.push({tag:"div",text:{tag:"lark_md",content:a.join(`
|
|
1264
|
+
`)}});break}case"paragraph":{t.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let o=[];e.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:e.footer.viewUrl,type:"primary"}),e.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:e.footer.rerunUrl,type:"default"}),t.push({tag:"hr"}),t.push({tag:"action",actions:o})}let i="blue";return e.headline.delta?.severity&&(i=ob[e.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:e.title.slice(0,200)},subtitle:e.subtitle?{tag:"plain_text",content:e.subtitle.slice(0,200)}:void 0,template:i},elements:t}}var lb=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),ic=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function He(r,e={}){let t={type:"text",text:{content:String(r).slice(0,2e3)}};return e.annotations&&(t.annotations=e.annotations),[t]}function Xn(r,e){let t={object:"block",type:"paragraph",paragraph:{rich_text:He(r)}};return e&&(t.paragraph.color=e),t}function db(r){return{object:"block",type:"code",code:{rich_text:He(r),language:"plain text"}}}function pb(r){let e=Mt.parse(r),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:He(e.title.slice(0,200))}}),e.subtitle&&t.push(Xn(e.subtitle,"gray_background"));let n=[{type:"text",text:{content:e.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(e.headline.delta){let i=Cr[e.headline.delta.direction]||"",o=e.headline.delta.severity?M[e.headline.delta.severity]:"",a=` ${i} ${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(Xn(e.headline.summary));for(let i of e.sections)switch(t.push({object:"block",type:"divider",divider:{}}),i.title&&t.push({object:"block",type:"heading_2",heading_2:{rich_text:He(i.title)}}),i.kind){case"trend":{let o=Math.max(...i.values),a=Math.min(...i.values),c=i.labels.map((l,d)=>{let p=i.values[d],u=Ur(p,o),h=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&p===o||i.highlight==="min"&&p===a)&&i.severity?` ${M[i.severity]}`:"";return`${Jt(l,10)} ${Br(p.toLocaleString(),8)} ${u}${h}`});t.push(db(c.join(`
|
|
1265
|
+
`)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:i.headers.map(c=>He(c))}},a=i.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(l=>He(String(l)))}}));t.push({object:"block",type:"table",table:{table_width:i.headers.length,has_column_header:!0,has_row_header:!1,children:[o,...a]}});break}case"callouts":{let o=i.tone||"info",a=ic[o],c=lb[o];for(let l of i.items)t.push({object:"block",type:"callout",callout:{rich_text:He(l),icon:{type:"emoji",emoji:a},color:c}});break}case"breakdown":{for(let o of i.rows){let a=[{type:"text",text:{content:`${o.label}: `},annotations:{bold:!0}},{type:"text",text:{content:String(o.value)}}];o.sub&&a.push({type:"text",text:{content:` (${o.sub})`},annotations:{italic:!0}}),o.severity&&a.push({type:"text",text:{content:` ${M[o.severity]}`}}),t.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{t.push(Xn(i.text));break}}e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)&&(t.push({object:"block",type:"divider",divider:{}}),e.footer.viewUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.viewUrl}}),e.footer.rerunUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.rerunUrl}}));let s=e.headline.delta?.severity?ic[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:s}}function oc(r){return String(r??"").replace(/\|/g,"\\|")}function ub(r){let e=Mt.parse(r),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let n=[`**${e.headline.primary}**`];if(e.headline.delta){let s=Cr[e.headline.delta.direction]||"",i=e.headline.delta.severity?M[e.headline.delta.severity]:"";n.push(`${s} ${e.headline.delta.value} ${i}`.trim())}t.push("",n.join(" ")),e.headline.summary&&t.push("",e.headline.summary);for(let s of e.sections)switch(t.push("","---",""),s.title&&t.push(`## ${s.title}`,""),s.kind){case"trend":{let i=Math.max(...s.values),o=Math.min(...s.values),a=s.labels.map((c,l)=>{let d=s.values[l],p=Ur(d,i),m=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&d===i||s.highlight==="min"&&d===o)&&s.severity?` ${M[s.severity]}`:"";return`${Jt(c,10)} ${Br(d.toLocaleString(),8)} ${p}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${s.headers.map(oc).join(" | ")} |`),t.push(`| ${s.headers.map(()=>"---").join(" | ")} |`);for(let i of s.rows)t.push(`| ${i.map(oc).join(" | ")} |`);break}case"callouts":{let i=M[s.tone||"info"];for(let o of s.items)t.push(`- ${i} ${o}`);break}case"breakdown":{for(let i of s.rows){let o=i.sub?` _${i.sub}_`:"",a=i.severity?` ${M[i.severity]}`:"";t.push(`- **${i.label}**: ${i.value}${o}${a}`)}break}case"paragraph":{t.push(s.text);break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let s=[];e.footer.viewUrl&&s.push(`[View in Zibby](${e.footer.viewUrl})`),e.footer.rerunUrl&&s.push(`[Run again](${e.footer.rerunUrl})`),t.push("","---","",s.join(" \xB7 "))}return t.join(`
|
|
1266
|
+
`)}import{createRequire as mb}from"module";import{fileURLToPath as hb}from"url";import{registerHandlers as fb}from"@zibby/core/function-skill-registry.js";import{registerSkill as yb}from"@zibby/agent-workflow";var gb=mb(import.meta.url);function bb(){try{return gb.resolve("@zibby/core/function-bridge.js")}catch{return null}}var _b=import.meta.url;function kb(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,s)=>s;let t=new Error().stack;for(let n=2;n<t.length;n++){let s=t[n].getFileName();if(s&&s!==_b&&!s.startsWith("node:"))return s.startsWith("file://")?hb(s):s}return null}finally{Error.prepareStackTrace=r}}function wb(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let e={},t=[];for(let[n,s]of Object.entries(r))if(typeof s=="string")e[n]={type:s},t.push(n);else{let{required:i,...o}=s;e[n]=o,i!==!1&&t.push(n)}return{type:"object",properties:e,required:t}}function Sb(r,e,t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n={[r]:t.handler},s=[{name:r,description:t.description||"",input_schema:wb(t.input)}];return fb(r,n,s),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:t.description||`Function skill: ${r}`,envKeys:[],tools:s,resolve(){let i=bb();return i?{command:"node",args:[i,e,r]}:null}}}function vb(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 cc(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=kb();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);t=Sb(r,n,e)}else if(typeof e.resolve=="function")t=vb(r,e);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return yb(t),t}var Ib=cc;import{registerSkill as fI,getSkill as yI,hasSkill as gI,getAllSkills as bI,listSkillIds as _I}from"@zibby/agent-workflow";var N=r=>Tb(rs(r));N(ss);N(Ss);N(Ve);N(Xe);N(Us);N(Ds);N(Js);N(Hs);N(zs);N(Zs);N(U);N(F);N(Qs);N(ai);N(pi);N(yi);N(Ii);N(Ei);N(xi);N(hr);N($i);N(no);N(Te);N(co);N(Pi);N(Mi);N(vo);N(Eo);N(Co);N(sa);N(fa);N(Go);N(ya);N(ga);N(Oa);N(Pa);N(Ca);N(Ma);N(qa);N(Qa);N(Wn);N(Zn);N(Vn);N({...U,id:"slack_notify"});export{I as INTEGRATIONS,wc as INTEGRATION_REGISTRY,re as REPORT_CODES,Dt as REPORT_SEVERITIES,cI as SKILLS,Zn as anthropicBillingSkill,sa as artifactSkill,ss as browserSkill,fa as chartRenderSkill,vo as chatMemorySkill,xi as chatNotifySkill,ga as chatProgressSkill,Or as checkRenderedReport,Pa as codeScanSkill,ya as codeStatsSkill,Ma as codebaseMemorySkill,Mi as coreToolsSkill,Vn as cursorAdminSkill,Co as datasetStoreSkill,ns as devServerPreviewRecipe,Qs as discordSkill,Zg as fetchAllProviders,nc as fetchAnthropicCosts,Wg as fetchAnthropicWorkspaces,sc as fetchCursorSpend,rc as fetchOpenAICosts,Yg as fetchOpenAIProjects,Us as figmaSkill,Ib as functionSkill,qa as gbrainSkill,bI as getAllSkills,yI as getSkill,Te as gitSkill,co as gitWriteSkill,Ve as githubSkill,Xe as gitlabSkill,yi as googleDocsSkill,Vg as groupByKey,gI as hasSkill,Ds as hubspotSkill,Ss as jiraSkill,Eo as kvMemorySkill,Ei as larkAttendanceSkill,Ii as larkDocsSkill,F as larkSkill,Js as linearSkill,pi as linkedinSkill,_I as listSkillIds,Xg as meanStddev,$i as memorySkill,ai as notionSkill,Wn as openaiBillingSkill,Zs as opendesignSkill,zs as planeSkill,fI as registerSkill,Go as reportCheckSkill,Mt as reportObjectSchema,ab as reportToBlockKit,cb as reportToLarkCard,ub as reportToMarkdown,pb as reportToNotionBlocks,no as runnerSkill,hr as sentrySkill,cc as skill,Pi as skillInstallerSkill,U as slackSkill,Oa as socialCardSkill,no as testRunnerSkill,Hs as vikunjaSkill,Qa as workflowBuilderSkill};
|