@zibby/skills 0.1.94 → 0.1.95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ ${"#".repeat(s)} ${n.trim()}
21
21
  ${n}
22
22
  `):t.push(n)}return t.join("").replace(/\n{3,}/g,`
23
23
 
24
- `)}function Ee(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Gt(r){return Ee(r).replace(/[a-z0-9]+/g,"")}function at(r,e){let t=Ee(r),i=Ee(e);if(!t||!i)return 0;if(t===i)return 1;if(t.length===1||i.length===1)return t===i?1:0;let n=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=n(t),o=n(i),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of s.entries()){let u=o.get(l)||0;a+=Math.min(p,u)}return 2*a/Math.max(1,c+d)}function pe(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function yo(r,e=[]){let t=Array.isArray(e)?e:[];if(t.length===0)return{requested:r||null,resolved:null,strategy:"none"};let i=t.filter(a=>!a.subtask),n=i.length>0?i:t,s=pe(r);if(s){let a=n.find(l=>pe(l.name)===s);if(a)return{requested:r,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(u=>pe(u)===s))continue;let p=n.find(u=>l.some(m=>pe(m)===pe(u.name)));if(p)return{requested:r,resolved:p,strategy:"alias"}}let d=n.map(l=>({t:l,score:at(r,l.name)})).sort((l,p)=>p.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:r,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=n.find(d=>pe(d.name)===a);if(c)return{requested:r||null,resolved:c,strategy:"default-preferred"}}return{requested:r||null,resolved:n[0],strategy:"default-first"}}async function Fr(r){let e=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,t=await j(`/rest/api/3/issue/createmeta?${e}`),i=Array.isArray(t?.projects)?t.projects:[],s=i.find(a=>String(a?.key||"").toUpperCase()===String(r||"").toUpperCase())||i[0]||null;return(Array.isArray(s?.issuetypes)?s.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function Kr(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 i=`project = ${r} AND ${t} ORDER BY updated DESC`,n=`jql=${encodeURIComponent(i)}&maxResults=100&fields=customfield_10020`,s=await j(`/rest/api/3/search/jql?${n}`),o=new Map;for(let a of s.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let d={active:0,future:1,closed:2},l=(d[a.state]??3)-(d[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function _o(r,{sprintId:e,sprintName:t,target:i}={}){let n=Array.isArray(r)?r:[];if(!n.length)return{sprint:null,selectedBy:"none"};if(e!=null&&String(e).trim()!=="")return{sprint:n.find(a=>String(a.id)===String(e))||null,selectedBy:"id"};if(t&&String(t).trim()){let o=String(t).trim(),a=n.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=n.map(d=>({s:d,score:at(o,d.name||"")})).sort((d,l)=>l.score-d.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let s=String(i||"current").trim().toLowerCase();return s==="active"||s==="current"||s==="latest"?{sprint:n[0],selectedBy:s}:{sprint:n[0],selectedBy:"default"}}function bo(r,e){let t=r?.fields?.customfield_10020;return Array.isArray(t)?t.some(i=>String(i?.id)===String(e)):!1}async function ko({issueKey:r,projectKey:e,sprintId:t,attempts:i=3,delayMs:n=450}){let s=[];for(let o=0;o<i;o++){try{let a=`project = ${e} AND key = ${r} AND sprint = ${t}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,d=await j(`/rest/api/3/search/jql?${c}`);if(Number(d?.total||0)>0)return s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let p=await j(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),u=bo(p,t);if(s.push({attempt:o+1,jql:!1,issueField:u}),u)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<i-1&&await new Promise(a=>setTimeout(a,n))}return{ok:!1,method:"none",traces:s}}async function Ht({issueKey:r,projectKey:e,sprintId:t,sprintName:i,target:n}){if(!r)return{ok:!1,error:"issueKey is required"};let s=e;if(!s&&(s=(await j(`/rest/api/3/issue/${r}?fields=project`))?.fields?.project?.key||null,!s))return{ok:!1,error:`Could not resolve project for ${r}`};let o=await Kr(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=_o(o,{sprintId:t,sprintName:i,target:n});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:t??null,sprintName:i??null,target:n??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await j(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await ko({issueKey:r,projectKey:s,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:r,projectKey:s,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:d.method,verified:l,verificationTrace:d.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${r} in sprint ${a.id}`}}async function j(r,e={}){let t=async()=>{let{token:i,cloudId:n}=await po("jira");if(typeof i!="string"||!i)throw new Error(`Invalid jira token type: ${typeof i}`);if(!n)throw new Error("Invalid jira cloudId: missing");let s=`https://api.atlassian.com/ex/jira/${n}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let a=await o.text().catch(()=>"");if(!a||!a.trim())return{};try{return JSON.parse(a)}catch{return{raw:a}}};try{return await t()}catch(i){let n=String(i?.message||i||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("403")||n.includes("substring")))throw i;return uo("jira"),t()}}var Gr={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:N.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
24
+ `)}function Ee(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Kt(r){return Ee(r).replace(/[a-z0-9]+/g,"")}function at(r,e){let t=Ee(r),i=Ee(e);if(!t||!i)return 0;if(t===i)return 1;if(t.length===1||i.length===1)return t===i?1:0;let n=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},s=n(t),o=n(i),a=0,c=0,d=0;for(let l of s.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of s.entries()){let u=o.get(l)||0;a+=Math.min(p,u)}return 2*a/Math.max(1,c+d)}function pe(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function yo(r,e=[]){let t=Array.isArray(e)?e:[];if(t.length===0)return{requested:r||null,resolved:null,strategy:"none"};let i=t.filter(a=>!a.subtask),n=i.length>0?i:t,s=pe(r);if(s){let a=n.find(l=>pe(l.name)===s);if(a)return{requested:r,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(u=>pe(u)===s))continue;let p=n.find(u=>l.some(m=>pe(m)===pe(u.name)));if(p)return{requested:r,resolved:p,strategy:"alias"}}let d=n.map(l=>({t:l,score:at(r,l.name)})).sort((l,p)=>p.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:r,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=n.find(d=>pe(d.name)===a);if(c)return{requested:r||null,resolved:c,strategy:"default-preferred"}}return{requested:r||null,resolved:n[0],strategy:"default-first"}}async function Fr(r){let e=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,t=await j(`/rest/api/3/issue/createmeta?${e}`),i=Array.isArray(t?.projects)?t.projects:[],s=i.find(a=>String(a?.key||"").toUpperCase()===String(r||"").toUpperCase())||i[0]||null;return(Array.isArray(s?.issuetypes)?s.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function Kr(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 i=`project = ${r} AND ${t} ORDER BY updated DESC`,n=`jql=${encodeURIComponent(i)}&maxResults=100&fields=customfield_10020`,s=await j(`/rest/api/3/search/jql?${n}`),o=new Map;for(let a of s.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let d={active:0,future:1,closed:2},l=(d[a.state]??3)-(d[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function _o(r,{sprintId:e,sprintName:t,target:i}={}){let n=Array.isArray(r)?r:[];if(!n.length)return{sprint:null,selectedBy:"none"};if(e!=null&&String(e).trim()!=="")return{sprint:n.find(a=>String(a.id)===String(e))||null,selectedBy:"id"};if(t&&String(t).trim()){let o=String(t).trim(),a=n.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=n.map(d=>({s:d,score:at(o,d.name||"")})).sort((d,l)=>l.score-d.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let s=String(i||"current").trim().toLowerCase();return s==="active"||s==="current"||s==="latest"?{sprint:n[0],selectedBy:s}:{sprint:n[0],selectedBy:"default"}}function bo(r,e){let t=r?.fields?.customfield_10020;return Array.isArray(t)?t.some(i=>String(i?.id)===String(e)):!1}async function ko({issueKey:r,projectKey:e,sprintId:t,attempts:i=3,delayMs:n=450}){let s=[];for(let o=0;o<i;o++){try{let a=`project = ${e} AND key = ${r} AND sprint = ${t}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,d=await j(`/rest/api/3/search/jql?${c}`);if(Number(d?.total||0)>0)return s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let p=await j(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),u=bo(p,t);if(s.push({attempt:o+1,jql:!1,issueField:u}),u)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<i-1&&await new Promise(a=>setTimeout(a,n))}return{ok:!1,method:"none",traces:s}}async function Gt({issueKey:r,projectKey:e,sprintId:t,sprintName:i,target:n}){if(!r)return{ok:!1,error:"issueKey is required"};let s=e;if(!s&&(s=(await j(`/rest/api/3/issue/${r}?fields=project`))?.fields?.project?.key||null,!s))return{ok:!1,error:`Could not resolve project for ${r}`};let o=await Kr(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=_o(o,{sprintId:t,sprintName:i,target:n});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:t??null,sprintName:i??null,target:n??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await j(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await ko({issueKey:r,projectKey:s,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:r,projectKey:s,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:d.method,verified:l,verificationTrace:d.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${r} in sprint ${a.id}`}}async function j(r,e={}){let t=async()=>{let{token:i,cloudId:n}=await po("jira");if(typeof i!="string"||!i)throw new Error(`Invalid jira token type: ${typeof i}`);if(!n)throw new Error("Invalid jira cloudId: missing");let s=`https://api.atlassian.com/ex/jira/${n}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let a=await o.text().catch(()=>"");if(!a||!a.trim())return{};try{return JSON.parse(a)}catch{return{raw:a}}};try{return await t()}catch(i){let n=String(i?.message||i||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("403")||n.includes("substring")))throw i;return uo("jira"),t()}}var Gr={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:N.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
25
25
  You have direct access to the user's Jira. Use these tools proactively:
26
26
 
27
27
  ### Issue tools
@@ -71,7 +71,7 @@ When user asks to move/transition ticket status:
71
71
  3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
72
72
  4. Call jira_get_issue(issueKey) to verify final status before claiming success.
73
73
  5. If target wording differs (e.g. \u5DF2\u7ECF\u9A8C\u6536 vs \u5DF2\u9A8C\u6536), try toStatus first; only ask user to confirm when no reasonable match exists.
74
- 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=fo();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 j("/rest/api/3/project"),i=(Array.isArray(t)?t:[]).map(n=>({id:n.id,key:n.key,name:n.name,style:n.style}));return JSON.stringify({count:i.length,projects:i})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await j(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let i=await j("/rest/api/3/status"),n=(Array.isArray(i)?i:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:n.length,statuses:n})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let i=await Fr(t);return JSON.stringify({projectKey:t,count:i.length,issueTypes:i})}case"jira_search":{let t=e.jql||"",i=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${i}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await j(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let i=await j(`/rest/api/3/issue/${t}`);return JSON.stringify({key:i.key,project:i.fields?.project?.key,summary:i.fields?.summary,description:i.fields?.description,status:i.fields?.status?.name,assignee:i.fields?.assignee?.displayName||"Unassigned",priority:i.fields?.priority?.name,type:i.fields?.issuetype?.name,labels:i.fields?.labels,created:i.fields?.created,updated:i.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:i,issueType:n,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=e;if(!t||!i)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:n||null,resolved:null,strategy:"none"},h=[];try{h=await Fr(t),f=yo(n,h)}catch{}let b={project:{key:t},summary:i,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:n||"Task"}};s&&(b.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(b.priority={name:o}),a?.length&&(b.labels=a),c&&(b.assignee={id:c});let y=await j("/rest/api/3/issue",{method:"POST",body:{fields:b}}),_={ok:!0,key:y.key,id:y.id,self:y.self};return f?.resolved&&(_.issueType=f.resolved.name,_.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&pe(f.requested)!==pe(f.resolved.name)&&(_.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(_.availableIssueTypes=h.map(g=>g.name)),(d||l)&&(_.sprintMove=await Ht({issueKey:y.key,projectKey:t,sprintId:p,sprintName:u,target:m})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:t,state:i}=e,n=await Kr(t,i);return JSON.stringify({count:n.length,sprints:n})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:i,sprintId:n,sprintName:s,target:o}=e||{},a=await Ht({issueKey:t,projectKey:i,sprintId:n,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:i,sprintId:n,sprintName:s,target:o}=e||{},a=await Ht({issueKey:t,projectKey:i,sprintId:n,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:i,projectKey:n,status:s,maxResults:o}=e;if(!t&&!i)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=i?`sprint = ${i}`:`sprint = "${t}"`,d=n?`project = ${n} AND `:"",l=s?` AND status = "${s}"`:"",p=`${d}${c}${l} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await j(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(b=>({key:b.key,project:b.fields?.project?.key,summary:b.fields?.summary,status:b.fields?.status?.name,assignee:b.fields?.assignee?.displayName||"Unassigned",priority:b.fields?.priority?.name,type:b.fields?.issuetype?.name})),h={};for(let b of f)h[b.status]=(h[b.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:t,maxResults:i}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await j(`/rest/api/3/issue/${t}/comment?maxResults=${i||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=ot(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:i}=e;return!t||!i?JSON.stringify({error:"issueKey and body are required"}):(await j(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:i}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:i}=e;return!t||!i?JSON.stringify({error:"issueKey and fields are required"}):(await j(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:i}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:i,toStatus:n,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(n||s||o||"").trim();if(!i&&!a){let p=((await j(`/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=i;if(!c){let p=(await j(`/rest/api/3/issue/${t}/transitions`)).transitions||[],u=Ee(a),m=p.find(f=>Ee(f?.name||"")===u||Ee(f?.to?.name||"")===u);if(!m){let f=Gt(a);f.length>=2&&(m=p.find(h=>{let b=Gt(h?.name||""),y=Gt(h?.to?.name||""),_=b.length>=2&&(b.includes(f)||f.includes(b)),g=y.length>=2&&(y.includes(f)||f.includes(y));return _||g}))}if(!m){let f=p.map(_=>{let g=at(a,_?.name||""),k=at(a,_?.to?.name||"");return{t:_,score:Math.max(g,k)}}).sort((_,g)=>g.score-_.score),h=f[0],b=f[1];h&&h.score>=.45&&(!b||h.score-b.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await j(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await j(`/rest/api/3/issue/${t}?fields=status`);return JSON.stringify({ok:!0,issueKey:t,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as Po}from"fs";import{fileURLToPath as Co}from"url";import{dirname as Uo,resolve as Jo}from"path";import{resolveIntegrationToken as Wr}from"@zibby/core/backend-client.js";import{spawn as wo,execSync as So}from"child_process";import{existsSync as V,mkdirSync as vo,readdirSync as Hr,statSync as Io,readFileSync as No}from"fs";import{resolve as zt,join as Q,basename as Oo}from"path";var Yt=".zibby/repos";function Ro(r){let e=String(r??"");for(let t of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])t&&(e=e.split(t).join("***"));return e.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,t=>t.replace(/:[^@\s]+@/,":***@"))}function Fe(r,e,t,i,n="clone"){try{r(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);i&&(o=o.split(i).join("***")),console.error(`[${n}] WARNING: failed to strip token from .git/config: ${o}`)}}function ct(r,e,t={}){return new Promise((i,n)=>{let s=wo(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?n(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):i(o.trim())}),s.on("error",c=>n(c))})}var ue={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
74
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=fo();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 j("/rest/api/3/project"),i=(Array.isArray(t)?t:[]).map(n=>({id:n.id,key:n.key,name:n.name,style:n.style}));return JSON.stringify({count:i.length,projects:i})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await j(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let i=await j("/rest/api/3/status"),n=(Array.isArray(i)?i:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:n.length,statuses:n})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let i=await Fr(t);return JSON.stringify({projectKey:t,count:i.length,issueTypes:i})}case"jira_search":{let t=e.jql||"",i=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${i}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await j(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let i=await j(`/rest/api/3/issue/${t}`);return JSON.stringify({key:i.key,project:i.fields?.project?.key,summary:i.fields?.summary,description:i.fields?.description,status:i.fields?.status?.name,assignee:i.fields?.assignee?.displayName||"Unassigned",priority:i.fields?.priority?.name,type:i.fields?.issuetype?.name,labels:i.fields?.labels,created:i.fields?.created,updated:i.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:i,issueType:n,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=e;if(!t||!i)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:n||null,resolved:null,strategy:"none"},h=[];try{h=await Fr(t),f=yo(n,h)}catch{}let b={project:{key:t},summary:i,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:n||"Task"}};s&&(b.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(b.priority={name:o}),a?.length&&(b.labels=a),c&&(b.assignee={id:c});let y=await j("/rest/api/3/issue",{method:"POST",body:{fields:b}}),_={ok:!0,key:y.key,id:y.id,self:y.self};return f?.resolved&&(_.issueType=f.resolved.name,_.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&pe(f.requested)!==pe(f.resolved.name)&&(_.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(_.availableIssueTypes=h.map(g=>g.name)),(d||l)&&(_.sprintMove=await Gt({issueKey:y.key,projectKey:t,sprintId:p,sprintName:u,target:m})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:t,state:i}=e,n=await Kr(t,i);return JSON.stringify({count:n.length,sprints:n})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:i,sprintId:n,sprintName:s,target:o}=e||{},a=await Gt({issueKey:t,projectKey:i,sprintId:n,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:i,sprintId:n,sprintName:s,target:o}=e||{},a=await Gt({issueKey:t,projectKey:i,sprintId:n,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:i,projectKey:n,status:s,maxResults:o}=e;if(!t&&!i)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=i?`sprint = ${i}`:`sprint = "${t}"`,d=n?`project = ${n} AND `:"",l=s?` AND status = "${s}"`:"",p=`${d}${c}${l} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await j(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(b=>({key:b.key,project:b.fields?.project?.key,summary:b.fields?.summary,status:b.fields?.status?.name,assignee:b.fields?.assignee?.displayName||"Unassigned",priority:b.fields?.priority?.name,type:b.fields?.issuetype?.name})),h={};for(let b of f)h[b.status]=(h[b.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:t,maxResults:i}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await j(`/rest/api/3/issue/${t}/comment?maxResults=${i||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=ot(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:i}=e;return!t||!i?JSON.stringify({error:"issueKey and body are required"}):(await j(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:i}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:i}=e;return!t||!i?JSON.stringify({error:"issueKey and fields are required"}):(await j(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:i}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:i,toStatus:n,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(n||s||o||"").trim();if(!i&&!a){let p=((await j(`/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=i;if(!c){let p=(await j(`/rest/api/3/issue/${t}/transitions`)).transitions||[],u=Ee(a),m=p.find(f=>Ee(f?.name||"")===u||Ee(f?.to?.name||"")===u);if(!m){let f=Kt(a);f.length>=2&&(m=p.find(h=>{let b=Kt(h?.name||""),y=Kt(h?.to?.name||""),_=b.length>=2&&(b.includes(f)||f.includes(b)),g=y.length>=2&&(y.includes(f)||f.includes(y));return _||g}))}if(!m){let f=p.map(_=>{let g=at(a,_?.name||""),k=at(a,_?.to?.name||"");return{t:_,score:Math.max(g,k)}}).sort((_,g)=>g.score-_.score),h=f[0],b=f[1];h&&h.score>=.45&&(!b||h.score-b.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await j(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await j(`/rest/api/3/issue/${t}?fields=status`);return JSON.stringify({ok:!0,issueKey:t,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as Po}from"fs";import{fileURLToPath as Co}from"url";import{dirname as Uo,resolve as Jo}from"path";import{resolveIntegrationToken as Wr}from"@zibby/core/backend-client.js";import{spawn as wo,execSync as So}from"child_process";import{existsSync as V,mkdirSync as vo,readdirSync as Hr,statSync as Io,readFileSync as No}from"fs";import{resolve as Ht,join as Q,basename as Oo}from"path";var zt=".zibby/repos";function Ro(r){let e=String(r??"");for(let t of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])t&&(e=e.split(t).join("***"));return e.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,t=>t.replace(/:[^@\s]+@/,":***@"))}function Fe(r,e,t,i,n="clone"){try{r(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);i&&(o=o.split(i).join("***")),console.error(`[${n}] WARNING: failed to strip token from .git/config: ${o}`)}}function ct(r,e,t={}){return new Promise((i,n)=>{let s=wo(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?n(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):i(o.trim())}),s.on("error",c=>n(c))})}var ue={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
75
75
  You can clone and explore git repositories locally for codebase analysis:
76
76
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
77
77
  - git_list_repos: List locally cloned repos
@@ -82,7 +82,7 @@ When a test ticket lacks context, use this workflow:
82
82
  2. Use git_explore to understand the project structure
83
83
  3. Use shell commands (grep, cat) to read specific files for deeper understanding
84
84
  4. Use GitHub/GitLab skills to read related PRs and commits
85
- 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(r,e,t){let i=t?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await To(e,i);case"git_list_repos":return Ao(e,i);case"git_explore":return Eo(e,i);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(n){return JSON.stringify({error:Ro(n.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 To(r,e){let{url:t,branch:i,shallow:n=!0,name:s}=r;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=s||Oo(t.replace(/\.git$/,"")),a=zt(e,Yt);vo(a,{recursive:!0});let c=Q(a,o),d=t,l=process.env.GITHUB_TOKEN,p=process.env.GITLAB_TOKEN,u=process.env.GITLAB_URL;if(t.includes("github.com")&&l)d=t.replace("https://github.com",`https://x-access-token:${l}@github.com`);else if(p&&u)try{let h=new URL(u).host;t.includes(h)&&(d=t.replace(`https://${h}`,`https://oauth2:${p}@${h}`))}catch{}if(V(Q(c,".git"))){let h=i?`git -C "${c}" fetch "${d}" ${i} && git -C "${c}" checkout ${i} && git -C "${c}" merge --ff-only FETCH_HEAD`:`git -C "${c}" pull "${d}"`;await ct(h,e);let b=await ct(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:i||"default",head:b})}let m=["git","clone"];n&&m.push("--depth","1"),i&&m.push("--branch",i),m.push(`"${d}"`,`"${c}"`),await ct(m.join(" "),e),Fe(So,c,t,l||p,"git_checkout");let f=await ct(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:i||"default",shallow:n,head:f})}function Ao(r,e){let t=zt(e,Yt);if(!V(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let i=[];for(let n of Hr(t,{withFileTypes:!0})){if(!n.isDirectory())continue;let s=Q(t,n.name);if(!V(Q(s,".git")))continue;let o=Io(s);i.push({name:n.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:i,total:i.length,directory:t})}function Eo(r,e){let{repo:t,depth:i=2}=r,n=zt(e,Yt,t);if(!V(n))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let s={repo:t,path:n},o=Q(n,"package.json");if(V(o))try{let m=JSON.parse(No(o,"utf-8"));s.packageJson={name:m.name,version:m.version,scripts:m.scripts?Object.keys(m.scripts):[],dependencies:m.dependencies?Object.keys(m.dependencies).slice(0,30):[],devDependencies:m.devDependencies?Object.keys(m.devDependencies).slice(0,20):[]},m.dependencies?.react?s.framework="React":m.dependencies?.next?s.framework="Next.js":m.dependencies?.vue?s.framework="Vue":m.dependencies?.angular?s.framework="Angular":m.dependencies?.express?s.framework="Express":m.dependencies?.fastify&&(s.framework="Fastify")}catch{}let a=Q(n,"pyproject.toml");V(a)&&(s.language="Python");let c=Q(n,"go.mod");V(c)&&(s.language="Go");let d=Q(n,"Cargo.toml");V(d)&&(s.language="Rust"),V(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function p(m,f,h){if(h>i)return;let b;try{b=Hr(m,{withFileTypes:!0})}catch{return}let y=b.filter(_=>!_.name.startsWith(".")&&_.name!=="node_modules"&&_.name!=="__pycache__"&&_.name!=="dist"&&_.name!=="build"&&_.name!==".git").sort((_,g)=>_.isDirectory()!==g.isDirectory()?_.isDirectory()?-1:1:_.name.localeCompare(g.name));for(let _ of y){let g=_.isDirectory();l.push(`${f}${g?"\u{1F4C1}":"\u{1F4C4}"} ${_.name}`),g&&h<i&&p(Q(m,_.name),`${f} `,h+1)}}p(n,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let u=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return s.keyFilesFound=u.filter(m=>V(Q(n,m))),JSON.stringify(s)}import xo from"crypto";var zr=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,Yr=/<!--\s*zbreview-summary\s*-->/i;function jo(r){return String(r||"").replace(zr,"").replace(Yr,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function Lo(r,e){return xo.createHash("sha256").update(`${String(r||"")}\0${jo(e)}`).digest("hex").slice(0,12)}function $o(r){return`
85
+ 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(r,e,t){let i=t?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await To(e,i);case"git_list_repos":return Ao(e,i);case"git_explore":return Eo(e,i);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(n){return JSON.stringify({error:Ro(n.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 To(r,e){let{url:t,branch:i,shallow:n=!0,name:s}=r;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=s||Oo(t.replace(/\.git$/,"")),a=Ht(e,zt);vo(a,{recursive:!0});let c=Q(a,o),d=t,l=process.env.GITHUB_TOKEN,p=process.env.GITLAB_TOKEN,u=process.env.GITLAB_URL;if(t.includes("github.com")&&l)d=t.replace("https://github.com",`https://x-access-token:${l}@github.com`);else if(p&&u)try{let h=new URL(u).host;t.includes(h)&&(d=t.replace(`https://${h}`,`https://oauth2:${p}@${h}`))}catch{}if(V(Q(c,".git"))){let h=i?`git -C "${c}" fetch "${d}" ${i} && git -C "${c}" checkout ${i} && git -C "${c}" merge --ff-only FETCH_HEAD`:`git -C "${c}" pull "${d}"`;await ct(h,e);let b=await ct(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:i||"default",head:b})}let m=["git","clone"];n&&m.push("--depth","1"),i&&m.push("--branch",i),m.push(`"${d}"`,`"${c}"`),await ct(m.join(" "),e),Fe(So,c,t,l||p,"git_checkout");let f=await ct(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:i||"default",shallow:n,head:f})}function Ao(r,e){let t=Ht(e,zt);if(!V(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let i=[];for(let n of Hr(t,{withFileTypes:!0})){if(!n.isDirectory())continue;let s=Q(t,n.name);if(!V(Q(s,".git")))continue;let o=Io(s);i.push({name:n.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:i,total:i.length,directory:t})}function Eo(r,e){let{repo:t,depth:i=2}=r,n=Ht(e,zt,t);if(!V(n))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let s={repo:t,path:n},o=Q(n,"package.json");if(V(o))try{let m=JSON.parse(No(o,"utf-8"));s.packageJson={name:m.name,version:m.version,scripts:m.scripts?Object.keys(m.scripts):[],dependencies:m.dependencies?Object.keys(m.dependencies).slice(0,30):[],devDependencies:m.devDependencies?Object.keys(m.devDependencies).slice(0,20):[]},m.dependencies?.react?s.framework="React":m.dependencies?.next?s.framework="Next.js":m.dependencies?.vue?s.framework="Vue":m.dependencies?.angular?s.framework="Angular":m.dependencies?.express?s.framework="Express":m.dependencies?.fastify&&(s.framework="Fastify")}catch{}let a=Q(n,"pyproject.toml");V(a)&&(s.language="Python");let c=Q(n,"go.mod");V(c)&&(s.language="Go");let d=Q(n,"Cargo.toml");V(d)&&(s.language="Rust"),V(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function p(m,f,h){if(h>i)return;let b;try{b=Hr(m,{withFileTypes:!0})}catch{return}let y=b.filter(_=>!_.name.startsWith(".")&&_.name!=="node_modules"&&_.name!=="__pycache__"&&_.name!=="dist"&&_.name!=="build"&&_.name!==".git").sort((_,g)=>_.isDirectory()!==g.isDirectory()?_.isDirectory()?-1:1:_.name.localeCompare(g.name));for(let _ of y){let g=_.isDirectory();l.push(`${f}${g?"\u{1F4C1}":"\u{1F4C4}"} ${_.name}`),g&&h<i&&p(Q(m,_.name),`${f} `,h+1)}}p(n,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let u=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return s.keyFilesFound=u.filter(m=>V(Q(n,m))),JSON.stringify(s)}import xo from"crypto";var zr=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,Yr=/<!--\s*zbreview-summary\s*-->/i;function jo(r){return String(r||"").replace(zr,"").replace(Yr,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function Lo(r,e){return xo.createHash("sha256").update(`${String(r||"")}\0${jo(e)}`).digest("hex").slice(0,12)}function $o(r){return`
86
86
 
87
87
  <!-- zbfp:${r} -->`}var lt=`
88
88
 
@@ -159,7 +159,7 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
159
159
  - 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.
160
160
  - 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=Ko();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/gitlab.js","gitlabSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gitlab_clone":{let{projectPath:t,projectId:i,destination:n,branch:s}=e||{},o=t&&String(t).trim();if(!o&&i!=null&&(/^\d+$/.test(String(i))?o=(await T(`/projects/${L(i)}`))?.path_with_namespace:o=String(i).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=zo();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:d,resolve:l}=await import("path"),{existsSync:p,mkdirSync:u}=await import("fs"),m=n?l(n):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(u(m,{recursive:!0}),p(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let b=Zr().replace(/^https?:\/\//,""),y=Zr().startsWith("http://")?"http":"https",_=`${y}://oauth2:${a}@${b}/${o}.git`,g=s?`--branch "${String(s).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${g}${_} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let k=`${y}://${b}/${o}.git`;Fe(c,h,k,a,"gitlab_clone");let O=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:O.split(`
161
161
  `).slice(0,30).join(`
162
- `)})}catch(k){let O=String(k.message||k).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${O}`})}}case"gitlab_create_mr":{let t=e?.project??e?.projectId,i=e?.source_branch??e?.sourceBranch,{title:n}=e||{};if(!t||!i||!n)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let s=L(t),o=e?.target_branch??e?.targetBranch;if(!o)try{o=(await T(`/projects/${s}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(i),target_branch:String(o),title:String(n),description:e?.description?String(e.description):""};try{let c=await T(`/projects/${s}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(t),provider:"gitlab",state:c.state})}catch(c){let d=String(c.message||c);if(/GitLab API (409|400)/.test(d))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(t),provider:"gitlab",skippedReason:d});throw c}}case"gitlab_accept_mr":{let t=e?.project??e?.projectId,{iid:i}=e||{};if(!t||!i)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let n=L(t),s={};e.squash!=null&&(s.squash=!!e.squash),e.mergeCommitMessage&&(s.merge_commit_message=String(e.mergeCommitMessage)),e.mergeWhenPipelineSucceeds!=null&&(s.merge_when_pipeline_succeeds=!!e.mergeWhenPipelineSucceeds);try{let o=await T(`/projects/${n}/merge_requests/${i}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??i,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:i,project:String(t),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:t,iid:i}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let n=await T(`/projects/${L(t)}/merge_requests/${i}`);return JSON.stringify({iid:n.iid,projectId:n.project_id,title:n.title,description:(n.description||"").slice(0,5e3),state:n.state,author:n.author?.username,sourceBranch:n.source_branch,targetBranch:n.target_branch,draft:n.draft??n.work_in_progress??!1,mergeStatus:n.merge_status,changesCount:n.changes_count,labels:Array.isArray(n.labels)?n.labels:[],webUrl:n.web_url,createdAt:n.created_at,updatedAt:n.updated_at,mergedAt:n.merged_at,diffRefs:n.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:t,iid:i}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let n=await T(`/projects/${L(t)}/merge_requests/${i}/changes`),s=Array.isArray(n.changes)?n.changes:[];return JSON.stringify({iid:n.iid,total:s.length,diffRefs:n.diff_refs||null,files:s.map(o=>({oldPath:o.old_path,newPath:o.new_path,newFile:!!o.new_file,deletedFile:!!o.deleted_file,renamedFile:!!o.renamed_file,diff:typeof o.diff=="string"?o.diff.slice(0,3e3):""}))})}case"gitlab_list_commits":{let{projectId:t,since:i,until:n,refName:s,page:o,perPage:a,withStats:c}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let d=new URLSearchParams;d.set("per_page",String(Math.min(Number(a)||50,100))),d.set("page",String(Number(o)||1)),i&&d.set("since",i),n&&d.set("until",n),s&&d.set("ref_name",s),c!==!1&&d.set("with_stats","true");let l=await T(`/projects/${L(t)}/repository/commits?${d.toString()}`),p=(Array.isArray(l)?l:[]).map(u=>({id:u.id,shortId:u.short_id,title:u.title,authorName:u.author_name,authorEmail:u.author_email,authoredDate:u.authored_date,committedDate:u.committed_date,parentIds:Array.isArray(u.parent_ids)?u.parent_ids:[],stats:u.stats||null}));return JSON.stringify({page:Number(o)||1,count:p.length,hasMore:p.length>=Math.min(Number(a)||50,100),commits:p})}case"gitlab_get_commit":{let{projectId:t,sha:i,includeDiff:n,includeMrs:s}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and sha are required"});let o=await T(`/projects/${L(t)}/repository/commits/${encodeURIComponent(i)}`),a;if(s)try{let d=await T(`/projects/${L(t)}/repository/commits/${encodeURIComponent(i)}/merge_requests`);a=(Array.isArray(d)?d:[]).map(l=>({iid:l.iid,title:l.title,state:l.state,webUrl:l.web_url}))}catch{a=[]}let c;if(n!==!1){let d=await T(`/projects/${L(t)}/repository/commits/${encodeURIComponent(i)}/diff`);c=(Array.isArray(d)?d:[]).map(l=>({oldPath:l.old_path,newPath:l.new_path,newFile:!!l.new_file,deletedFile:!!l.deleted_file,renamedFile:!!l.renamed_file,diff:typeof l.diff=="string"?l.diff.slice(0,3e3):""}))}return JSON.stringify({id:o.id,shortId:o.short_id,title:o.title,message:typeof o.message=="string"?o.message.slice(0,2e3):"",authorName:o.author_name,authorEmail:o.author_email,authoredDate:o.authored_date,committedDate:o.committed_date,parentIds:Array.isArray(o.parent_ids)?o.parent_ids:[],stats:o.stats||null,webUrl:o.web_url,...c?{filesChanged:c.length,files:c}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:t,state:i,targetBranch:n,sourceBranch:s,authorUsername:o,labels:a,search:c,sort:d,orderBy:l,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",i||"opened"),u.set("per_page",String(p||20)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),n&&u.set("target_branch",n),s&&u.set("source_branch",s),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await T(`/projects/${L(t)}/merge_requests?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:t,iid:i,limit:n}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let s=await T(`/projects/${L(t)}/merge_requests/${i}/notes?per_page=${n||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(s)?s.length:0,notes:(Array.isArray(s)?s:[]).map(o=>({id:o.id,author:o.author?.username,body:(o.body||"").slice(0,1e3),system:!!o.system,createdAt:o.created_at}))})}case"gitlab_post_mr_note":{let{projectId:t,iid:i,body:n}=e||{};if(!t||!i||!n)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await T(`/projects/${L(t)}/merge_requests/${i}/notes`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:i,path:n,oldPath:s,newLine:o,oldLine:a,body:c}=e||{};if(!t||!i||!n||!c)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(o==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let d=L(t),l=e.diffRefs||null;if(l||(l=(await T(`/projects/${d}/merge_requests/${i}`)).diff_refs||null),!l||!l.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let p={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:n,old_path:s||n};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await T(`/projects/${d}/merge_requests/${i}/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:i,body:n,comments:s}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let o=L(t),a=Array.isArray(s)?s.filter(y=>y&&y.path&&y.body&&(y.newLine!=null||y.oldLine!=null)):[];if(!n&&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 T(`/projects/${o}/merge_requests/${i}`)).diff_refs||null);let d=new Set,l=null;try{for(let y=1;y<=20;y+=1){let _=await T(`/projects/${o}/merge_requests/${i}/discussions?per_page=100&page=${y}`);if(!Array.isArray(_)||_.length===0)break;for(let g of _)for(let k of g.notes||[]){let O=dt(k.body);O&&d.add(O),l==null&&pt(k.body)&&(l=k.id)}if(_.length<100)break}}catch{}let p=!1,u=!1;if(n){let y=`${String(n)}${lt}`;try{l!=null?(await T(`/projects/${o}/merge_requests/${i}/notes/${l}`,{method:"PUT",body:{body:y}}),u=!0):await T(`/projects/${o}/merge_requests/${i}/notes`,{method:"POST",body:{body:y}}),p=!0}catch{await T(`/projects/${o}/merge_requests/${i}/notes`,{method:"POST",body:{body:y}}),p=!0}}let{toPost:m,skipped:f}=ut(a,d),h=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 T(`/projects/${o}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(y.body),position:_}}),h+=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:h,inlineSkipped:f||void 0,inlineErrors:b.length?b:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:i,discussionId:n}=e||{};if(!t||!i||!n)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let s=await T(`/projects/${L(t)}/merge_requests/${i}/discussions/${encodeURIComponent(n)}`),o=Array.isArray(s.notes)?s.notes:[],a=o.find(d=>d.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:s.id,individualNote:!!s.individual_note,path:c&&(c.new_path||c.old_path)||null,newLine:c?c.new_line??null:null,oldLine:c?c.old_line??null:null,diffRefs:c?{base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha}:null,notes:o.map(d=>({id:d.id,author:d.author?.username,body:(d.body||"").slice(0,4e3),system:!!d.system,createdAt:d.created_at}))})}case"gitlab_reply_discussion":{let{projectId:t,iid:i,discussionId:n,body:s}=e||{};if(!t||!i||!n||!s)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await T(`/projects/${L(t)}/merge_requests/${i}/discussions/${encodeURIComponent(n)}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:t,limit:i}=e||{},n=Math.min(Number(i)>0?Number(i):50,200),s=new URLSearchParams;s.set("membership","true"),s.set("simple","true"),s.set("order_by","last_activity_at"),s.set("sort","desc"),s.set("per_page",String(Math.min(n+1,100))),t&&s.set("search",String(t));let o=await T(`/projects?${s.toString()}`),a=Array.isArray(o)?o:[],c=a.length>n,d=a.slice(0,n).map(l=>({fullPath:l.path_with_namespace,name:l.name,webUrl:l.web_url,defaultBranch:l.default_branch||null,visibility:l.visibility||null}));return JSON.stringify({count:d.length,truncated:c,projects:d})}case"gitlab_list_issues":{let{projectId:t,state:i,labels:n,assigneeUsername:s,authorUsername:o,updatedAfter:a,search:c,sort:d,orderBy:l,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",i||"opened"),u.set("per_page",String(p||30)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),n&&u.set("labels",Array.isArray(n)?n.join(","):n),s&&u.set("assignee_username",s),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await T(`/projects/${L(t)}/issues?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(b=>b.username),userNotesCount:h.user_notes_count,webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,issues:f})}case"gitlab_get_issue":{let{projectId:t,iid:i}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let n=await T(`/projects/${L(t)}/issues/${i}`);return JSON.stringify({iid:n.iid,projectId:n.project_id,title:n.title,description:(n.description||"").slice(0,5e3),state:n.state,labels:Array.isArray(n.labels)?n.labels:[],author:n.author?.username,assignees:(n.assignees||[]).map(s=>s.username),milestone:n.milestone?.title||null,webUrl:n.web_url,createdAt:n.created_at,updatedAt:n.updated_at,closedAt:n.closed_at})}case"gitlab_add_issue_comment":{let{projectId:t,iid:i,body:n}=e||{};if(!t||!i||!n)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await T(`/projects/${L(t)}/issues/${i}/notes`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_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 Yo}from"fs";import{fileURLToPath as Wo}from"url";import{dirname as Zo,resolve as Vo}from"path";import{resolveIntegrationToken as Qo}from"@zibby/core/backend-client.js";function Xo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Zo(Wo(import.meta.url)),e=Vo(r,"..","bin","mcp-skill.mjs");return Yo(e)?e:null}async function Y(r,e={}){let{token:t}=await Qo("figma"),i=r.startsWith("https://")?r:`https://api.figma.com${r}`,n={"X-Figma-Token":t,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(i,{method:e.method||"GET",headers:n,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Figma API ${s.status}: ${o.slice(0,300)}`)}return s.json()}function oe(r){let e=String(r||"").trim(),t=e.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return t?t[1]:e}function mt(r){return r==null?void 0:(Array.isArray(r)?r:String(r).split(",")).map(t=>String(t).trim().replace(/-/g,":")).filter(Boolean).join(",")}function ea(r){let e=String(r||"").match(/[?&]node-id=([^&]+)/i);return e?decodeURIComponent(e[1]).replace(/-/g,":"):void 0}var X=r=>typeof r=="number"?Math.round(r*100)/100:r;function Wt(r){if(!r)return null;let e=i=>Math.round((i??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=X(r.a)),t}function Vr(r){return!r||r.visible===!1?null:r.type==="SOLID"?{type:"SOLID",...Wt(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:X(e.position),...Wt(e.color)}))}:{}}}function Qr(r,e){let t=r.absoluteBoundingBox,i={id:r.id,name:r.name,type:r.type};t&&(i.size={w:X(t.width),h:X(t.height)},i.position={x:X(t.x),y:X(t.y)}),r.opacity!=null&&r.opacity!==1&&(i.opacity=r.opacity),r.cornerRadius!=null&&(i.cornerRadius=r.cornerRadius),Array.isArray(r.rectangleCornerRadii)&&(i.cornerRadii=r.rectangleCornerRadii);let n=(r.fills||[]).map(Vr).filter(Boolean);n.length&&(i.fills=n);let s=(r.strokes||[]).map(Vr).filter(Boolean);s.length&&(i.strokes=s,r.strokeWeight!=null&&(i.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:X(a.offset.x),y:X(a.offset.y)}}:{},...a.spread?{spread:a.spread}:{},...a.color?Wt(a.color):{}}));if(o.length&&(i.effects=o),r.layoutMode&&r.layoutMode!=="NONE"&&(i.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||{};i.text=r.characters,i.textStyle={fontFamily:a.fontFamily,fontWeight:a.fontWeight,fontSize:a.fontSize,lineHeightPx:a.lineHeightPx!=null?X(a.lineHeightPx):void 0,letterSpacing:a.letterSpacing!=null?X(a.letterSpacing):void 0,align:a.textAlignHorizontal,case:a.textCase}}return e>0&&Array.isArray(r.children)&&r.children.length&&(i.children=r.children.map(a=>Qr(a,e-1))),i}var Xr={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:N.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma (connected)
162
+ `)})}catch(k){let O=String(k.message||k).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${O}`})}}case"gitlab_create_mr":{let t=e?.project??e?.projectId,i=e?.source_branch??e?.sourceBranch,{title:n}=e||{};if(!t||!i||!n)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let s=L(t),o=e?.target_branch??e?.targetBranch;if(!o)try{o=(await T(`/projects/${s}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(i),target_branch:String(o),title:String(n),description:e?.description?String(e.description):""};try{let c=await T(`/projects/${s}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(t),provider:"gitlab",state:c.state})}catch(c){let d=String(c.message||c);if(/GitLab API (409|400)/.test(d))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(t),provider:"gitlab",skippedReason:d});throw c}}case"gitlab_accept_mr":{let t=e?.project??e?.projectId,{iid:i}=e||{};if(!t||!i)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let n=L(t),s={};e.squash!=null&&(s.squash=!!e.squash),e.mergeCommitMessage&&(s.merge_commit_message=String(e.mergeCommitMessage)),e.mergeWhenPipelineSucceeds!=null&&(s.merge_when_pipeline_succeeds=!!e.mergeWhenPipelineSucceeds);try{let o=await T(`/projects/${n}/merge_requests/${i}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??i,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:i,project:String(t),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:t,iid:i}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let n=await T(`/projects/${L(t)}/merge_requests/${i}`);return JSON.stringify({iid:n.iid,projectId:n.project_id,title:n.title,description:(n.description||"").slice(0,5e3),state:n.state,author:n.author?.username,sourceBranch:n.source_branch,targetBranch:n.target_branch,draft:n.draft??n.work_in_progress??!1,mergeStatus:n.merge_status,changesCount:n.changes_count,labels:Array.isArray(n.labels)?n.labels:[],webUrl:n.web_url,createdAt:n.created_at,updatedAt:n.updated_at,mergedAt:n.merged_at,diffRefs:n.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:t,iid:i}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let n=await T(`/projects/${L(t)}/merge_requests/${i}/changes`),s=Array.isArray(n.changes)?n.changes:[];return JSON.stringify({iid:n.iid,total:s.length,diffRefs:n.diff_refs||null,files:s.map(o=>({oldPath:o.old_path,newPath:o.new_path,newFile:!!o.new_file,deletedFile:!!o.deleted_file,renamedFile:!!o.renamed_file,diff:typeof o.diff=="string"?o.diff.slice(0,3e3):""}))})}case"gitlab_list_commits":{let{projectId:t,since:i,until:n,refName:s,page:o,perPage:a,withStats:c}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let d=new URLSearchParams;d.set("per_page",String(Math.min(Number(a)||50,100))),d.set("page",String(Number(o)||1)),i&&d.set("since",i),n&&d.set("until",n),s&&d.set("ref_name",s),c!==!1&&d.set("with_stats","true");let l=await T(`/projects/${L(t)}/repository/commits?${d.toString()}`),p=(Array.isArray(l)?l:[]).map(u=>({id:u.id,shortId:u.short_id,title:u.title,authorName:u.author_name,authorEmail:u.author_email,authoredDate:u.authored_date,committedDate:u.committed_date,parentIds:Array.isArray(u.parent_ids)?u.parent_ids:[],stats:u.stats||null}));return JSON.stringify({page:Number(o)||1,count:p.length,hasMore:p.length>=Math.min(Number(a)||50,100),commits:p})}case"gitlab_get_commit":{let{projectId:t,sha:i,includeDiff:n,includeMrs:s}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and sha are required"});let o=await T(`/projects/${L(t)}/repository/commits/${encodeURIComponent(i)}`),a;if(s)try{let d=await T(`/projects/${L(t)}/repository/commits/${encodeURIComponent(i)}/merge_requests`);a=(Array.isArray(d)?d:[]).map(l=>({iid:l.iid,title:l.title,state:l.state,webUrl:l.web_url}))}catch{a=[]}let c;if(n!==!1){let d=await T(`/projects/${L(t)}/repository/commits/${encodeURIComponent(i)}/diff`);c=(Array.isArray(d)?d:[]).map(l=>({oldPath:l.old_path,newPath:l.new_path,newFile:!!l.new_file,deletedFile:!!l.deleted_file,renamedFile:!!l.renamed_file,diff:typeof l.diff=="string"?l.diff.slice(0,3e3):""}))}return JSON.stringify({id:o.id,shortId:o.short_id,title:o.title,message:typeof o.message=="string"?o.message.slice(0,2e3):"",authorName:o.author_name,authorEmail:o.author_email,authoredDate:o.authored_date,committedDate:o.committed_date,parentIds:Array.isArray(o.parent_ids)?o.parent_ids:[],stats:o.stats||null,webUrl:o.web_url,...c?{filesChanged:c.length,files:c}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:t,state:i,targetBranch:n,sourceBranch:s,authorUsername:o,labels:a,search:c,sort:d,orderBy:l,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",i||"opened"),u.set("per_page",String(p||20)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),n&&u.set("target_branch",n),s&&u.set("source_branch",s),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await T(`/projects/${L(t)}/merge_requests?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:t,iid:i,limit:n}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let s=await T(`/projects/${L(t)}/merge_requests/${i}/notes?per_page=${n||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(s)?s.length:0,notes:(Array.isArray(s)?s:[]).map(o=>({id:o.id,author:o.author?.username,body:(o.body||"").slice(0,1e3),system:!!o.system,createdAt:o.created_at}))})}case"gitlab_post_mr_note":{let{projectId:t,iid:i,body:n}=e||{};if(!t||!i||!n)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await T(`/projects/${L(t)}/merge_requests/${i}/notes`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:i,path:n,oldPath:s,newLine:o,oldLine:a,body:c}=e||{};if(!t||!i||!n||!c)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(o==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let d=L(t),l=e.diffRefs||null;if(l||(l=(await T(`/projects/${d}/merge_requests/${i}`)).diff_refs||null),!l||!l.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let p={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:n,old_path:s||n};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await T(`/projects/${d}/merge_requests/${i}/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:i,body:n,comments:s}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let o=L(t),a=Array.isArray(s)?s.filter(y=>y&&y.path&&y.body&&(y.newLine!=null||y.oldLine!=null)):[];if(!n&&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 T(`/projects/${o}/merge_requests/${i}`)).diff_refs||null);let d=new Set,l=null;try{for(let y=1;y<=20;y+=1){let _=await T(`/projects/${o}/merge_requests/${i}/discussions?per_page=100&page=${y}`);if(!Array.isArray(_)||_.length===0)break;for(let g of _)for(let k of g.notes||[]){let O=dt(k.body);O&&d.add(O),l==null&&pt(k.body)&&(l=k.id)}if(_.length<100)break}}catch{}let p=!1,u=!1;if(n){let y=`${String(n)}${lt}`;try{l!=null?(await T(`/projects/${o}/merge_requests/${i}/notes/${l}`,{method:"PUT",body:{body:y}}),u=!0):await T(`/projects/${o}/merge_requests/${i}/notes`,{method:"POST",body:{body:y}}),p=!0}catch{await T(`/projects/${o}/merge_requests/${i}/notes`,{method:"POST",body:{body:y}}),p=!0}}let{toPost:m,skipped:f}=ut(a,d),h=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 T(`/projects/${o}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(y.body),position:_}}),h+=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:h,inlineSkipped:f||void 0,inlineErrors:b.length?b:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:i,discussionId:n}=e||{};if(!t||!i||!n)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let s=await T(`/projects/${L(t)}/merge_requests/${i}/discussions/${encodeURIComponent(n)}`),o=Array.isArray(s.notes)?s.notes:[],a=o.find(d=>d.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:s.id,individualNote:!!s.individual_note,path:c&&(c.new_path||c.old_path)||null,newLine:c?c.new_line??null:null,oldLine:c?c.old_line??null:null,diffRefs:c?{base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha}:null,notes:o.map(d=>({id:d.id,author:d.author?.username,body:(d.body||"").slice(0,4e3),system:!!d.system,createdAt:d.created_at}))})}case"gitlab_reply_discussion":{let{projectId:t,iid:i,discussionId:n,body:s}=e||{};if(!t||!i||!n||!s)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await T(`/projects/${L(t)}/merge_requests/${i}/discussions/${encodeURIComponent(n)}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:t,limit:i}=e||{},n=Math.min(Number(i)>0?Number(i):50,200),s=new URLSearchParams;s.set("membership","true"),s.set("simple","true"),s.set("order_by","last_activity_at"),s.set("sort","desc"),s.set("per_page",String(Math.min(n+1,100))),t&&s.set("search",String(t));let o=await T(`/projects?${s.toString()}`),a=Array.isArray(o)?o:[],c=a.length>n,d=a.slice(0,n).map(l=>({fullPath:l.path_with_namespace,name:l.name,webUrl:l.web_url,defaultBranch:l.default_branch||null,visibility:l.visibility||null}));return JSON.stringify({count:d.length,truncated:c,projects:d})}case"gitlab_list_issues":{let{projectId:t,state:i,labels:n,assigneeUsername:s,authorUsername:o,updatedAfter:a,search:c,sort:d,orderBy:l,limit:p}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",i||"opened"),u.set("per_page",String(p||30)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),n&&u.set("labels",Array.isArray(n)?n.join(","):n),s&&u.set("assignee_username",s),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await T(`/projects/${L(t)}/issues?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(b=>b.username),userNotesCount:h.user_notes_count,webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,issues:f})}case"gitlab_get_issue":{let{projectId:t,iid:i}=e||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let n=await T(`/projects/${L(t)}/issues/${i}`);return JSON.stringify({iid:n.iid,projectId:n.project_id,title:n.title,description:(n.description||"").slice(0,5e3),state:n.state,labels:Array.isArray(n.labels)?n.labels:[],author:n.author?.username,assignees:(n.assignees||[]).map(s=>s.username),milestone:n.milestone?.title||null,webUrl:n.web_url,createdAt:n.created_at,updatedAt:n.updated_at,closedAt:n.closed_at})}case"gitlab_add_issue_comment":{let{projectId:t,iid:i,body:n}=e||{};if(!t||!i||!n)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await T(`/projects/${L(t)}/issues/${i}/notes`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_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 Yo}from"fs";import{fileURLToPath as Wo}from"url";import{dirname as Zo,resolve as Vo}from"path";import{resolveIntegrationToken as Qo}from"@zibby/core/backend-client.js";function Xo(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Zo(Wo(import.meta.url)),e=Vo(r,"..","bin","mcp-skill.mjs");return Yo(e)?e:null}async function Y(r,e={}){let{token:t}=await Qo("figma"),i=r.startsWith("https://")?r:`https://api.figma.com${r}`,n={"X-Figma-Token":t,Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(i,{method:e.method||"GET",headers:n,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Figma API ${s.status}: ${o.slice(0,300)}`)}return s.json()}function oe(r){let e=String(r||"").trim(),t=e.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return t?t[1]:e}function mt(r){return r==null?void 0:(Array.isArray(r)?r:String(r).split(",")).map(t=>String(t).trim().replace(/-/g,":")).filter(Boolean).join(",")}function ea(r){let e=String(r||"").match(/[?&]node-id=([^&]+)/i);return e?decodeURIComponent(e[1]).replace(/-/g,":"):void 0}var X=r=>typeof r=="number"?Math.round(r*100)/100:r;function Yt(r){if(!r)return null;let e=i=>Math.round((i??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=X(r.a)),t}function Vr(r){return!r||r.visible===!1?null:r.type==="SOLID"?{type:"SOLID",...Yt(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:X(e.position),...Yt(e.color)}))}:{}}}function Qr(r,e){let t=r.absoluteBoundingBox,i={id:r.id,name:r.name,type:r.type};t&&(i.size={w:X(t.width),h:X(t.height)},i.position={x:X(t.x),y:X(t.y)}),r.opacity!=null&&r.opacity!==1&&(i.opacity=r.opacity),r.cornerRadius!=null&&(i.cornerRadius=r.cornerRadius),Array.isArray(r.rectangleCornerRadii)&&(i.cornerRadii=r.rectangleCornerRadii);let n=(r.fills||[]).map(Vr).filter(Boolean);n.length&&(i.fills=n);let s=(r.strokes||[]).map(Vr).filter(Boolean);s.length&&(i.strokes=s,r.strokeWeight!=null&&(i.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:X(a.offset.x),y:X(a.offset.y)}}:{},...a.spread?{spread:a.spread}:{},...a.color?Yt(a.color):{}}));if(o.length&&(i.effects=o),r.layoutMode&&r.layoutMode!=="NONE"&&(i.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||{};i.text=r.characters,i.textStyle={fontFamily:a.fontFamily,fontWeight:a.fontWeight,fontSize:a.fontSize,lineHeightPx:a.lineHeightPx!=null?X(a.lineHeightPx):void 0,letterSpacing:a.letterSpacing!=null?X(a.letterSpacing):void 0,align:a.textAlignHorizontal,case:a.textCase}}return e>0&&Array.isArray(r.children)&&r.children.length&&(i.children=r.children.map(a=>Qr(a,e-1))),i}var Xr={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:N.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma (connected)
163
163
  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:
164
164
 
165
165
  ### Identity
@@ -345,14 +345,14 @@ You can send messages and replies on Lark. Use:
345
345
  - lark_get_chat_history: fetch recent messages in a chat
346
346
  - 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)
347
347
  When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=$a();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=Ua(e.receive_id),i=await _e("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:ci(e.text)});return JSON.stringify({ok:!0,message_id:i.message_id})}case"lark_reply":{if(!e.message_id||!e.text)return JSON.stringify({error:"message_id and text are required"});let t=await _e("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:ci(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,n=((await _e("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(s=>({chat_id:s.chat_id,name:s.name,description:s.description,owner_id:s.owner_id,chat_mode:s.chat_mode}));return JSON.stringify({chats:n})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,n=((await _e("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(s=>({message_id:s.message_id,sender_id:s.sender?.id,sender_type:s.sender?.sender_type,msg_type:s.msg_type,content:s.body?.content,create_time:s.create_time}));return JSON.stringify({messages:n})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let i=((await _e("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(n=>n.email===e.email&&n.user_id);return JSON.stringify(i?{ok:!0,user:{open_id:i.user_id,email:i.email,name:i.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 i=Math.max(1,Math.min(Number(e.limit)||5,25)),n=200,o=((await _e("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(l=>l.chat_id),a=new Set,c=[];for(let l of o){if(c.length>=n)break;try{let p=await _e("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=n))break}catch(p){console.warn(`[lark] member scan failed for ${l}: ${p.message}`)}}let d=[];for(let l of c){let p=(l.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(t)&&(u+=100-Math.abs(p.length-t.length)),p===t&&(u+=200),u>0&&d.push({open_id:l.open_id,name:l.name,_score:u})}return d.sort((l,p)=>p._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,i).map(({_score:l,...p})=>p),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}}};import{existsSync as Ja}from"fs";import{fileURLToPath as qa}from"url";import{dirname as Da,resolve as Ba}from"path";import{resolveIntegrationToken as Ma}from"@zibby/core/backend-client.js";function Fa(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Da(qa(import.meta.url)),e=Ba(r,"..","bin","mcp-skill.mjs");return Ja(e)?e:null}var Ka=process.env.DISCORD_API_URL||"https://discord.com/api/v10",Ga=2e3;function Ha(r,e=Ga){let t=String(r??"");if(!t.trim())return[];if(t.length<=e)return[t];let i=[],n=t;for(;n.length>e;){let o=n.slice(0,e).lastIndexOf(`
348
- `),a=o>e/2?o+1:e;i.push(n.slice(0,a)),n=n.slice(a)}return n&&i.push(n),i}async function li(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await Ma(N.DISCORD),t=(e&&e.token?String(e.token):"").trim();if(!t)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:t,guildId:(e.guildId||"").trim()}}async function Zt(r,e,{token:t,body:i}={}){let n=t.startsWith("Bot ")?t:`Bot ${t}`,s=await fetch(`${Ka}${e}`,{method:r,headers:{Authorization:n,...i!==void 0?{"Content-Type":"application/json"}:{}},...i!==void 0?{body:JSON.stringify(i)}:{}}),o=await s.json().catch(()=>null);if(!s.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${s.status}`;throw new Error(`Discord API error (${s.status}): ${a}`)}return o}async function za({token:r,guildId:e},t){let i=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(i)return i;let n=await Zt("GET","/users/@me/guilds",{token:r}),s=Array.isArray(n)?n:[];if(s.length===1)return s[0].id;if(s.length===0)throw new Error("The bot is not in any Discord server \u2014 invite it to a server first.");let o=s.slice(0,10).map(a=>`${a.name} (${a.id})`).join(", ");throw new Error(`The bot is in ${s.length} servers \u2014 pass guildId explicitly. Servers: ${o}`)}var di={id:"discord",serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:N.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord (connected)
348
+ `),a=o>e/2?o+1:e;i.push(n.slice(0,a)),n=n.slice(a)}return n&&i.push(n),i}async function li(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await Ma(N.DISCORD),t=(e&&e.token?String(e.token):"").trim();if(!t)throw new Error("Discord is not connected: connect Discord in the Zibby dashboard or set DISCORD_BOT_TOKEN.");return{token:t,guildId:(e.guildId||"").trim()}}async function Wt(r,e,{token:t,body:i}={}){let n=t.startsWith("Bot ")?t:`Bot ${t}`,s=await fetch(`${Ka}${e}`,{method:r,headers:{Authorization:n,...i!==void 0?{"Content-Type":"application/json"}:{}},...i!==void 0?{body:JSON.stringify(i)}:{}}),o=await s.json().catch(()=>null);if(!s.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${s.status}`;throw new Error(`Discord API error (${s.status}): ${a}`)}return o}async function za({token:r,guildId:e},t){let i=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(i)return i;let n=await Wt("GET","/users/@me/guilds",{token:r}),s=Array.isArray(n)?n:[];if(s.length===1)return s[0].id;if(s.length===0)throw new Error("The bot is not in any Discord server \u2014 invite it to a server first.");let o=s.slice(0,10).map(a=>`${a.name} (${a.id})`).join(", ");throw new Error(`The bot is in ${s.length} servers \u2014 pass guildId explicitly. Servers: ${o}`)}var di={id:"discord",serverName:"discord",allowedTools:["mcp__discord__*"],requiresIntegration:N.DISCORD,envKeys:["DISCORD_BOT_TOKEN","DISCORD_GUILD_ID"],description:"Discord bot tools (send messages, list channels)",promptFragment:`## Discord (connected)
349
349
  You can post to the user's Discord server as their bot. Tools:
350
350
  - discord_send_message(channelId, text) \u2014 post a message to a channel (long text is auto-chunked to Discord's 2000-char limit)
351
- - 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=Fa();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(),i=String(e.text||"");if(!t||!i.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let n=await li(),s=Ha(i),o=[];for(let a of s){let c=await Zt("POST",`/channels/${encodeURIComponent(t)}/messages`,{token:n.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:t,messageIds:o,chunks:s.length})}case"discord_list_channels":{let t=await li(),i=await za(t,e.guildId),n=await Zt("GET",`/guilds/${encodeURIComponent(i)}/channels`,{token:t.token}),s=(Array.isArray(n)?n:[]).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:i,channels:s})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"discord_send_message",description:"Post a message to a Discord channel as the connected bot. Text over 2000 chars is automatically split into sequential messages.",input_schema:{type:"object",properties:{channelId:{type:"string",description:"Discord channel id (snowflake). Use discord_list_channels to find it."},text:{type:"string",description:"Message text (Discord markdown supported)"}},required:["channelId","text"]}},{name:"discord_list_channels",description:"List the text channels of the connected Discord server (id + name). Pass guildId only when the bot is in multiple servers.",input_schema:{type:"object",properties:{guildId:{type:"string",description:"Discord server (guild) id \u2014 optional when the bot is in exactly one server or one was captured at connect time"}}}}]};import{existsSync as gi,statSync as Ya,readFileSync as Wa}from"fs";import{fileURLToPath as Za}from"url";import{basename as Va,dirname as Qa,resolve as Xa}from"path";import{resolveIntegrationToken as ec,clearTokenCache as tc}from"@zibby/core/backend-client.js";function rc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Qa(Za(import.meta.url)),e=Xa(r,"..","bin","mcp-skill.mjs");return gi(e)?e:null}var ic="2022-06-28",nc="https://api.notion.com/v1",ft=2e4,pi=25,sc=25,ht=100,ui=500,oc=20*1024*1024;function ae(r){if(!r||typeof r!="string")return null;let t=r.trim().split(/[?#]/)[0],i=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(i)return i[0].toLowerCase();let n=t.match(/[0-9a-fA-F]{32}/g);if(n&&n.length){let s=n[n.length-1].toLowerCase();return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}return null}async function te(r,e={}){let t=async()=>{let{token:i}=await ec("notion");if(typeof i!="string"||!i)throw new Error(`Invalid notion token type: ${typeof i}`);let n=await fetch(`${nc}${r}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,"Notion-Version":ic,Accept:"application/json",...e.body&&!e.formData?{"Content-Type":"application/json"}:{},...e.headers},body:e.formData?e.formData:e.body?JSON.stringify(e.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Notion API ${n.status}: ${o.slice(0,300)}`)}let s=await n.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(i){let n=String(i?.message||i||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("unauthorized")))throw i;return tc("notion"),t()}}function $e(r){if(!Array.isArray(r))return"";let e="";for(let t of r){let i=t?.plain_text??t?.text?.content??"";if(!i)continue;let n=t.annotations||{};n.code&&(i=`\`${i}\``),n.bold&&(i=`**${i}**`),n.italic&&(i=`_${i}_`),n.strikethrough&&(i=`~~${i}~~`);let s=t?.href||t?.text?.link?.url;s&&(i=`[${i}](${s})`),e+=i}return e}function ac(r,e,t){let i=r?.type,n=r?.[i]||{},s=" ".repeat(Math.max(0,e)),o=(d="rich_text")=>$e(n[d]),a;switch(i){case"paragraph":a=o();break;case"heading_1":a=`# ${o()}`;break;case"heading_2":a=`## ${o()}`;break;case"heading_3":a=`### ${o()}`;break;case"bulleted_list_item":a=`${s}- ${o()}`;break;case"numbered_list_item":a=`${s}1. ${o()}`;break;case"to_do":a=`${s}- [${n.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${s}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${n.icon?.emoji?`${n.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${n.language||""}
351
+ - 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=Fa();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(),i=String(e.text||"");if(!t||!i.trim())return JSON.stringify({ok:!1,error:"channelId and text are required"});let n=await li(),s=Ha(i),o=[];for(let a of s){let c=await Wt("POST",`/channels/${encodeURIComponent(t)}/messages`,{token:n.token,body:{content:a}});o.push(c&&c.id?c.id:"")}return JSON.stringify({ok:!0,channelId:t,messageIds:o,chunks:s.length})}case"discord_list_channels":{let t=await li(),i=await za(t,e.guildId),n=await Wt("GET",`/guilds/${encodeURIComponent(i)}/channels`,{token:t.token}),s=(Array.isArray(n)?n:[]).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:i,channels:s})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"discord_send_message",description:"Post a message to a Discord channel as the connected bot. Text over 2000 chars is automatically split into sequential messages.",input_schema:{type:"object",properties:{channelId:{type:"string",description:"Discord channel id (snowflake). Use discord_list_channels to find it."},text:{type:"string",description:"Message text (Discord markdown supported)"}},required:["channelId","text"]}},{name:"discord_list_channels",description:"List the text channels of the connected Discord server (id + name). Pass guildId only when the bot is in multiple servers.",input_schema:{type:"object",properties:{guildId:{type:"string",description:"Discord server (guild) id \u2014 optional when the bot is in exactly one server or one was captured at connect time"}}}}]};import{existsSync as gi,statSync as Ya,readFileSync as Wa}from"fs";import{fileURLToPath as Za}from"url";import{basename as Va,dirname as Qa,resolve as Xa}from"path";import{resolveIntegrationToken as ec,clearTokenCache as tc}from"@zibby/core/backend-client.js";function rc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Qa(Za(import.meta.url)),e=Xa(r,"..","bin","mcp-skill.mjs");return gi(e)?e:null}var ic="2022-06-28",nc="https://api.notion.com/v1",ft=2e4,pi=25,sc=25,ht=100,ui=500,oc=20*1024*1024;function ae(r){if(!r||typeof r!="string")return null;let t=r.trim().split(/[?#]/)[0],i=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(i)return i[0].toLowerCase();let n=t.match(/[0-9a-fA-F]{32}/g);if(n&&n.length){let s=n[n.length-1].toLowerCase();return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}return null}async function te(r,e={}){let t=async()=>{let{token:i}=await ec("notion");if(typeof i!="string"||!i)throw new Error(`Invalid notion token type: ${typeof i}`);let n=await fetch(`${nc}${r}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,"Notion-Version":ic,Accept:"application/json",...e.body&&!e.formData?{"Content-Type":"application/json"}:{},...e.headers},body:e.formData?e.formData:e.body?JSON.stringify(e.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Notion API ${n.status}: ${o.slice(0,300)}`)}let s=await n.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(i){let n=String(i?.message||i||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("unauthorized")))throw i;return tc("notion"),t()}}function $e(r){if(!Array.isArray(r))return"";let e="";for(let t of r){let i=t?.plain_text??t?.text?.content??"";if(!i)continue;let n=t.annotations||{};n.code&&(i=`\`${i}\``),n.bold&&(i=`**${i}**`),n.italic&&(i=`_${i}_`),n.strikethrough&&(i=`~~${i}~~`);let s=t?.href||t?.text?.link?.url;s&&(i=`[${i}](${s})`),e+=i}return e}function ac(r,e,t){let i=r?.type,n=r?.[i]||{},s=" ".repeat(Math.max(0,e)),o=(d="rich_text")=>$e(n[d]),a;switch(i){case"paragraph":a=o();break;case"heading_1":a=`# ${o()}`;break;case"heading_2":a=`## ${o()}`;break;case"heading_3":a=`### ${o()}`;break;case"bulleted_list_item":a=`${s}- ${o()}`;break;case"numbered_list_item":a=`${s}1. ${o()}`;break;case"to_do":a=`${s}- [${n.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${s}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${n.icon?.emoji?`${n.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${n.language||""}
352
352
  ${o()}
353
353
  \`\`\``;break}case"divider":a="---";break;case"child_page":a=`[child page: ${n.title||""}]`;break;case"child_database":a=`[child database: ${n.title||""}]`;break;case"bookmark":case"embed":case"link_preview":a=n.url?`<${n.url}>`:"";break;case"equation":a=n.expression?`$${n.expression}$`:"";break;case"table":case"column_list":case"column":a="";break;case"table_row":{let d=(n.cells||[]).map(l=>$e(l).trim());a=`${s}| ${d.join(" | ")} |`;break}default:a=o();break}let c=[];return a&&a.trim()&&c.push(a),t&&t.trim()&&c.push(t),c.join(`
354
354
  `)}async function yi(r,e,t){let i=[],n,s=0;do{if(t.used>=ft)break;let o=new URLSearchParams({page_size:"100"});n&&o.set("start_cursor",n);let a=await te(`/blocks/${r}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await yi(d.id,e+1,t));let p=ac(d,e,l);if(p&&(i.push(p),t.used+=p.length+1),t.used>=ft)break}n=a.has_more?a.next_cursor:void 0,s+=1}while(n&&s<sc);return i.join(`
355
- `)}function mi(r){let e=r?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let i=$e(t.title).trim();if(i)return i}return""}function ze(r){let e=String(r??"");if(!e)return[{type:"text",text:{content:""}}];let t=[];for(let i=0;i<e.length;i+=2e3)t.push({type:"text",text:{content:e.slice(i,i+2e3)}});return t}function cc(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:$e(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function lc(r){if(!r||!r.type)return"";switch(r.type){case"title":return $e(r.title).trim();case"rich_text":return $e(r.rich_text).trim();case"number":return r.number==null?"":String(r.number);case"select":return r.select?.name||"";case"status":return r.status?.name||"";case"multi_select":return(r.multi_select||[]).map(t=>t.name).join(", ");case"checkbox":return r.checkbox?"true":"false";case"url":return r.url||"";case"email":return r.email||"";case"phone_number":return r.phone_number||"";case"date":return r.date?.start||"";case"people":return(r.people||[]).map(t=>t.name||t.id).join(", ");default:return""}}function Vt(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function dc(r){let e=String(r??"").replace(/\r\n/g,`
355
+ `)}function mi(r){let e=r?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let i=$e(t.title).trim();if(i)return i}return""}function ze(r){let e=String(r??"");if(!e)return[{type:"text",text:{content:""}}];let t=[];for(let i=0;i<e.length;i+=2e3)t.push({type:"text",text:{content:e.slice(i,i+2e3)}});return t}function cc(r){return{id:r?.id||"",discussionId:r?.discussion_id||"",text:$e(r?.rich_text).trim(),author:r?.created_by?.id||"",createdTime:r?.created_time||""}}function lc(r){if(!r||!r.type)return"";switch(r.type){case"title":return $e(r.title).trim();case"rich_text":return $e(r.rich_text).trim();case"number":return r.number==null?"":String(r.number);case"select":return r.select?.name||"";case"status":return r.status?.name||"";case"multi_select":return(r.multi_select||[]).map(t=>t.name).join(", ");case"checkbox":return r.checkbox?"true":"false";case"url":return r.url||"";case"email":return r.email||"";case"phone_number":return r.phone_number||"";case"date":return r.date?.start||"";case"people":return(r.people||[]).map(t=>t.name||t.id).join(", ");default:return""}}function Zt(r){return`https://www.notion.so/${String(r||"").replace(/-/g,"")}`}function dc(r){let e=String(r??"").replace(/\r\n/g,`
356
356
  `),t=[];for(let i of e.split(`
357
357
  `)){let n=i.replace(/\s+$/,"");if(!n.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(n),o=/^\s*[-*]\s+(.*)$/.exec(n),a=/^\s*\d+[.)]\s+(.*)$/.exec(n),c,d;s?(c=`heading_${s[1].length}`,d=s[2]):o?(c="bulleted_list_item",d=o[1]):a?(c="numbered_list_item",d=a[1]):(c="paragraph",d=n),t.push({object:"block",type:c,[c]:{rich_text:ze(d)}})}return t}function fi(r){return Array.isArray(r?.blocks)&&r.blocks.length?r.blocks.slice(0,ui):typeof r?.markdown=="string"&&r.markdown.trim()?dc(r.markdown).slice(0,ui):null}async function hi(r,e){for(let t=0;t<e.length;t+=ht)await te(`/blocks/${r}/children`,{method:"PATCH",body:{children:e.slice(t,t+ht)}})}function pc(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!gi(e)||!Ya(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=Wa(e);if(t.length>oc)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return t}async function uc(r){let e=pc(r),t=Va(r.trim()),i=/\.png$/i.test(t)?"image/png":"image/jpeg",s=(await te("/file_uploads",{method:"POST",body:{mode:"single_part",filename:t}}))?.id;if(!s)throw new Error("Notion file upload create returned no id");let o=new FormData;return o.set("file",new Blob([e],{type:i}),t),await te(`/file_uploads/${s}/send`,{method:"POST",formData:o}),s}var _i={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:N.NOTION,description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion (connected)
358
358
  You can read Notion content as context AND write to Notion (create pages, append blocks, insert images).
@@ -363,7 +363,7 @@ You can read Notion content as context AND write to Notion (create pages, append
363
363
  - 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 }.
364
364
  - 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.
365
365
  - 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.
366
- 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=rc();return r?{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,i=ae(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=await te(`/pages/${i}`),s=mi(n),o=n?.url||`https://www.notion.so/${i.replace(/-/g,"")}`,c=await yi(i,0,{used:0}),d=!1;return c.length>ft&&(c=c.slice(0,ft),d=!0),JSON.stringify({ok:!0,id:i,title:s,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,i=ae(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let s={page_size:Math.max(1,Math.min(Number(e?.maxResults)||pi,pi))};e?.filter&&typeof e.filter=="object"&&(s.filter=e.filter);let o=await te(`/databases/${i}/query`,{method:"POST",body:s}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[p,u]of Object.entries(d.properties||{})){let m=lc(u);m&&(l[p]=m)}return{id:d.id,title:mi(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:i,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 i=e?.databaseId?ae(e.databaseId):null,n=e?.parentPageId?ae(e.parentPageId):ae(e?.parent||e?.pageId);if(!i&&!n)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let s=i?{database_id:i}:{page_id:n},o={title:{title:ze(t)}},a=fi(e)||[],c=a.slice(0,ht),d=await te("/pages",{method:"POST",body:{parent:s,properties:o,...c.length?{children:c}:{}}}),l=d?.id;if(!l)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let p=a.slice(ht);return p.length&&await hi(l,p),JSON.stringify({ok:!0,pageId:l,url:d?.url||Vt(l)})}case"notion_append_blocks":{let t=ae(e?.pageId||e?.blockId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=fi(e);return!i||!i.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await hi(t,i),JSON.stringify({ok:!0,pageId:t,url:Vt(t)}))}case"notion_insert_image":{let t=ae(e?.pageId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=typeof e?.caption=="string"&&e.caption.trim()?ze(e.caption.trim()):null,n,s;if(typeof e?.imagePath=="string"&&e.imagePath.trim())s=await uc(e.imagePath),n={type:"file_upload",file_upload:{id:s}};else if(typeof e?.imageUrl=="string"&&e.imageUrl.trim())n={type:"external",external:{url:e.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return i&&(n.caption=i),await te(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:n}]}}),JSON.stringify({ok:!0,pageId:t,url:Vt(t),...s?{fileUploadId:s}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,i=ae(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let n=new URLSearchParams({block_id:i,page_size:"100"}),s=await te(`/comments?${n.toString()}`),a=(Array.isArray(s.results)?s.results:[]).map(cc);return JSON.stringify({ok:!0,id:i,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 i=e?.discussionId||e?.discussion_id||null,n;if(i)n={discussion_id:String(i),rich_text:ze(t)};else{let o=e?.pageId||e?.page||e?.url||e?.id,a=ae(o);if(!a)return JSON.stringify({ok:!1,error:"Either discussionId (to reply) or a valid pageId (to start a comment) is required"});n={parent:{page_id:a},rich_text:ze(t)}}let s=await te("/comments",{method:"POST",body:n});return JSON.stringify({ok:!0,id:s?.id||"",discussionId:s?.discussion_id||i||""})}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 mc,readFileSync as fc}from"fs";import{fileURLToPath as hc}from"url";import{dirname as gc,resolve as yc}from"path";import{resolveIntegrationToken as Qt,clearTokenCache as _c}from"@zibby/core/backend-client.js";function bc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=gc(hc(import.meta.url)),e=yc(r,"..","bin","mcp-skill.mjs");return mc(e)?e:null}function kc(){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 wc(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function Sc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var vc="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 Xt(){let r=kc();if(r)return r;if(wc()||Sc())throw new Error(vc);return null}var Ic="202506",Nc="https://api.linkedin.com";function bi(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 ki(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 gt(r,e){return r?typeof r.get=="function"?r.get(e):r[e]||r[e.toLowerCase()]||null:null}async function be(r,e={},t="linkedin_business"){let i=async()=>{let n;if(t==="linkedin_personal"){let d=Xt();d&&(n=d.token)}if(n||({token:n}=await Qt(t)),typeof n!="string"||!n)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let s=r.startsWith("https://")?r:`${Nc}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"LinkedIn-Version":Ic,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${d.slice(0,300)}`)}let a=await o.text().catch(()=>""),c={};if(a&&a.trim())try{c=JSON.parse(a)}catch{c={raw:a}}return{status:o.status,headers:o.headers,body:c}};try{return await i()}catch(n){let s=String(n?.message||n||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw n;return _c(t),i()}}async function Oc(r){let e;if(r==="linkedin_personal"){let t=Xt();t&&(e=t.token)}if(e||({token:e}=await Qt(r)),typeof e!="string"||!e)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return e}function Rc(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 wi(r,e,t,i){if(typeof t!="string"||!t.trim())throw new Error("imagePath (a local image file path) is required to upload an image");let{body:n}=await be("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:e}}},r),s=n?.value?.uploadUrl,o=n?.value?.image;if(!s||!o)throw new Error(`LinkedIn image initializeUpload returned no uploadUrl/image (got: ${JSON.stringify(n).slice(0,200)})`);let a=fc(t),c=await Oc(r),d=await fetch(s,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":i||Rc(t)},body:a});if(!d.ok){let l=await d.text().catch(()=>"");throw new Error(`LinkedIn image upload ${d.status}: ${l.slice(0,300)}`)}return o}var Si={id:"linkedin",serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn (connected)
366
+ 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=rc();return r?{type:"stdio",command:"node",args:[r,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,i=ae(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=await te(`/pages/${i}`),s=mi(n),o=n?.url||`https://www.notion.so/${i.replace(/-/g,"")}`,c=await yi(i,0,{used:0}),d=!1;return c.length>ft&&(c=c.slice(0,ft),d=!0),JSON.stringify({ok:!0,id:i,title:s,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,i=ae(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let s={page_size:Math.max(1,Math.min(Number(e?.maxResults)||pi,pi))};e?.filter&&typeof e.filter=="object"&&(s.filter=e.filter);let o=await te(`/databases/${i}/query`,{method:"POST",body:s}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[p,u]of Object.entries(d.properties||{})){let m=lc(u);m&&(l[p]=m)}return{id:d.id,title:mi(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:i,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 i=e?.databaseId?ae(e.databaseId):null,n=e?.parentPageId?ae(e.parentPageId):ae(e?.parent||e?.pageId);if(!i&&!n)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let s=i?{database_id:i}:{page_id:n},o={title:{title:ze(t)}},a=fi(e)||[],c=a.slice(0,ht),d=await te("/pages",{method:"POST",body:{parent:s,properties:o,...c.length?{children:c}:{}}}),l=d?.id;if(!l)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let p=a.slice(ht);return p.length&&await hi(l,p),JSON.stringify({ok:!0,pageId:l,url:d?.url||Zt(l)})}case"notion_append_blocks":{let t=ae(e?.pageId||e?.blockId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=fi(e);return!i||!i.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await hi(t,i),JSON.stringify({ok:!0,pageId:t,url:Zt(t)}))}case"notion_insert_image":{let t=ae(e?.pageId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=typeof e?.caption=="string"&&e.caption.trim()?ze(e.caption.trim()):null,n,s;if(typeof e?.imagePath=="string"&&e.imagePath.trim())s=await uc(e.imagePath),n={type:"file_upload",file_upload:{id:s}};else if(typeof e?.imageUrl=="string"&&e.imageUrl.trim())n={type:"external",external:{url:e.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return i&&(n.caption=i),await te(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:n}]}}),JSON.stringify({ok:!0,pageId:t,url:Zt(t),...s?{fileUploadId:s}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,i=ae(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let n=new URLSearchParams({block_id:i,page_size:"100"}),s=await te(`/comments?${n.toString()}`),a=(Array.isArray(s.results)?s.results:[]).map(cc);return JSON.stringify({ok:!0,id:i,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 i=e?.discussionId||e?.discussion_id||null,n;if(i)n={discussion_id:String(i),rich_text:ze(t)};else{let o=e?.pageId||e?.page||e?.url||e?.id,a=ae(o);if(!a)return JSON.stringify({ok:!1,error:"Either discussionId (to reply) or a valid pageId (to start a comment) is required"});n={parent:{page_id:a},rich_text:ze(t)}}let s=await te("/comments",{method:"POST",body:n});return JSON.stringify({ok:!0,id:s?.id||"",discussionId:s?.discussion_id||i||""})}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 mc,readFileSync as fc}from"fs";import{fileURLToPath as hc}from"url";import{dirname as gc,resolve as yc}from"path";import{resolveIntegrationToken as Vt,clearTokenCache as _c}from"@zibby/core/backend-client.js";function bc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=gc(hc(import.meta.url)),e=yc(r,"..","bin","mcp-skill.mjs");return mc(e)?e:null}function kc(){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 wc(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function Sc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var vc="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 Qt(){let r=kc();if(r)return r;if(wc()||Sc())throw new Error(vc);return null}var Ic="202506",Nc="https://api.linkedin.com";function bi(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 ki(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 gt(r,e){return r?typeof r.get=="function"?r.get(e):r[e]||r[e.toLowerCase()]||null:null}async function be(r,e={},t="linkedin_business"){let i=async()=>{let n;if(t==="linkedin_personal"){let d=Qt();d&&(n=d.token)}if(n||({token:n}=await Vt(t)),typeof n!="string"||!n)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let s=r.startsWith("https://")?r:`${Nc}${r}`,o=await fetch(s,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"LinkedIn-Version":Ic,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(`LinkedIn API ${o.status}: ${d.slice(0,300)}`)}let a=await o.text().catch(()=>""),c={};if(a&&a.trim())try{c=JSON.parse(a)}catch{c={raw:a}}return{status:o.status,headers:o.headers,body:c}};try{return await i()}catch(n){let s=String(n?.message||n||"").toLowerCase();if(!(s.includes("token")||s.includes("401")||s.includes("unauthorized")))throw n;return _c(t),i()}}async function Oc(r){let e;if(r==="linkedin_personal"){let t=Qt();t&&(e=t.token)}if(e||({token:e}=await Vt(r)),typeof e!="string"||!e)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");return e}function Rc(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 wi(r,e,t,i){if(typeof t!="string"||!t.trim())throw new Error("imagePath (a local image file path) is required to upload an image");let{body:n}=await be("/rest/images?action=initializeUpload",{method:"POST",body:{initializeUploadRequest:{owner:e}}},r),s=n?.value?.uploadUrl,o=n?.value?.image;if(!s||!o)throw new Error(`LinkedIn image initializeUpload returned no uploadUrl/image (got: ${JSON.stringify(n).slice(0,200)})`);let a=fc(t),c=await Oc(r),d=await fetch(s,{method:"PUT",headers:{Authorization:`Bearer ${c}`,"Content-Type":i||Rc(t)},body:a});if(!d.ok){let l=await d.text().catch(()=>"");throw new Error(`LinkedIn image upload ${d.status}: ${l.slice(0,300)}`)}return o}var Si={id:"linkedin",serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn (connected)
367
367
  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.
368
368
 
369
369
  Business (company Page) \u2014 DRAFT only:
@@ -379,10 +379,10 @@ Attaching an image (optional, both tools):
379
379
  Notes:
380
380
  - Org-page posts are ALWAYS created as a DRAFT; personal-profile posts are ALWAYS published live \u2014 choose the tool accordingly.
381
381
  - 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.
382
- - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=bc();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/linkedin.js","linkedinSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"linkedin_list_organizations":{let{body:t}=await be("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),i=Array.isArray(t.elements)?t.elements:[],n=[];for(let s of i){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=bi(o);if(!a)continue;let c="",d="";try{let l=(await be(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=ki(l),d=l.vanityName||""}catch{}n.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:n.length,organizations:n})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,i=bi(t);if(!i)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let n=e?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${i}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u="";try{let m=(await be(`/rest/organizations/${i}`,{},"linkedin_business")).body;u=ki(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:i,urn:o},visibility:s,textPreview:n,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:n,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await wi("linkedin_business",o,a);d.content={media:{id:u,altText:c||""}}}let l=await be("/rest/posts",{method:"POST",body:d},"linkedin_business"),p=gt(l.headers,"x-restli-id")||gt(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"DRAFT",visibility:s,status:l.status})}case"linkedin_publish_post":{let t=Xt(),i=t?t.memberId:(await Qt("linkedin_personal")).memberId;if(!i)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let n=e?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${i}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u=(await be("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",f=u?.sub?String(u.sub):i;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:n,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:n,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await wi("linkedin_personal",o,a);d.content={media:{id:u,altText:c||""}}}let l=await be("/rest/posts",{method:"POST",body:d},"linkedin_personal"),p=gt(l.headers,"x-restli-id")||gt(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"PUBLISHED",visibility:s,status:l.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}}]};import{existsSync as Oi,statSync as Tc,readFileSync as Ac}from"fs";import{fileURLToPath as Ec}from"url";import{basename as xc,dirname as jc,resolve as Lc}from"path";import{resolveIntegrationToken as $c,clearTokenCache as Pc}from"@zibby/core/backend-client.js";function Cc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=jc(Ec(import.meta.url)),e=Lc(r,"..","bin","mcp-skill.mjs");return Oi(e)?e:null}var ke="https://docs.googleapis.com/v1",vi="https://www.googleapis.com/drive/v3",Uc="https://www.googleapis.com/upload/drive/v3",Jc=5*1024*1024;function qc(){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 Dc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Bc(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Mc="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.",tr=2e4,Fc=25;function er(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 Kc(){let r,e=qc();if(e)r=e.token;else{if(Bc()||Dc())throw new Error(Mc);({token:r}=await $c("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function re(r,e={}){let t=async()=>{let i=await Kc(),n=await fetch(r,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Google API ${n.status}: ${o.slice(0,300)}`)}let s=await n.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(i){let n=String(i?.message||i||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("unauthorized")))throw i;return Pc("google"),t()}}function Gc(r){let e=[],t="",i=0;for(;i<r.length;){let n=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(i));if(n){e.push({start:t.length,end:t.length+n[1].length,link:n[2]}),t+=n[1],i+=n[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(i));if(s){e.push({start:t.length,end:t.length+s[1].length,bold:!0}),t+=s[1],i+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(i));if(o){e.push({start:t.length,end:t.length+o[1].length,code:!0}),t+=o[1],i+=o[0].length;continue}t+=r[i],i+=1}return{text:t,styles:e}}function Ii(r,e){let t=String(r??"").replace(/\r\n/g,`
382
+ - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=bc();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/linkedin.js","linkedinSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"linkedin_list_organizations":{let{body:t}=await be("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),i=Array.isArray(t.elements)?t.elements:[],n=[];for(let s of i){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=bi(o);if(!a)continue;let c="",d="";try{let l=(await be(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=ki(l),d=l.vanityName||""}catch{}n.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:n.length,organizations:n})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,i=bi(t);if(!i)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let n=e?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${i}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u="";try{let m=(await be(`/rest/organizations/${i}`,{},"linkedin_business")).body;u=ki(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:i,urn:o},visibility:s,textPreview:n,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:n,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await wi("linkedin_business",o,a);d.content={media:{id:u,altText:c||""}}}let l=await be("/rest/posts",{method:"POST",body:d},"linkedin_business"),p=gt(l.headers,"x-restli-id")||gt(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"DRAFT",visibility:s,status:l.status})}case"linkedin_publish_post":{let t=Qt(),i=t?t.memberId:(await Vt("linkedin_personal")).memberId;if(!i)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let n=e?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${i}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u=(await be("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",f=u?.sub?String(u.sub):i;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:n,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:n,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await wi("linkedin_personal",o,a);d.content={media:{id:u,altText:c||""}}}let l=await be("/rest/posts",{method:"POST",body:d},"linkedin_personal"),p=gt(l.headers,"x-restli-id")||gt(l.headers,"x-linkedin-id")||l.body?.id||null;return JSON.stringify({ok:!0,postUrn:p,author:o,lifecycleState:"PUBLISHED",visibility:s,status:l.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Optionally ATTACH an image: pass imagePath (a local PNG file path, e.g. one returned by social_card_render) and it is uploaded to LinkedIn and attached to the post. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded (a set imagePath is reported as imageWouldAttach:true).",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},imagePath:{type:"string",description:"Optional. A LOCAL image file path (e.g. a PNG returned by social_card_render). When set, the image is uploaded to LinkedIn and attached to the post as its media. Not uploaded on a dry_run."},imageAltText:{type:"string",description:"Optional alt text for the attached image (accessibility). Only used when imagePath is set."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published or uploaded. Returns { dryRun, target, wouldPostAs, visibility, textPreview, imageWouldAttach? }. Defaults to false."}},required:["text"]}}]};import{existsSync as Oi,statSync as Tc,readFileSync as Ac}from"fs";import{fileURLToPath as Ec}from"url";import{basename as xc,dirname as jc,resolve as Lc}from"path";import{resolveIntegrationToken as $c,clearTokenCache as Pc}from"@zibby/core/backend-client.js";function Cc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=jc(Ec(import.meta.url)),e=Lc(r,"..","bin","mcp-skill.mjs");return Oi(e)?e:null}var ke="https://docs.googleapis.com/v1",vi="https://www.googleapis.com/drive/v3",Uc="https://www.googleapis.com/upload/drive/v3",Jc=5*1024*1024;function qc(){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 Dc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Bc(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Mc="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.",er=2e4,Fc=25;function Xt(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 Kc(){let r,e=qc();if(e)r=e.token;else{if(Bc()||Dc())throw new Error(Mc);({token:r}=await $c("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function re(r,e={}){let t=async()=>{let i=await Kc(),n=await fetch(r,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Google API ${n.status}: ${o.slice(0,300)}`)}let s=await n.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(i){let n=String(i?.message||i||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("unauthorized")))throw i;return Pc("google"),t()}}function Gc(r){let e=[],t="",i=0;for(;i<r.length;){let n=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(i));if(n){e.push({start:t.length,end:t.length+n[1].length,link:n[2]}),t+=n[1],i+=n[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(i));if(s){e.push({start:t.length,end:t.length+s[1].length,bold:!0}),t+=s[1],i+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(i));if(o){e.push({start:t.length,end:t.length+o[1].length,code:!0}),t+=o[1],i+=o[0].length;continue}t+=r[i],i+=1}return{text:t,styles:e}}function Ii(r,e){let t=String(r??"").replace(/\r\n/g,`
383
383
  `);if(!t.trim())return{requests:[],endIndex:e};let i=t.split(`
384
384
  `),n="",s=[],o=[];for(let l of i){let p=l,u=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(p),h=/^\s*[-*]\s+(.*)$/.exec(p),b=/^\s*\d+[.)]\s+(.*)$/.exec(p);f?(u=`HEADING_${f[1].length}`,p=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",p=h[1]):b&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",p=b[1]);let{text:y,styles:_}=Gc(p),g=e+n.length;for(let k of _)o.push({...k,start:g+k.start,end:g+k.end});n+=`${y}
385
- `,s.push({start:g,end:e+n.length,named:u,bullet:m})}if(!n)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:n}}];for(let l of s)l.named&&a.push({updateParagraphStyle:{range:{startIndex:l.start,endIndex:l.end},paragraphStyle:{namedStyleType:l.named},fields:"namedStyleType"}});let c=null,d=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let l of s)l.bullet?c&&c.preset===l.bullet?c.end=l.end:(d(),c={start:l.start,end:l.end,preset:l.bullet}):d();d();for(let l of o)l.end<=l.start||(l.bold?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{bold:!0},fields:"bold"}}):l.link?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{link:{url:l.link}},fields:"link"}}):l.code&&a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:e+n.length}}function Hc(r){let e="",t=i=>{for(let n of Array.isArray(i)?i:[]){if(e.length>=tr)return;if(n.paragraph)for(let s of n.paragraph.elements||[])e+=s?.textRun?.content||"";else if(n.table)for(let s of n.table.tableRows||[])for(let o of s.tableCells||[])t(o.content);else n.tableOfContents&&t(n.tableOfContents.content)}};return t(r?.content),e.slice(0,tr)}var Ye=r=>`https://docs.google.com/document/d/${r}/edit`;function zc(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Oi(e)||!Tc(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=Ac(e);if(t.length>Jc)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:xc(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Yc(r,e,t){let i=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${i}\r
385
+ `,s.push({start:g,end:e+n.length,named:u,bullet:m})}if(!n)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:n}}];for(let l of s)l.named&&a.push({updateParagraphStyle:{range:{startIndex:l.start,endIndex:l.end},paragraphStyle:{namedStyleType:l.named},fields:"namedStyleType"}});let c=null,d=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let l of s)l.bullet?c&&c.preset===l.bullet?c.end=l.end:(d(),c={start:l.start,end:l.end,preset:l.bullet}):d();d();for(let l of o)l.end<=l.start||(l.bold?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{bold:!0},fields:"bold"}}):l.link?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{link:{url:l.link}},fields:"link"}}):l.code&&a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:e+n.length}}function Hc(r){let e="",t=i=>{for(let n of Array.isArray(i)?i:[]){if(e.length>=er)return;if(n.paragraph)for(let s of n.paragraph.elements||[])e+=s?.textRun?.content||"";else if(n.table)for(let s of n.table.tableRows||[])for(let o of s.tableCells||[])t(o.content);else n.tableOfContents&&t(n.tableOfContents.content)}};return t(r?.content),e.slice(0,er)}var Ye=r=>`https://docs.google.com/document/d/${r}/edit`;function zc(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Oi(e)||!Tc(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=Ac(e);if(t.length>Jc)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:xc(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Yc(r,e,t){let i=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${i}\r
386
386
  Content-Type: application/json; charset=UTF-8\r
387
387
  \r
388
388
  ${JSON.stringify(r)}\r
@@ -399,10 +399,10 @@ Docs access is PER-USER: each teammate connects their OWN Google account (Integr
399
399
  - 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 }.
400
400
  - 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).
401
401
  - gdocs_list_created: list the Google Docs visible to this app (drive.file \u2192 only docs it created or the user picked).
402
- 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=Cc();if(!r)return null;let e={};for(let t of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gdocs_create_doc":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let n=(await re(`${ke}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!n)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=Ni(e);if(s&&s.trim()){let{requests:o}=Ii(s,1);o.length&&await re(`${ke}/documents/${n}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:n,title:t,url:Ye(n)})}case"gdocs_append":{let t=er(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let i=Ni(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await re(`${ke}/documents/${t}`))?.body,o=Array.isArray(s?.content)?s.content:[],a=o.length&&o[o.length-1].endIndex||2,c=Math.max(1,a-1),d=[],l=c;c>1&&(d.push({insertText:{location:{index:c},text:`
403
- `}}),l=c+1);let p=Ii(i,l);return d.push(...p.requests),await re(`${ke}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:Ye(t)})}case"gdocs_insert_image":{let t=er(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:i,fileName:n,mimeType:s}=zc(e.imagePath),{rawBody:o,contentType:a}=Yc({name:n,mimeType:s},i,s),d=(await re(`${Uc}/files?uploadType=multipart&fields=id`,{method:"POST",rawBody:o,contentType:a}))?.id;if(!d)return JSON.stringify({ok:!1,error:"Drive upload returned no file id"});await re(`${vi}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await re(`${ke}/documents/${t}`),p=Array.isArray(l?.body?.content)?l.body.content:[],u=p.length&&p[p.length-1].endIndex||2,f={location:{index:Math.max(1,u-1)},uri:`https://drive.google.com/uc?export=download&id=${d}`},h=Number(e?.width),b=Number(e?.height);return(Number.isFinite(h)&&h>0||Number.isFinite(b)&&b>0)&&(f.objectSize={...Number.isFinite(h)&&h>0?{width:{magnitude:h,unit:"PT"}}:{},...Number.isFinite(b)&&b>0?{height:{magnitude:b,unit:"PT"}}:{}}),await re(`${ke}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:Ye(t)})}case"gdocs_get":{let t=er(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let i=await re(`${ke}/documents/${t}`),n=Hc(i?.body);return JSON.stringify({ok:!0,documentId:t,title:i?.title||"",url:Ye(t),text:n,...n.length>=tr?{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(Fc),orderBy:"modifiedTime desc"}),i=await re(`${vi}/files?${t.toString()}`),n=(Array.isArray(i?.files)?i.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||Ye(s.id)}));return JSON.stringify({ok:!0,count:n.length,files:n})}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 Li,statSync as Wc,readFileSync as Zc}from"fs";import{fileURLToPath as Vc}from"url";import{basename as Qc,dirname as Xc,resolve as el}from"path";import{resolveIntegrationToken as tl}from"@zibby/core/backend-client.js";function rl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Xc(Vc(import.meta.url)),e=el(r,"..","bin","mcp-skill.mjs");return Li(e)?e:null}var Ti=2e4,Ai=50,il=10*1024*1024,nl=6e3*1e3,We=null;async function $i(){let{appId:r,appSecret:e,host:t}=await tl("lark");if(We&&We.appId===r&&We.expiresAt>Date.now())return{token:We.token,host:t};let n=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(n.code!==0)throw new Error(`Lark tenant_access_token failed: ${n.msg||n.code}`);return We={token:n.tenant_access_token,expiresAt:Date.now()+nl,appId:r},{token:n.tenant_access_token,host:t}}async function ie(r,e,t){let{token:i,host:n}=await $i(),s={method:r,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(s.body=JSON.stringify(t));let a=await(await fetch(`${n}${e}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:n}}function yt(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function we(r){if(!r||typeof r!="string")return null;let e=r.trim();if(!e)return null;let t=e.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return t?{type:t[1],token:t[2]}:/^[A-Za-z0-9]{10,}$/.test(e)?{type:"docx",token:e}:null}async function Pe(r){let e=typeof r=="string"?we(r):r;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:t}=await ie("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),i=t?.node||{};if(i.obj_type!=="docx"||!i.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${i.obj_type||"unknown"})`);return i.obj_token}function Ei(r){let e=String(r??"").replace(/\r\n/g,`
402
+ 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=Cc();if(!r)return null;let e={};for(let t of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gdocs_create_doc":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let n=(await re(`${ke}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!n)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=Ni(e);if(s&&s.trim()){let{requests:o}=Ii(s,1);o.length&&await re(`${ke}/documents/${n}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:n,title:t,url:Ye(n)})}case"gdocs_append":{let t=Xt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let i=Ni(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await re(`${ke}/documents/${t}`))?.body,o=Array.isArray(s?.content)?s.content:[],a=o.length&&o[o.length-1].endIndex||2,c=Math.max(1,a-1),d=[],l=c;c>1&&(d.push({insertText:{location:{index:c},text:`
403
+ `}}),l=c+1);let p=Ii(i,l);return d.push(...p.requests),await re(`${ke}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:Ye(t)})}case"gdocs_insert_image":{let t=Xt(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:i,fileName:n,mimeType:s}=zc(e.imagePath),{rawBody:o,contentType:a}=Yc({name:n,mimeType:s},i,s),d=(await re(`${Uc}/files?uploadType=multipart&fields=id`,{method:"POST",rawBody:o,contentType:a}))?.id;if(!d)return JSON.stringify({ok:!1,error:"Drive upload returned no file id"});await re(`${vi}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await re(`${ke}/documents/${t}`),p=Array.isArray(l?.body?.content)?l.body.content:[],u=p.length&&p[p.length-1].endIndex||2,f={location:{index:Math.max(1,u-1)},uri:`https://drive.google.com/uc?export=download&id=${d}`},h=Number(e?.width),b=Number(e?.height);return(Number.isFinite(h)&&h>0||Number.isFinite(b)&&b>0)&&(f.objectSize={...Number.isFinite(h)&&h>0?{width:{magnitude:h,unit:"PT"}}:{},...Number.isFinite(b)&&b>0?{height:{magnitude:b,unit:"PT"}}:{}}),await re(`${ke}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:Ye(t)})}case"gdocs_get":{let t=Xt(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let i=await re(`${ke}/documents/${t}`),n=Hc(i?.body);return JSON.stringify({ok:!0,documentId:t,title:i?.title||"",url:Ye(t),text:n,...n.length>=er?{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(Fc),orderBy:"modifiedTime desc"}),i=await re(`${vi}/files?${t.toString()}`),n=(Array.isArray(i?.files)?i.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||Ye(s.id)}));return JSON.stringify({ok:!0,count:n.length,files:n})}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 Li,statSync as Wc,readFileSync as Zc}from"fs";import{fileURLToPath as Vc}from"url";import{basename as Qc,dirname as Xc,resolve as el}from"path";import{resolveIntegrationToken as tl}from"@zibby/core/backend-client.js";function rl(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Xc(Vc(import.meta.url)),e=el(r,"..","bin","mcp-skill.mjs");return Li(e)?e:null}var Ti=2e4,Ai=50,il=10*1024*1024,nl=6e3*1e3,We=null;async function $i(){let{appId:r,appSecret:e,host:t}=await tl("lark");if(We&&We.appId===r&&We.expiresAt>Date.now())return{token:We.token,host:t};let n=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(n.code!==0)throw new Error(`Lark tenant_access_token failed: ${n.msg||n.code}`);return We={token:n.tenant_access_token,expiresAt:Date.now()+nl,appId:r},{token:n.tenant_access_token,host:t}}async function ie(r,e,t){let{token:i,host:n}=await $i(),s={method:r,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(s.body=JSON.stringify(t));let a=await(await fetch(`${n}${e}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:n}}function yt(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function we(r){if(!r||typeof r!="string")return null;let e=r.trim();if(!e)return null;let t=e.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return t?{type:t[1],token:t[2]}:/^[A-Za-z0-9]{10,}$/.test(e)?{type:"docx",token:e}:null}async function Pe(r){let e=typeof r=="string"?we(r):r;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:t}=await ie("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),i=t?.node||{};if(i.obj_type!=="docx"||!i.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${i.obj_type||"unknown"})`);return i.obj_token}function Ei(r){let e=String(r??"").replace(/\r\n/g,`
404
404
  `),t=[];for(let i of e.split(`
405
- `)){let n=i.replace(/\s+$/,"");if(!n.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(n),o=/^\s*[-*]\s+(.*)$/.exec(n),a=/^\s*\d+[.)]\s+(.*)$/.exec(n),c,d,l;if(s){let p=s[1].length;c=`heading${p}`,d=2+p,l=s[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=n);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function _t(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function xi(r,e){let t;for(let i=0;i<e.length;i+=Ai){let n=e.slice(i,i+Ai);t=(await ie("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:n})).host}return t}function sl(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Li(e)||!Wc(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=Zc(e);if(t.length>il)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function ol({fileName:r,parentNode:e,bytes:t}){let{token:i,host:n}=await $i(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",e),s.set("size",String(t.length)),s.set("file",new Blob([t]),r);let a=await(await fetch(`${n}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:s})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var al="docx",cl=50;function ji(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function ll(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function dl(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:ll(t?.content?.elements),createTime:t?.create_time||""}))}}function rr(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():al}var Pi={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:N.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs (connected)
405
+ `)){let n=i.replace(/\s+$/,"");if(!n.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(n),o=/^\s*[-*]\s+(.*)$/.exec(n),a=/^\s*\d+[.)]\s+(.*)$/.exec(n),c,d,l;if(s){let p=s[1].length;c=`heading${p}`,d=2+p,l=s[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=n);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function _t(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function xi(r,e){let t;for(let i=0;i<e.length;i+=Ai){let n=e.slice(i,i+Ai);t=(await ie("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:n})).host}return t}function sl(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Li(e)||!Wc(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=Zc(e);if(t.length>il)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function ol({fileName:r,parentNode:e,bytes:t}){let{token:i,host:n}=await $i(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",e),s.set("size",String(t.length)),s.set("file",new Blob([t]),r);let a=await(await fetch(`${n}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:s})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var al="docx",cl=50;function ji(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function ll(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function dl(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:ll(t?.content?.elements),createTime:t?.create_time||""}))}}function tr(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():al}var Pi={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:N.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs (connected)
406
406
  You can read, create, and append Lark/Feishu documents (docx). This reuses the same connected Lark app as messaging.
407
407
  - larkdoc_get: pass a Lark doc id OR a full doc URL (a /docx/ or /wiki/ link); returns { ok, documentId, title, url, text } where text is the doc as plain text (truncated to ~20k chars). Use it as reference context.
408
408
  - larkdoc_create: create a new doc from a title + markdown/text (#/##/### headings, - bullets, 1. ordered supported); returns { ok, documentId, url }. Share the url.
@@ -411,7 +411,7 @@ You can read, create, and append Lark/Feishu documents (docx). This reuses the s
411
411
  - larkdoc_list_comments: list the comment threads on a doc (pass the documentId or doc URL); returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.
412
412
  - larkdoc_reply_comment: reply INSIDE an existing comment thread \u2014 pass { documentId, commentId, text }. Use this to answer a user who @mentioned Zibby in a doc comment (reply in the SAME commentId).
413
413
  - larkdoc_add_comment: post a NEW top-level comment on a doc \u2014 pass { documentId, text }.
414
- These tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.`,resolve(){let r=rl();return r?{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=await Pe(i),s="";try{s=(await ie("GET",`/open-apis/docx/v1/documents/${n}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await ie("GET",`/open-apis/docx/v1/documents/${n}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>Ti&&(c=c.slice(0,Ti),d=!0),JSON.stringify({ok:!0,documentId:n,title:s,url:yt(a,n),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let{data:i,host:n}=await ie("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),s=i?.document?.document_id;if(!s)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let o=_t(e);if(o&&o.trim()){let a=Ei(o);a.length&&await xi(s,a)}return JSON.stringify({ok:!0,documentId:s,title:t,url:yt(n,s)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=_t(e);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Pe(i),o=Ei(n);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await xi(s,o);return JSON.stringify({ok:!0,documentId:s,url:yt(a,s)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,i=we(t);if(!i)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 n=await Pe(i),s=e.imagePath.trim(),o=sl(s),a=Qc(s),d=(await ie("POST",`/open-apis/docx/v1/documents/${n}/blocks/${n}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!d)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let l=await ol({fileName:a,parentNode:d,bytes:o}),p={token:l},u=Number(e?.width),m=Number(e?.height);Number.isFinite(u)&&u>0&&(p.width=Math.round(u)),Number.isFinite(m)&&m>0&&(p.height=Math.round(m));let{host:f}=await ie("PATCH",`/open-apis/docx/v1/documents/${n}/blocks/${d}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:n,blockId:d,fileToken:l,url:yt(f,n)})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=await Pe(i),s=rr(e),o=new URLSearchParams({file_type:s,page_size:String(cl)}),{data:a}=await ie("GET",`/open-apis/drive/v1/files/${n}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(dl);return JSON.stringify({ok:!0,documentId:n,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=_t({text:e?.text??e?.body});if(!n||!n.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Pe(i),o=rr(e),{data:a}=await ie("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:ji(n)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=e?.commentId||e?.comment_id;if(!n)return JSON.stringify({ok:!1,error:"commentId is required"});let s=_t({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Pe(i),a=rr(e),{data:c}=await ie("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(n)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:ji(s)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(n),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root."}},required:["title"]}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};var Ci={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:[...$.envKeys||[],...B.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return $.serverName;if(process.env.LARK_RECEIVE_ID)return B.serverName;if(process.env.SLACK_BOT_TOKEN)return $.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?$.allowedTools||[]:process.env.LARK_RECEIVE_ID?B.allowedTools||[]:process.env.SLACK_BOT_TOKEN?$.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
414
+ These tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.`,resolve(){let r=rl();return r?{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=await Pe(i),s="";try{s=(await ie("GET",`/open-apis/docx/v1/documents/${n}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await ie("GET",`/open-apis/docx/v1/documents/${n}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>Ti&&(c=c.slice(0,Ti),d=!0),JSON.stringify({ok:!0,documentId:n,title:s,url:yt(a,n),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let{data:i,host:n}=await ie("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),s=i?.document?.document_id;if(!s)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let o=_t(e);if(o&&o.trim()){let a=Ei(o);a.length&&await xi(s,a)}return JSON.stringify({ok:!0,documentId:s,title:t,url:yt(n,s)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=_t(e);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Pe(i),o=Ei(n);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await xi(s,o);return JSON.stringify({ok:!0,documentId:s,url:yt(a,s)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,i=we(t);if(!i)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 n=await Pe(i),s=e.imagePath.trim(),o=sl(s),a=Qc(s),d=(await ie("POST",`/open-apis/docx/v1/documents/${n}/blocks/${n}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!d)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let l=await ol({fileName:a,parentNode:d,bytes:o}),p={token:l},u=Number(e?.width),m=Number(e?.height);Number.isFinite(u)&&u>0&&(p.width=Math.round(u)),Number.isFinite(m)&&m>0&&(p.height=Math.round(m));let{host:f}=await ie("PATCH",`/open-apis/docx/v1/documents/${n}/blocks/${d}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:n,blockId:d,fileToken:l,url:yt(f,n)})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=await Pe(i),s=tr(e),o=new URLSearchParams({file_type:s,page_size:String(cl)}),{data:a}=await ie("GET",`/open-apis/drive/v1/files/${n}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(dl);return JSON.stringify({ok:!0,documentId:n,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=_t({text:e?.text??e?.body});if(!n||!n.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Pe(i),o=tr(e),{data:a}=await ie("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:ji(n)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,i=we(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let n=e?.commentId||e?.comment_id;if(!n)return JSON.stringify({ok:!1,error:"commentId is required"});let s=_t({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Pe(i),a=tr(e),{data:c}=await ie("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(n)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:ji(s)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(n),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root."}},required:["title"]}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};var Ci={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:[...$.envKeys||[],...B.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return $.serverName;if(process.env.LARK_RECEIVE_ID)return B.serverName;if(process.env.SLACK_BOT_TOKEN)return $.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?$.allowedTools||[]:process.env.LARK_RECEIVE_ID?B.allowedTools||[]:process.env.SLACK_BOT_TOKEN?$.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
415
415
  You can post chat messages via:
416
416
  - slack_post_message (channel, text[, blocks]) \u2014 Slack. The \`channel\` is REQUIRED on every call.
417
417
  - lark_send_message (receive_id, text) \u2014 Lark.
@@ -442,17 +442,17 @@ AFTER completing the test, you MUST call memory_save_insight at least once:
442
442
  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:
443
443
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
444
444
  2. Click "Connect Sentry" and authorize
445
- 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 wl(){let r=["## Available Skills"];for(let[e,t]of Object.entries(Se)){let i=t.integrationProvider?`integration: ${t.integrationProvider}`:"ready";r.push(`- ${e}: ${t.description} [${i}]`)}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: ${ir()}`),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(`
446
- `)}function Sl(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=bl(_l(),".zibby","config.json");return gl(r)&&JSON.parse(yl(r,"utf-8")).sessionToken||null}catch{return null}}function vl(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function ir(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function Il(r){try{let e=process.platform;return kl(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 Nl(){let r=Sl();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${vl()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});return e.ok?{checked:!0,statuses:await e.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${e.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function qi(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 Di={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:Se,promptFragment:wl,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:i}=t,n=await Nl();if(r==="list_available_skills"){let s=Object.entries(Se).map(([o,a])=>{let c=i.includes(o),d=qi(n.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:d.connected,setupInstructions:d.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:s})}if(r==="install_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(i.includes(s)){let l=Se[s],{getSkill:p}=await import("@zibby/agent-workflow"),m=(p(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?ir():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!Se[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(Se).join(", ")}`});let o=Se[s];if(o.integrationProvider){let l=qi(n.statuses,o.integrationProvider),p=ir();if(n.checked&&l.connected===!1){let u=Il(p);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:p,openedBrowser:u,setupInstructions:`Please connect ${o.integrationProvider} first at ${p}. After you finish OAuth, ask me to install ${s} again.`})}}i.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(s)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:d,hint:`${s} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(s==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=i.indexOf(s);return o===-1?JSON.stringify({ok:!1,error:`${s} is not installed`}):(i.splice(o,1),JSON.stringify({ok:!0,uninstalled:s}))}return JSON.stringify({error:`Unknown tool: ${r}`})},resolve(){return null}};import{readFileSync as Ol,readdirSync as Rl,statSync as Mi,writeFileSync as Tl,mkdirSync as Al}from"fs";import{join as Fi,resolve as El,relative as xl}from"path";import{execSync as Ki}from"child_process";var Bi=256*1024,jl=64*1024,Gi={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 i=t?.options?.workspace||process.cwd();try{switch(r){case"read_file":return Ll(e,i);case"write_file":return $l(e,i);case"list_directory":return Pl(e,i);case"run_command":return Cl(e,i);case"open_url":return Ul(e);case"wait":return await Jl(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(n){return JSON.stringify({error:n.message})}},resolve(){return null}};function bt(r,e){return El(e,r)}function Ll(r,e){let t=bt(r.path,e),i=Mi(t);return i.size>Bi?JSON.stringify({error:`File too large (${(i.size/1024).toFixed(0)}KB). Max: ${Bi/1024}KB`}):Ol(t,"utf-8")}function $l(r,e){let t=bt(r.path,e),i=Fi(t,"..");return Al(i,{recursive:!0}),Tl(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:xl(e,t)})}function Pl(r,e){let t=bt(r.path||".",e);return Rl(t).map(n=>{try{return Mi(Fi(t,n)).isDirectory()?`${n}/`:n}catch{return n}}).join(`
447
- `)}function Cl(r,e){let t=r.cwd?bt(r.cwd,e):e;return Ki(r.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:jl,stdio:["pipe","pipe","pipe"]})||"(no output)"}function Ul(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,i=t==="darwin"?"open":t==="win32"?"start":"xdg-open";try{return Ki(`${i} "${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 Jl(r,e){let t=Math.min(Math.max(r.seconds||5,1),300),i=r.reason||"async operation",n=500,s=Date.now()+t*1e3;for(;Date.now()<s;){if(e?.aborted)return JSON.stringify({ok:!0,waited:Math.round((t*1e3-(s-Date.now()))/1e3),reason:i,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(n,s-Date.now())))}return JSON.stringify({ok:!0,waited:t,reason:i})}import{existsSync as ql}from"fs";import{fileURLToPath as Dl}from"url";import{dirname as Bl,resolve as Ml}from"path";import{resolveIntegrationToken as Ze}from"@zibby/core/backend-client.js";function Fl(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=Bl(Dl(import.meta.url)),e=Ml(r,"..","bin","mcp-sentry.mjs");return ql(e)?e:null}function Ve(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Hi(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 zi(r,e={}){let{token:t,organizationSlug:i,baseUrl:n}=await Ze("sentry"),s=`${Ve(n)}/api/0/organizations/${Hi(i)}${r}`,o={method:e.method||"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}};e.body!=null&&(o.body=typeof e.body=="string"?e.body:JSON.stringify(e.body));let a=await fetch(s,o);if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Sentry API ${a.status}: ${c.slice(0,300)}`)}return a.json()}async function Kl(){return zi("/projects/?per_page=50")}async function Gl({query:r="is:unresolved",sort:e="date",project:t,limit:i=25}={}){let n=`/issues/?query=${encodeURIComponent(r)}&sort=${e}&per_page=${i}`;return t&&(n+=`&project=${encodeURIComponent(t)}`),zi(n)}async function nr(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:i,baseUrl:n}=await Ze("sentry"),s=await fetch(`${Ve(n)}/api/0/organizations/${Hi(i)}/shortids/${encodeURIComponent(e)}/`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status} resolving shortId "${e}": ${c.slice(0,200)}`)}let o=await s.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${e}" did not resolve to a numeric issue id`);return String(a)}async function Hl(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let e=await nr(r),{token:t,baseUrl:i}=await Ze("sentry"),n=await fetch(`${Ve(i)}/api/0/issues/${e}/`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Sentry API ${n.status}: ${s.slice(0,300)}`)}return n.json()}async function zl(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 i=await nr(r),{token:n,baseUrl:s}=await Ze("sentry"),o=await fetch(`${Ve(s)}/api/0/issues/${i}/`,{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===403?new Error(`Sentry API 403 updating issue ${r}: ${a.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access to let Zibby resolve/comment on issues.`):new Error(`Sentry API ${o.status} updating issue ${r}: ${a.slice(0,300)}`)}return o.json()}async function Yl(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 nr(r),{token:i,baseUrl:n}=await Ze("sentry"),s=await fetch(`${Ve(n)}/api/0/issues/${t}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(e)})});if(!s.ok){let o=await s.text().catch(()=>"");throw s.status===403?new Error(`Sentry API 403 commenting on issue ${r}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${s.status} commenting on issue ${r}: ${o.slice(0,300)}`)}return s.json()}var kt={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:N.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
445
+ 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 wl(){let r=["## Available Skills"];for(let[e,t]of Object.entries(Se)){let i=t.integrationProvider?`integration: ${t.integrationProvider}`:"ready";r.push(`- ${e}: ${t.description} [${i}]`)}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: ${rr()}`),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(`
446
+ `)}function Sl(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=bl(_l(),".zibby","config.json");return gl(r)&&JSON.parse(yl(r,"utf-8")).sessionToken||null}catch{return null}}function vl(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function rr(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function Il(r){try{let e=process.platform;return kl(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 Nl(){let r=Sl();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${vl()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});return e.ok?{checked:!0,statuses:await e.json()||{},reason:null}:{checked:!1,statuses:null,reason:`status-${e.status}`}}catch{return{checked:!1,statuses:null,reason:"network-error"}}}function qi(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 Di={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:Se,promptFragment:wl,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:i}=t,n=await Nl();if(r==="list_available_skills"){let s=Object.entries(Se).map(([o,a])=>{let c=i.includes(o),d=qi(n.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:d.connected,setupInstructions:d.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:s})}if(r==="install_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(i.includes(s)){let l=Se[s],{getSkill:p}=await import("@zibby/agent-workflow"),m=(p(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?rr():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!Se[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(Se).join(", ")}`});let o=Se[s];if(o.integrationProvider){let l=qi(n.statuses,o.integrationProvider),p=rr();if(n.checked&&l.connected===!1){let u=Il(p);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:p,openedBrowser:u,setupInstructions:`Please connect ${o.integrationProvider} first at ${p}. After you finish OAuth, ask me to install ${s} again.`})}}i.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(s)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:d,hint:`${s} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(s==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=i.indexOf(s);return o===-1?JSON.stringify({ok:!1,error:`${s} is not installed`}):(i.splice(o,1),JSON.stringify({ok:!0,uninstalled:s}))}return JSON.stringify({error:`Unknown tool: ${r}`})},resolve(){return null}};import{readFileSync as Ol,readdirSync as Rl,statSync as Mi,writeFileSync as Tl,mkdirSync as Al}from"fs";import{join as Fi,resolve as El,relative as xl}from"path";import{execSync as Ki}from"child_process";var Bi=256*1024,jl=64*1024,Gi={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 i=t?.options?.workspace||process.cwd();try{switch(r){case"read_file":return Ll(e,i);case"write_file":return $l(e,i);case"list_directory":return Pl(e,i);case"run_command":return Cl(e,i);case"open_url":return Ul(e);case"wait":return await Jl(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(n){return JSON.stringify({error:n.message})}},resolve(){return null}};function bt(r,e){return El(e,r)}function Ll(r,e){let t=bt(r.path,e),i=Mi(t);return i.size>Bi?JSON.stringify({error:`File too large (${(i.size/1024).toFixed(0)}KB). Max: ${Bi/1024}KB`}):Ol(t,"utf-8")}function $l(r,e){let t=bt(r.path,e),i=Fi(t,"..");return Al(i,{recursive:!0}),Tl(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:xl(e,t)})}function Pl(r,e){let t=bt(r.path||".",e);return Rl(t).map(n=>{try{return Mi(Fi(t,n)).isDirectory()?`${n}/`:n}catch{return n}}).join(`
447
+ `)}function Cl(r,e){let t=r.cwd?bt(r.cwd,e):e;return Ki(r.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:jl,stdio:["pipe","pipe","pipe"]})||"(no output)"}function Ul(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,i=t==="darwin"?"open":t==="win32"?"start":"xdg-open";try{return Ki(`${i} "${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 Jl(r,e){let t=Math.min(Math.max(r.seconds||5,1),300),i=r.reason||"async operation",n=500,s=Date.now()+t*1e3;for(;Date.now()<s;){if(e?.aborted)return JSON.stringify({ok:!0,waited:Math.round((t*1e3-(s-Date.now()))/1e3),reason:i,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(n,s-Date.now())))}return JSON.stringify({ok:!0,waited:t,reason:i})}import{existsSync as ql}from"fs";import{fileURLToPath as Dl}from"url";import{dirname as Bl,resolve as Ml}from"path";import{resolveIntegrationToken as Ze}from"@zibby/core/backend-client.js";function Fl(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=Bl(Dl(import.meta.url)),e=Ml(r,"..","bin","mcp-sentry.mjs");return ql(e)?e:null}function Ve(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Hi(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 zi(r,e={}){let{token:t,organizationSlug:i,baseUrl:n}=await Ze("sentry"),s=`${Ve(n)}/api/0/organizations/${Hi(i)}${r}`,o={method:e.method||"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}};e.body!=null&&(o.body=typeof e.body=="string"?e.body:JSON.stringify(e.body));let a=await fetch(s,o);if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Sentry API ${a.status}: ${c.slice(0,300)}`)}return a.json()}async function Kl(){return zi("/projects/?per_page=50")}async function Gl({query:r="is:unresolved",sort:e="date",project:t,limit:i=25}={}){let n=`/issues/?query=${encodeURIComponent(r)}&sort=${e}&per_page=${i}`;return t&&(n+=`&project=${encodeURIComponent(t)}`),zi(n)}async function ir(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:i,baseUrl:n}=await Ze("sentry"),s=await fetch(`${Ve(n)}/api/0/organizations/${Hi(i)}/shortids/${encodeURIComponent(e)}/`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status} resolving shortId "${e}": ${c.slice(0,200)}`)}let o=await s.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${e}" did not resolve to a numeric issue id`);return String(a)}async function Hl(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let e=await ir(r),{token:t,baseUrl:i}=await Ze("sentry"),n=await fetch(`${Ve(i)}/api/0/issues/${e}/`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Sentry API ${n.status}: ${s.slice(0,300)}`)}return n.json()}async function zl(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 i=await ir(r),{token:n,baseUrl:s}=await Ze("sentry"),o=await fetch(`${Ve(s)}/api/0/issues/${i}/`,{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===403?new Error(`Sentry API 403 updating issue ${r}: ${a.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access to let Zibby resolve/comment on issues.`):new Error(`Sentry API ${o.status} updating issue ${r}: ${a.slice(0,300)}`)}return o.json()}async function Yl(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 ir(r),{token:i,baseUrl:n}=await Ze("sentry"),s=await fetch(`${Ve(n)}/api/0/issues/${t}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(e)})});if(!s.ok){let o=await s.text().catch(()=>"");throw s.status===403?new Error(`Sentry API 403 commenting on issue ${r}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${s.status} commenting on issue ${r}: ${o.slice(0,300)}`)}return s.json()}var kt={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:N.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry (connected)
448
448
  You have access to the user's Sentry. Use these tools:
449
449
  - sentry_list_projects: List projects in the organization
450
450
  - sentry_list_issues: List errors/issues (supports Sentry search query, project filter, sort)
451
451
  - sentry_get_issue: Get detailed info about a specific issue (requires issueId)
452
452
  - sentry_update_issue: Change an issue's status (resolved / resolvedInNextRelease / ignored / unresolved / muted), assignment, or bookmark (requires issueId; needs write scope)
453
- - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=Fl();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 Kl();return JSON.stringify({projects:t.map(i=>({slug:i.slug,name:i.name,platform:i.platform}))})}case"sentry_list_issues":{let t=await Gl({query:e.query,sort:e.sort,project:e.project,limit:e.limit});return JSON.stringify({issues:t.map(i=>({id:i.id,title:i.title,culprit:i.culprit,count:i.count,firstSeen:i.firstSeen,lastSeen:i.lastSeen,level:i.level,status:i.status}))})}case"sentry_get_issue":{let t=await Hl(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 zl(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 Yl(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"]}}]};kt.tools=kt.toolsForAssistant;import{spawn as nn}from"child_process";import{writeFileSync as Wl,mkdirSync as Yi,existsSync as ne,readdirSync as It,readFileSync as vt,unlinkSync as Zl,createWriteStream as Vl,statSync as Ql}from"fs";import{resolve as ve,join as Z}from"path";import{resolveMaxParallelRuns as sn}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Xl}from"@zibby/core/constants/zibby-scratch.js";var ar="sessions",cr=".zibby/output",wt=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",ed=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",on=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",M=new Map,he=[],td=0,sr=0,Wi=3e3;function an(){return`run_${++td}_${Date.now().toString(36)}`}function Zi(r){let e=Math.floor(r/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function cn(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function J(r,e,t){if(!ed)return;let i=`
453
+ - sentry_add_comment: Post a comment/note on an issue (requires issueId + text; needs write scope)`,resolve(){let r=Fl();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 Kl();return JSON.stringify({projects:t.map(i=>({slug:i.slug,name:i.name,platform:i.platform}))})}case"sentry_list_issues":{let t=await Gl({query:e.query,sort:e.sort,project:e.project,limit:e.limit});return JSON.stringify({issues:t.map(i=>({id:i.id,title:i.title,culprit:i.culprit,count:i.count,firstSeen:i.firstSeen,lastSeen:i.lastSeen,level:i.level,status:i.status}))})}case"sentry_get_issue":{let t=await Hl(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 zl(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 Yl(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"]}}]};kt.tools=kt.toolsForAssistant;import{spawn as nn}from"child_process";import{writeFileSync as Wl,mkdirSync as Yi,existsSync as ne,readdirSync as It,readFileSync as vt,unlinkSync as Zl,createWriteStream as Vl,statSync as Ql}from"fs";import{resolve as ve,join as Z}from"path";import{resolveMaxParallelRuns as sn}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Xl}from"@zibby/core/constants/zibby-scratch.js";var or="sessions",ar=".zibby/output",wt=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",ed=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",on=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",M=new Map,he=[],td=0,nr=0,Wi=3e3;function an(){return`run_${++td}_${Date.now().toString(36)}`}function Zi(r){let e=Math.floor(r/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function cn(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function J(r,e,t){if(!ed)return;let i=`
454
454
  ${e} [${r}] ${t}
455
- `;try{process.stderr.write(i)}catch{}}function lr(){he.length=0;for(let[,r]of M)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",lr);process.on("SIGINT",()=>{lr(),process.exit(0)});process.on("SIGTERM",()=>{lr(),process.exit(0)});var ln={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
455
+ `;try{process.stderr.write(i)}catch{}}function cr(){he.length=0;for(let[,r]of M)if(r.status==="queued"&&(r.status="cancelled"),r.status==="running"&&r._child)try{r._child.kill("SIGTERM")}catch{}}process.on("exit",cr);process.on("SIGINT",()=>{cr(),process.exit(0)});process.on("SIGTERM",()=>{cr(),process.exit(0)});var ln={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
456
456
  You can run zibby test workflows directly from chat:
457
457
 
458
458
  **CRITICAL: When user asks to test a ticket:**
@@ -589,7 +589,7 @@ Each run generates:
589
589
  - events.json: All browser events
590
590
  - raw_stream_output.txt: Agent log
591
591
 
592
- Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(r,e,t){let i=t?.options?.workspace||process.cwd();try{switch(r){case"run_generate":return await rd(e,i);case"run_test":return await cd(e,i,t);case"run_status":return ld(e);case"run_cancel":return dd(e);case"run_artifacts":return md(e,i);case"run_diagnose":return fd(e,i);case"list_specs":return hd(e,i);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(n){return JSON.stringify({error:n.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 or(){let r=0;for(let[,e]of M)e.status==="running"&&r++;return r}function Vi(){for(;he.length>0;){let r=sn(he[0]?.context?.options?.config);if(or()>=r)break;let{args:e,cwd:t,context:i}=he.shift();dn(e,t,i)}}async function rd(r,e){let{ticket:t,description:i,input:n,repo:s,agent:o,output:a}=r,c=["generate"];t&&c.push("--ticket",t),i&&c.push("--description",i),n&&c.push("--input",n),s&&c.push("--repo",s),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,p=l&&d.includes(l)?l:null;p&&c.push("--agent",p);let u=t||"generate";return J(u,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{on&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(y=>/\s/.test(y)?JSON.stringify(y):y).join(" ")} cwd=${e}`);let f=nn("zibby",c,{cwd:e,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",b="";f.stdout.on("data",y=>{let _=y.toString();h+=_;for(let g of _.split(`
592
+ Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(r,e,t){let i=t?.options?.workspace||process.cwd();try{switch(r){case"run_generate":return await rd(e,i);case"run_test":return await cd(e,i,t);case"run_status":return ld(e);case"run_cancel":return dd(e);case"run_artifacts":return md(e,i);case"run_diagnose":return fd(e,i);case"list_specs":return hd(e,i);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(n){return JSON.stringify({error:n.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 sr(){let r=0;for(let[,e]of M)e.status==="running"&&r++;return r}function Vi(){for(;he.length>0;){let r=sn(he[0]?.context?.options?.config);if(sr()>=r)break;let{args:e,cwd:t,context:i}=he.shift();dn(e,t,i)}}async function rd(r,e){let{ticket:t,description:i,input:n,repo:s,agent:o,output:a}=r,c=["generate"];t&&c.push("--ticket",t),i&&c.push("--description",i),n&&c.push("--input",n),s&&c.push("--repo",s),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,p=l&&d.includes(l)?l:null;p&&c.push("--agent",p);let u=t||"generate";return J(u,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{on&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(y=>/\s/.test(y)?JSON.stringify(y):y).join(" ")} cwd=${e}`);let f=nn("zibby",c,{cwd:e,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",b="";f.stdout.on("data",y=>{let _=y.toString();h+=_;for(let g of _.split(`
593
593
  `)){let k=cn(g).trim();k.startsWith("\u2705")?J(u,"\u2705",k.slice(2).trim()):k.startsWith("\u2713")&&J(u,"\u2714",k.slice(2).trim())}}),f.stderr.on("data",y=>{b+=y.toString()}),f.on("close",y=>{if(y!==0){J(u,"\u274C",`Generation failed (exit ${y})`),m(JSON.stringify({error:`zibby generate failed with exit code ${y}`,stderr:b.slice(-1e3)}));return}let _=ve(e,a||"test-specs"),g=[];try{let k=t?t.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";g=It(_).filter(O=>O.endsWith(".txt")&&(!k||O.startsWith(k))).map(O=>Z(_,O))}catch{}J(u,"\u2705",`Generated ${g.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:t||null,specFiles:g.map(k=>k.replace(`${e}/`,"")),total:g.length,message:`Generated ${g.length} specs. Now call run_test for each file.`}))}),f.on("error",y=>{J(u,"\u274C",`Spawn error: ${y.message}`),m(JSON.stringify({error:y.message}))})})}var Qi=1e5,Xi=/^[A-Z][A-Z0-9]+-\d+$/,id=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function nd(r,e){if(!e||!e.length)return r;let t=r;for(let i of e)i.type==="strong"?t=`**${t}**`:i.type==="em"?t=`_${t}_`:i.type==="code"?t=`\`${t}\``:i.type==="strike"?t=`~~${t}~~`:i.type==="link"&&i.attrs?.href&&(t=`[${t}](${i.attrs.href})`);return t}function St(r,e=0){if(!Array.isArray(r))return"";let t=[];for(let i of r){if(i.type==="text"){t.push(nd(i.text||"",i.marks));continue}if(i.type==="hardBreak"){t.push(`
594
594
  `);continue}if(i.type==="rule"){t.push(`
595
595
  ---
@@ -614,10 +614,10 @@ ${n}
614
614
 
615
615
  `).trim();return l?(l.length>Qi&&(l=`${l.slice(0,Qi)}
616
616
 
617
- ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function ad(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function cd(r,e,t){let i={...r},n=String(i.spec??"").trim();if(!n)return JSON.stringify({error:"spec is required"});let s=null;if(Xi.test(n)&&!n.startsWith("inline:")){let l=await od(n);l&&(n=l.inlineSpec,i.spec=n,String(i.ticketKey||"").trim()||(i.ticketKey=l.issueKey),s=l.issueKey)}let o=String(i.ticketKey||"").trim();if(o){for(let[l,p]of M.entries())if(p?.ticketKey===o&&!(p?.status!=="running"&&p?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:p.status,reused:!0,message:`A run for ${o} is already ${p.status}. Reusing existing run instead of starting a duplicate.`})}if(!n.startsWith("inline:")){let l=ve(e,n);if(!ne(l))return Xi.test(n)?JSON.stringify({error:`Invalid run_test spec: "${n}" 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:n},invalidExample:{spec:n,ticketKey:n}}):JSON.stringify({error:`Test spec not found: ${n}`,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=sn(t?.options?.config);if(or()>=a){let l=an(),p=i.ticketKey||l,u={runId:l,spec:i.ticketKey?`${i.ticketKey}: ${i.spec}`:i.spec,ticketKey:i.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};M.set(l,u),he.push({args:{...i,_queuedRunId:l},cwd:e,context:t}),J(p,"\u23F3",`Queued (${or()}/${a} running, ${he.length} queued)`);let m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return s&&(m.resolvedFromJiraIssue=s,m.message+=` (spec built from Jira ${s})`),JSON.stringify(m)}let c=Date.now()-sr;c<Wi&&sr>0&&await new Promise(l=>setTimeout(l,Wi-c)),sr=Date.now();let d=dn(i,e,t);return s?ad(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function dn(r,e,t){let{spec:i,ticketKey:n,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||an(),l=i,p=!1;if(i.startsWith("inline:")){p=!0;let A=Xl(e);Yi(A,{recursive:!0}),l=Z(A,`${d}.txt`),Wl(l,i.slice(7).trim(),"utf-8")}let u=ve(e,".zibby","output","runs");Yi(u,{recursive:!0});let m=Z(u,`${d}.log`),f=Vl(m,{flags:"a"}),b=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,y=["test",l];b&&y.push("--agent",b),o&&y.push("--headless"),a&&y.push("--workflow",a),on&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${y.map(A=>/\s/.test(A)?JSON.stringify(A):A).join(" ")} cwd=${e}`);let _=nn("zibby",y,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),g={runId:d,spec:n?`${n}: ${i}`:i,ticketKey:n||null,specPath:l,logPath:m,isInline:p,pid:_.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=n||d,O="";function H(A){let R=cn(A).trim();if(!R)return;if(R.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let x=JSON.parse(R.slice(22));x.phase==="node_begin"?g.currentNode=x.node:x.phase==="node_end"&&(x.node&&!g.completedNodes.includes(x.node)&&g.completedNodes.push(x.node),g.currentNode===x.node&&(g.currentNode=null))}catch{}return}let D=R.match(/Session\s+(\S+)/);if(D&&!g.sessionId&&(g.sessionId=D[1],g.sessionPath=ve(e,cr,ar,g.sessionId)),R.startsWith("\u250C ")||R.startsWith("\u250C ")){let x=R.slice(2).trim();g.currentNode=x,wt&&J(k,"\u25B6",`${x}`)}else if(R.startsWith("\u2514 ")||R.startsWith("\u2514 ")){let x=R.slice(2).trim();x.startsWith("done")?(g.currentNode&&!g.completedNodes.includes(g.currentNode)&&g.completedNodes.push(g.currentNode),wt&&J(k,"\u2714",`${g.currentNode||"node"} done ${x.replace("done","").trim()}`),g.currentNode=null):x.startsWith("failed")&&(wt&&J(k,"\u2718",`${g.currentNode||"node"} failed ${x.replace("failed","").trim()}`),g.currentNode=null)}else R.includes("Workflow completed")&&(g.currentNode=null,wt&&J(k,"\u2714",`Workflow completed (${Zi(Date.now()-g.startTime)})`))}function Te(A){let R=A.toString();g.output+=R,f.write(R),g.output.length>5e4&&(g.output=g.output.slice(-3e4)),O+=R;let D=O.split(`
617
+ ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function ad(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function cd(r,e,t){let i={...r},n=String(i.spec??"").trim();if(!n)return JSON.stringify({error:"spec is required"});let s=null;if(Xi.test(n)&&!n.startsWith("inline:")){let l=await od(n);l&&(n=l.inlineSpec,i.spec=n,String(i.ticketKey||"").trim()||(i.ticketKey=l.issueKey),s=l.issueKey)}let o=String(i.ticketKey||"").trim();if(o){for(let[l,p]of M.entries())if(p?.ticketKey===o&&!(p?.status!=="running"&&p?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:p.status,reused:!0,message:`A run for ${o} is already ${p.status}. Reusing existing run instead of starting a duplicate.`})}if(!n.startsWith("inline:")){let l=ve(e,n);if(!ne(l))return Xi.test(n)?JSON.stringify({error:`Invalid run_test spec: "${n}" 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:n},invalidExample:{spec:n,ticketKey:n}}):JSON.stringify({error:`Test spec not found: ${n}`,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=sn(t?.options?.config);if(sr()>=a){let l=an(),p=i.ticketKey||l,u={runId:l,spec:i.ticketKey?`${i.ticketKey}: ${i.spec}`:i.spec,ticketKey:i.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};M.set(l,u),he.push({args:{...i,_queuedRunId:l},cwd:e,context:t}),J(p,"\u23F3",`Queued (${sr()}/${a} running, ${he.length} queued)`);let m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return s&&(m.resolvedFromJiraIssue=s,m.message+=` (spec built from Jira ${s})`),JSON.stringify(m)}let c=Date.now()-nr;c<Wi&&nr>0&&await new Promise(l=>setTimeout(l,Wi-c)),nr=Date.now();let d=dn(i,e,t);return s?ad(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function dn(r,e,t){let{spec:i,ticketKey:n,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||an(),l=i,p=!1;if(i.startsWith("inline:")){p=!0;let A=Xl(e);Yi(A,{recursive:!0}),l=Z(A,`${d}.txt`),Wl(l,i.slice(7).trim(),"utf-8")}let u=ve(e,".zibby","output","runs");Yi(u,{recursive:!0});let m=Z(u,`${d}.log`),f=Vl(m,{flags:"a"}),b=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,y=["test",l];b&&y.push("--agent",b),o&&y.push("--headless"),a&&y.push("--workflow",a),on&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${y.map(A=>/\s/.test(A)?JSON.stringify(A):A).join(" ")} cwd=${e}`);let _=nn("zibby",y,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),g={runId:d,spec:n?`${n}: ${i}`:i,ticketKey:n||null,specPath:l,logPath:m,isInline:p,pid:_.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=n||d,O="";function H(A){let R=cn(A).trim();if(!R)return;if(R.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let x=JSON.parse(R.slice(22));x.phase==="node_begin"?g.currentNode=x.node:x.phase==="node_end"&&(x.node&&!g.completedNodes.includes(x.node)&&g.completedNodes.push(x.node),g.currentNode===x.node&&(g.currentNode=null))}catch{}return}let D=R.match(/Session\s+(\S+)/);if(D&&!g.sessionId&&(g.sessionId=D[1],g.sessionPath=ve(e,ar,or,g.sessionId)),R.startsWith("\u250C ")||R.startsWith("\u250C ")){let x=R.slice(2).trim();g.currentNode=x,wt&&J(k,"\u25B6",`${x}`)}else if(R.startsWith("\u2514 ")||R.startsWith("\u2514 ")){let x=R.slice(2).trim();x.startsWith("done")?(g.currentNode&&!g.completedNodes.includes(g.currentNode)&&g.completedNodes.push(g.currentNode),wt&&J(k,"\u2714",`${g.currentNode||"node"} done ${x.replace("done","").trim()}`),g.currentNode=null):x.startsWith("failed")&&(wt&&J(k,"\u2718",`${g.currentNode||"node"} failed ${x.replace("failed","").trim()}`),g.currentNode=null)}else R.includes("Workflow completed")&&(g.currentNode=null,wt&&J(k,"\u2714",`Workflow completed (${Zi(Date.now()-g.startTime)})`))}function Te(A){let R=A.toString();g.output+=R,f.write(R),g.output.length>5e4&&(g.output=g.output.slice(-3e4)),O+=R;let D=O.split(`
618
618
  `);O=D.pop();for(let x of D)H(x)}return _.stdout.on("data",Te),_.stderr.on("data",A=>{let R=A.toString();g.error+=R,f.write(R),g.error.length>2e4&&(g.error=g.error.slice(-1e4))}),_.on("close",A=>{g.status=A===0?"passed":"failed",g.exitCode=A,g.endTime=Date.now(),O&&H(O),f.end();let R=Zi(Date.now()-g.startTime);if(A===0?J(k,"\u2705",`Passed (${R})`):J(k,"\u274C",`Failed (${R})`),g.isInline)try{Zl(g.specPath)}catch{}Vi()}),_.on("error",A=>{g.status="error",g.error+=`
619
- Spawn error: ${A.message}`,J(k,"\u274C",`Spawn error: ${A.message}`),f.end(),Vi()}),g._child=_,M.set(d,g),JSON.stringify({runId:d,spec:g.spec,ticketKey:g.ticketKey,status:"running",pid:_.pid,logFile:m})}function en(r){let e=Math.round(((r.endTime||Date.now())-r.startTime)/1e3),t=r.completedNodes||[],i=r.currentNode||null;if(r.status!=="running")return{elapsed:e,stage:r.status,completedNodes:t,currentNode:null};let n;return i?(n=`Actively executing node "${i}"`,t.length&&(n+=` (completed: ${t.join(", ")})`)):t.length?n=`Between nodes (completed: ${t.join(", ")})`:n="Starting up (initializing workflow)",n+=`. Elapsed: ${e}s. This is normal progress \u2014 do not cancel.`,{elapsed:e,stage:"running",currentNode:i,completedNodes:t,progress:n}}function ld(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let s=[...M.entries()].map(([l,p])=>{let u=en(p),m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:p.status,elapsed:u.elapsed,exitCode:p.exitCode,sessionId:p.sessionId||null};return p.status==="running"?(m.currentNode=u.currentNode,m.completedNodes=u.completedNodes,m.progress=u.progress):m.outputTail=p.output.slice(-500),m}),o=s.filter(l=>l.status==="running").length,a=s.filter(l=>l.status==="passed").length,c=s.filter(l=>l.status==="failed").length,d={total:s.length,running:o,passed:a,failed:c,runs:s};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let t=M.get(e);if(!t)return JSON.stringify({error:`Run not found: ${e}`});let i=en(t),n={runId:e,spec:t.spec,ticketKey:t.ticketKey,status:t.status,elapsed:i.elapsed,exitCode:t.exitCode,sessionId:t.sessionId||null};return t.status==="running"?(n.currentNode=i.currentNode,n.completedNodes=i.completedNodes,n.progress=i.progress):(n.outputTail=t.output.slice(-1e3),n.errorTail=t.error.slice(-500)),t.status==="running"&&(n._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(n)}function tn(r,e){if(e.status==="queued"){let t=he.findIndex(i=>i.args._queuedRunId===r);return t>=0&&he.splice(t,1),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}if(e.status!=="running")return{ok:!1,runId:r,error:`Run is not active (status: ${e.status})`};try{return e._child.kill("SIGTERM"),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}catch(t){return{ok:!1,runId:r,error:`Failed to cancel: ${t.message}`}}}function dd(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let i=[];for(let[n,s]of M.entries())(s.status==="running"||s.status==="queued")&&i.push(tn(n,s));return i.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:i.length,results:i})}let t=M.get(e);return JSON.stringify(t?tn(e,t):{error:`Run not found: ${e}`})}function pd(r,e){let t=M.get(r);if(t?.sessionPath&&ne(t.sessionPath))return t.sessionPath;if(t?.sessionId){let i=ve(e,cr,ar,t.sessionId);if(ne(i))return i}return null}function pn(r,e=""){let t=[];if(!ne(r))return t;for(let i of It(r,{withFileTypes:!0})){let n=e?`${e}/${i.name}`:i.name;if(i.isDirectory())t.push(...pn(Z(r,i.name),n));else{let s=Ql(Z(r,i.name));t.push({path:n,size:s.size})}}return t}function rn(r){if(!ne(r))return null;try{return JSON.parse(vt(r,"utf-8"))}catch{return null}}function un(r,e=2e3){if(!r||!ne(r))return"";try{return vt(r,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function ud({run:r,logTail:e,errorTail:t}){let n=`${e||""}
620
- ${t||""}`.toLowerCase(),s={runId:r?.runId||null,status:r?.status||null,exitCode:r?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return r?.status==="running"||r?.status==="queued"?{...s,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:n.includes("test spec not found")?{...s,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:n.includes("unknown command")&&n.includes("'run'")?{...s,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:n.includes("missing openai_api_key")||n.includes("didn't provide an api key")||n.includes("401")?{...s,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:n.includes("spawn error")||n.includes("enoent")?{...s,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:n.includes("security command failed")||n.includes("security process exited with code: 45")||n.includes("password not found for account")?{...s,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:s}function md(r,e){let{runId:t,type:i,node:n="execute_live",query:s,tail:o=3e3}=r;if(i==="search"){if(!s)return JSON.stringify({error:'query is required for type="search"'});let c=ve(e,cr,ar);if(!ne(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=s.toLowerCase();for(let p of It(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=Z(c,p.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let b=Z(u,f);if(ne(b))try{let y=vt(b,"utf-8");if(y.toLowerCase().includes(l)){let _=y.toLowerCase().indexOf(l),g=Math.max(0,_-100),k=Math.min(y.length,_+s.length+100);d.push({sessionId:p.name,artifact:h,snippet:y.slice(g,k)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:s,matches:d,total:d.length})}if(!t)return JSON.stringify({error:"runId is required for this type"});if(i==="log"){let c=M.get(t),d=un(c?.logPath,o);if(d)return JSON.stringify({runId:t,source:"run-log",totalLength:d.length,tail:d})}let a=pd(t,e);if(!a)return JSON.stringify({error:`No session found for run ${t}. The run may still be starting.`});switch(i){case"list":{let c=pn(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=rn(Z(a,n,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:n,result:c}:{error:`No result.json found in ${n}`})}case"events":{let c=rn(Z(a,n,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${n}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:n,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=Z(a,n,"raw_stream_output.txt");if(!ne(c))return JSON.stringify({error:`No log found in ${n}`});let d=vt(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:n,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${i}. Use: list, result, events, log, search`})}}function fd(r,e){let t=String(r?.runId||"all"),i=Number(r?.tail||2e3),n=t==="all"?[...M.keys()]:[t];if(n.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let s=n.map(c=>{let d=M.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=un(d.logPath,i),p=String(d.error||"").slice(-Math.max(200,i));return{...ud({run:d,logTail:l,errorTail:p}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:p}}),o=s.filter(c=>c.status==="failed"||c.status==="error"),a=s.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:s.length,failed:o.length,active:a.length,diagnoses:s})}function hd(r,e){let t=r?.directory||"test-specs",i=ve(e,t);if(!ne(i))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let s=function(o,a){for(let c of It(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(Z(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&n.push(d)}},n=[];return s(i,""),JSON.stringify({specs:n.map(o=>`${t}/${o}`),total:n.length,directory:t})}catch(n){return JSON.stringify({error:n.message})}}function mn(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 fn={...ue,id:"git-write",envKeys:[...ue.envKeys||[],...xe.envKeys||[],...je.envKeys||[]].filter((r,e,t)=>t.indexOf(r)===e),promptFragment:`${ue.promptFragment}
619
+ Spawn error: ${A.message}`,J(k,"\u274C",`Spawn error: ${A.message}`),f.end(),Vi()}),g._child=_,M.set(d,g),JSON.stringify({runId:d,spec:g.spec,ticketKey:g.ticketKey,status:"running",pid:_.pid,logFile:m})}function en(r){let e=Math.round(((r.endTime||Date.now())-r.startTime)/1e3),t=r.completedNodes||[],i=r.currentNode||null;if(r.status!=="running")return{elapsed:e,stage:r.status,completedNodes:t,currentNode:null};let n;return i?(n=`Actively executing node "${i}"`,t.length&&(n+=` (completed: ${t.join(", ")})`)):t.length?n=`Between nodes (completed: ${t.join(", ")})`:n="Starting up (initializing workflow)",n+=`. Elapsed: ${e}s. This is normal progress \u2014 do not cancel.`,{elapsed:e,stage:"running",currentNode:i,completedNodes:t,progress:n}}function ld(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let s=[...M.entries()].map(([l,p])=>{let u=en(p),m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:p.status,elapsed:u.elapsed,exitCode:p.exitCode,sessionId:p.sessionId||null};return p.status==="running"?(m.currentNode=u.currentNode,m.completedNodes=u.completedNodes,m.progress=u.progress):m.outputTail=p.output.slice(-500),m}),o=s.filter(l=>l.status==="running").length,a=s.filter(l=>l.status==="passed").length,c=s.filter(l=>l.status==="failed").length,d={total:s.length,running:o,passed:a,failed:c,runs:s};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let t=M.get(e);if(!t)return JSON.stringify({error:`Run not found: ${e}`});let i=en(t),n={runId:e,spec:t.spec,ticketKey:t.ticketKey,status:t.status,elapsed:i.elapsed,exitCode:t.exitCode,sessionId:t.sessionId||null};return t.status==="running"?(n.currentNode=i.currentNode,n.completedNodes=i.completedNodes,n.progress=i.progress):(n.outputTail=t.output.slice(-1e3),n.errorTail=t.error.slice(-500)),t.status==="running"&&(n._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(n)}function tn(r,e){if(e.status==="queued"){let t=he.findIndex(i=>i.args._queuedRunId===r);return t>=0&&he.splice(t,1),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}if(e.status!=="running")return{ok:!1,runId:r,error:`Run is not active (status: ${e.status})`};try{return e._child.kill("SIGTERM"),e.status="cancelled",e.endTime=Date.now(),{ok:!0,runId:r,status:"cancelled"}}catch(t){return{ok:!1,runId:r,error:`Failed to cancel: ${t.message}`}}}function dd(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let i=[];for(let[n,s]of M.entries())(s.status==="running"||s.status==="queued")&&i.push(tn(n,s));return i.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:i.length,results:i})}let t=M.get(e);return JSON.stringify(t?tn(e,t):{error:`Run not found: ${e}`})}function pd(r,e){let t=M.get(r);if(t?.sessionPath&&ne(t.sessionPath))return t.sessionPath;if(t?.sessionId){let i=ve(e,ar,or,t.sessionId);if(ne(i))return i}return null}function pn(r,e=""){let t=[];if(!ne(r))return t;for(let i of It(r,{withFileTypes:!0})){let n=e?`${e}/${i.name}`:i.name;if(i.isDirectory())t.push(...pn(Z(r,i.name),n));else{let s=Ql(Z(r,i.name));t.push({path:n,size:s.size})}}return t}function rn(r){if(!ne(r))return null;try{return JSON.parse(vt(r,"utf-8"))}catch{return null}}function un(r,e=2e3){if(!r||!ne(r))return"";try{return vt(r,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function ud({run:r,logTail:e,errorTail:t}){let n=`${e||""}
620
+ ${t||""}`.toLowerCase(),s={runId:r?.runId||null,status:r?.status||null,exitCode:r?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return r?.status==="running"||r?.status==="queued"?{...s,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:n.includes("test spec not found")?{...s,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:n.includes("unknown command")&&n.includes("'run'")?{...s,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:n.includes("missing openai_api_key")||n.includes("didn't provide an api key")||n.includes("401")?{...s,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:n.includes("spawn error")||n.includes("enoent")?{...s,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:n.includes("security command failed")||n.includes("security process exited with code: 45")||n.includes("password not found for account")?{...s,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:s}function md(r,e){let{runId:t,type:i,node:n="execute_live",query:s,tail:o=3e3}=r;if(i==="search"){if(!s)return JSON.stringify({error:'query is required for type="search"'});let c=ve(e,ar,or);if(!ne(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=s.toLowerCase();for(let p of It(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=Z(c,p.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let b=Z(u,f);if(ne(b))try{let y=vt(b,"utf-8");if(y.toLowerCase().includes(l)){let _=y.toLowerCase().indexOf(l),g=Math.max(0,_-100),k=Math.min(y.length,_+s.length+100);d.push({sessionId:p.name,artifact:h,snippet:y.slice(g,k)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:s,matches:d,total:d.length})}if(!t)return JSON.stringify({error:"runId is required for this type"});if(i==="log"){let c=M.get(t),d=un(c?.logPath,o);if(d)return JSON.stringify({runId:t,source:"run-log",totalLength:d.length,tail:d})}let a=pd(t,e);if(!a)return JSON.stringify({error:`No session found for run ${t}. The run may still be starting.`});switch(i){case"list":{let c=pn(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=rn(Z(a,n,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:n,result:c}:{error:`No result.json found in ${n}`})}case"events":{let c=rn(Z(a,n,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${n}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:n,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=Z(a,n,"raw_stream_output.txt");if(!ne(c))return JSON.stringify({error:`No log found in ${n}`});let d=vt(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:n,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${i}. Use: list, result, events, log, search`})}}function fd(r,e){let t=String(r?.runId||"all"),i=Number(r?.tail||2e3),n=t==="all"?[...M.keys()]:[t];if(n.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let s=n.map(c=>{let d=M.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=un(d.logPath,i),p=String(d.error||"").slice(-Math.max(200,i));return{...ud({run:d,logTail:l,errorTail:p}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:p}}),o=s.filter(c=>c.status==="failed"||c.status==="error"),a=s.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:s.length,failed:o.length,active:a.length,diagnoses:s})}function hd(r,e){let t=r?.directory||"test-specs",i=ve(e,t);if(!ne(i))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let s=function(o,a){for(let c of It(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(Z(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&n.push(d)}},n=[];return s(i,""),JSON.stringify({specs:n.map(o=>`${t}/${o}`),total:n.length,directory:t})}catch(n){return JSON.stringify({error:n.message})}}function mn(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 fn={...ue,id:"git-write",envKeys:[...ue.envKeys||[],...xe.envKeys||[],...je.envKeys||[]].filter((r,e,t)=>t.indexOf(r)===e),promptFragment:`${ue.promptFragment}
621
621
 
622
622
  ## Opening a pull request / merge request (git_open_pr)
623
623
  After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
@@ -629,7 +629,7 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
629
629
  To MERGE an open PR/MR, use the provider-agnostic tool:
630
630
  - git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
631
631
  { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
632
- Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(r,e,t){if(r!=="git_open_pr"&&r!=="git_merge_pr")return ue.handleToolCall(r,e,t);try{let i=e||{},n=i.repoUrl||i.repo_url||i.url;if(!n)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(r==="git_merge_pr"){let l=i.number??i.iid??i.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let p=mn(n);return p?p.provider==="github"?xe.handleToolCall("github_merge_pr",{owner:p.owner,repo:p.repo,number:l,mergeMethod:i.mergeMethod},t):je.handleToolCall("gitlab_accept_mr",{project:`${p.owner}/${p.repo}`,iid:l},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${n}. git_merge_pr supports github.com and gitlab.com.`})}let s=i.head||i.source_branch||i.sourceBranch||i.branch,o=i.base||i.target_branch||i.targetBranch,{title:a,body:c}=i;if(!s||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=mn(n);return d?d.provider==="github"?xe.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:s,base:o,title:a,body:c},t):je.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:s,target_branch:o,title:a,description:c},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${n}. git_open_pr supports github.com and gitlab.com.`})}catch(i){return JSON.stringify({error:i.message})}},tools:[...ue.tools||[],{name:"git_open_pr",description:"Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. The provider is auto-detected from repoUrl. Returns the REAL provider-returned url (pr_url = GitHub html_url / GitLab web_url) \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR is opened against (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},head:{type:"string",description:"Source branch to merge FROM (must already be pushed). GitLab alias: source_branch."},base:{type:"string",description:"Target branch to merge INTO (default: the repo/project default branch). GitLab alias: target_branch."},title:{type:"string",description:"PR/MR title"},body:{type:"string",description:"PR/MR description (markdown)"}},required:["repoUrl","head","title"]}},{name:"git_merge_pr",description:"Merge a pull request (GitHub) or accept a merge request (GitLab) by number. The provider is auto-detected from repoUrl. Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider \u2014 never fabricate it. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR belongs to (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},number:{type:"number",description:"The PR (GitHub) / MR (GitLab) number to merge. GitLab alias: iid."},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (GitHub only; default: squash). Ignored for GitLab."}},required:["repoUrl","number"]}}]};import{execFileSync as bn}from"child_process";import{existsSync as hr,mkdirSync as kn}from"fs";import{join as ce,basename as gd}from"path";import{randomBytes as yd}from"crypto";import{pathToFileURL as Xe}from"url";import{createRequire as wn}from"module";var ur=".zibby/memory",Sn="dolt",vn={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},mr="mem0",dr=new Map,Nt=new Map,Ot=!1,_d=wn(import.meta.url),Et=()=>yd(8).toString("hex"),Ie=()=>new Date().toISOString(),bd=[`CREATE TABLE IF NOT EXISTS chat_memory (
632
+ Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(r,e,t){if(r!=="git_open_pr"&&r!=="git_merge_pr")return ue.handleToolCall(r,e,t);try{let i=e||{},n=i.repoUrl||i.repo_url||i.url;if(!n)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(r==="git_merge_pr"){let l=i.number??i.iid??i.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let p=mn(n);return p?p.provider==="github"?xe.handleToolCall("github_merge_pr",{owner:p.owner,repo:p.repo,number:l,mergeMethod:i.mergeMethod},t):je.handleToolCall("gitlab_accept_mr",{project:`${p.owner}/${p.repo}`,iid:l},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${n}. git_merge_pr supports github.com and gitlab.com.`})}let s=i.head||i.source_branch||i.sourceBranch||i.branch,o=i.base||i.target_branch||i.targetBranch,{title:a,body:c}=i;if(!s||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=mn(n);return d?d.provider==="github"?xe.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:s,base:o,title:a,body:c},t):je.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:s,target_branch:o,title:a,description:c},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${n}. git_open_pr supports github.com and gitlab.com.`})}catch(i){return JSON.stringify({error:i.message})}},tools:[...ue.tools||[],{name:"git_open_pr",description:"Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. The provider is auto-detected from repoUrl. Returns the REAL provider-returned url (pr_url = GitHub html_url / GitLab web_url) \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR is opened against (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},head:{type:"string",description:"Source branch to merge FROM (must already be pushed). GitLab alias: source_branch."},base:{type:"string",description:"Target branch to merge INTO (default: the repo/project default branch). GitLab alias: target_branch."},title:{type:"string",description:"PR/MR title"},body:{type:"string",description:"PR/MR description (markdown)"}},required:["repoUrl","head","title"]}},{name:"git_merge_pr",description:"Merge a pull request (GitHub) or accept a merge request (GitLab) by number. The provider is auto-detected from repoUrl. Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider \u2014 never fabricate it. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR belongs to (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},number:{type:"number",description:"The PR (GitHub) / MR (GitLab) number to merge. GitLab alias: iid."},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (GitHub only; default: squash). Ignored for GitLab."}},required:["repoUrl","number"]}}]};import{execFileSync as bn}from"child_process";import{existsSync as fr,mkdirSync as kn}from"fs";import{join as ce,basename as gd}from"path";import{randomBytes as yd}from"crypto";import{pathToFileURL as Xe}from"url";import{createRequire as wn}from"module";var pr=".zibby/memory",Sn="dolt",vn={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},ur="mem0",lr=new Map,Nt=new Map,Ot=!1,_d=wn(import.meta.url),Et=()=>yd(8).toString("hex"),Ie=()=>new Date().toISOString(),bd=[`CREATE TABLE IF NOT EXISTS chat_memory (
633
633
  id VARCHAR(64) PRIMARY KEY,
634
634
  memory_key VARCHAR(160),
635
635
  category VARCHAR(32) NOT NULL,
@@ -660,10 +660,10 @@ To MERGE an open PR/MR, use the provider-agnostic tool:
660
660
  tasks_failed INT DEFAULT 0,
661
661
  key_facts TEXT,
662
662
  created_at VARCHAR(32) NOT NULL
663
- )`],hn=new Set;function F(r,e){return bn(Sn,e,{...vn,cwd:r})}function ge(r,e){try{let t=F(r,["sql","-q",e,"-r","json"]);return JSON.parse(t.trim()).rows||[]}catch{return[]}}function K(r,e){F(r,["sql","-q",e])}function Rt(r){if(hn.has(r))return!0;if(!hr(ce(r,".dolt"))){if(!kd())return!1;kn(r,{recursive:!0}),F(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${bd.join(`;
664
- `)};`;K(r,e);try{K(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{K(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return hn.add(r),!0}function kd(){try{return bn(Sn,["version"],{...vn,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function fr(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function Ce(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function gr(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 In(r){let e=new Map;for(let t of r||[]){let i=fr(t.content),n=t.memory_key?`key:${t.memory_key}`:i?`norm:${i}`:"";if(!n)continue;let s=e.get(n);if(!s){e.set(n,t);continue}let o=Ce(s.tier),a=Ce(t.tier);if(a>o){e.set(n,t);continue}a===o&&Number(t.relevance||0)>Number(s.relevance||0)&&e.set(n,t)}return[...e.values()]}function At(r,e){let t=String(r??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function Qe(r,e){let t={recentSessions:Array.isArray(r?.recentSessions)?r.recentSessions:[],topMemories:Array.isArray(r?.topMemories)?r.topMemories:[],taskStats:Array.isArray(r?.taskStats)?r.taskStats:[],ticketFilter:r?.ticketFilter||null,backend:e||String(r?.backend||mr),error:r?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function gn(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(`- ${At(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 i=t.tier==="long"?"\u2605":"\xB7";e.push(`${i} [${t.category}] ${At(t.content,120)}`)}}return e.length===0?"":`## Memory Context
663
+ )`],hn=new Set;function F(r,e){return bn(Sn,e,{...vn,cwd:r})}function ge(r,e){try{let t=F(r,["sql","-q",e,"-r","json"]);return JSON.parse(t.trim()).rows||[]}catch{return[]}}function K(r,e){F(r,["sql","-q",e])}function Rt(r){if(hn.has(r))return!0;if(!fr(ce(r,".dolt"))){if(!kd())return!1;kn(r,{recursive:!0}),F(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${bd.join(`;
664
+ `)};`;K(r,e);try{K(r,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{K(r,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return hn.add(r),!0}function kd(){try{return bn(Sn,["version"],{...vn,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function mr(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function Ce(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function hr(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 In(r){let e=new Map;for(let t of r||[]){let i=mr(t.content),n=t.memory_key?`key:${t.memory_key}`:i?`norm:${i}`:"";if(!n)continue;let s=e.get(n);if(!s){e.set(n,t);continue}let o=Ce(s.tier),a=Ce(t.tier);if(a>o){e.set(n,t);continue}a===o&&Number(t.relevance||0)>Number(s.relevance||0)&&e.set(n,t)}return[...e.values()]}function At(r,e){let t=String(r??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function Qe(r,e){let t={recentSessions:Array.isArray(r?.recentSessions)?r.recentSessions:[],topMemories:Array.isArray(r?.topMemories)?r.topMemories:[],taskStats:Array.isArray(r?.taskStats)?r.taskStats:[],ticketFilter:r?.ticketFilter||null,backend:e||String(r?.backend||ur),error:r?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function gn(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(`- ${At(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 i=t.tier==="long"?"\u2605":"\xB7";e.push(`${i} [${t.category}] ${At(t.content,120)}`)}}return e.length===0?"":`## Memory Context
665
665
  ${e.join(`
666
- `)}`}function Tt(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:At(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:At(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function wd(r,e){let t=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(t==="mem0"||t==="dolt")return t;let i=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(i==="mem0"||i==="dolt")return i;if(Nt.has(r))return Nt.get(r);try{let n=ce(r,".zibby.config.mjs");if(hr(n)){let s=await import(Xe(n).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return Nt.set(r,o),o}}catch{}return Nt.set(r,mr),mr}function Nn(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${gd(r||process.cwd())}`}var Sd="mem0";function On(r){let e=ce(r,ur,Sd);return{dir:e,vectorDbPath:ce(e,"vectors.db"),historyDbPath:ce(e,"history.db")}}function vd(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(),i=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),n=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),s=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=On(r||process.cwd());return{llm:{provider:"openai",config:{model:i,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:n,embeddingDims:s,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function Rn(r){let e=r||process.cwd();if(dr.has(e))return dr.get(e);let t;try{let a=wn(Xe(ce(e,"package.json")).href).resolve("mem0ai/oss");t=await import(Xe(a).href)}catch{try{let o=_d.resolve("mem0ai/oss");t=await import(Xe(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let i=t?.Memory;if(!i)throw new Error("mem0ai/oss does not export Memory");let n=vd(e);if(n)try{kn(On(e).dir,{recursive:!0})}catch{}let s=n?new i(n):new i;return dr.set(e,s),s}function yn(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(i=>({id:i?.id||Et(),memory_key:i?.metadata?.memoryKey||i?.metadata?.memory_key||null,category:i?.metadata?.category||"fact",content:i?.memory||i?.content||"",source:i?.metadata?.source||"mem0",ticket_key:i?.metadata?.ticketKey||i?.metadata?.ticket_key||null,tier:gr(i?.metadata?.tier||e,i?.metadata?.category||"fact"),relevance:Number(i?.score??i?.metadata?.relevance??.8),created_at:i?.created_at||i?.metadata?.created_at||Ie()})).filter(i=>String(i.content||"").trim().length>0)}var Ue={id:"dolt",store:(r,e)=>An(r,e),recall:(r,e)=>Ad(r,e),brief:(r,e)=>Ed(r,e),endSession:(r,e)=>xn(r,e),logTask:(r,e)=>jn(r,e),taskHistory:(r,e)=>Ln(r,e)},Id={id:"mem0",store:(r,e,t)=>Td(r,e,t),recall:(r,e,t)=>En(r,e,t),brief:(r,e,t)=>xd(r,e,t),endSession:(r,e)=>xn(r,e),logTask:(r,e)=>jn(r,e),taskHistory:(r,e)=>Ln(r,e)},Nd={dolt:Ue,mem0:Id};async function _n(r,e){let t=await wd(r,e);return Nd[t]||Ue}var Tn={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
666
+ `)}`}function Tt(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:At(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:At(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function wd(r,e){let t=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(t==="mem0"||t==="dolt")return t;let i=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(i==="mem0"||i==="dolt")return i;if(Nt.has(r))return Nt.get(r);try{let n=ce(r,".zibby.config.mjs");if(fr(n)){let s=await import(Xe(n).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return Nt.set(r,o),o}}catch{}return Nt.set(r,ur),ur}function Nn(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${gd(r||process.cwd())}`}var Sd="mem0";function On(r){let e=ce(r,pr,Sd);return{dir:e,vectorDbPath:ce(e,"vectors.db"),historyDbPath:ce(e,"history.db")}}function vd(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(),i=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),n=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),s=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=On(r||process.cwd());return{llm:{provider:"openai",config:{model:i,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:n,embeddingDims:s,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function Rn(r){let e=r||process.cwd();if(lr.has(e))return lr.get(e);let t;try{let a=wn(Xe(ce(e,"package.json")).href).resolve("mem0ai/oss");t=await import(Xe(a).href)}catch{try{let o=_d.resolve("mem0ai/oss");t=await import(Xe(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let i=t?.Memory;if(!i)throw new Error("mem0ai/oss does not export Memory");let n=vd(e);if(n)try{kn(On(e).dir,{recursive:!0})}catch{}let s=n?new i(n):new i;return lr.set(e,s),s}function yn(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(i=>({id:i?.id||Et(),memory_key:i?.metadata?.memoryKey||i?.metadata?.memory_key||null,category:i?.metadata?.category||"fact",content:i?.memory||i?.content||"",source:i?.metadata?.source||"mem0",ticket_key:i?.metadata?.ticketKey||i?.metadata?.ticket_key||null,tier:hr(i?.metadata?.tier||e,i?.metadata?.category||"fact"),relevance:Number(i?.score??i?.metadata?.relevance??.8),created_at:i?.created_at||i?.metadata?.created_at||Ie()})).filter(i=>String(i.content||"").trim().length>0)}var Ue={id:"dolt",store:(r,e)=>An(r,e),recall:(r,e)=>Ad(r,e),brief:(r,e)=>Ed(r,e),endSession:(r,e)=>xn(r,e),logTask:(r,e)=>jn(r,e),taskHistory:(r,e)=>Ln(r,e)},Id={id:"mem0",store:(r,e,t)=>Td(r,e,t),recall:(r,e,t)=>En(r,e,t),brief:(r,e,t)=>xd(r,e,t),endSession:(r,e)=>xn(r,e),logTask:(r,e)=>jn(r,e),taskHistory:(r,e)=>Ln(r,e)},Nd={dolt:Ue,mem0:Id};async function _n(r,e){let t=await wd(r,e);return Nd[t]||Ue}var Tn={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
667
667
  You have persistent memory across sessions. Use it to avoid losing context:
668
668
  - **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
669
669
  - **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
@@ -679,9 +679,9 @@ You have persistent memory across sessions. Use it to avoid losing context:
679
679
  - When the user's request is complete: call memory_end_session
680
680
 
681
681
  ### Categories for memory_store
682
- fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,e={}){let t=r?.options?.workspace||process.cwd(),i=ce(t,ur),n=await _n(t,r),s=n.id;if(s==="dolt"&&!Rt(i)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:Qe({backend:s,error:o},s),promptContext:"",debugPreview:Tt(Qe({backend:s,error:o},s)),error:o}}try{let o=await n.brief(e,i,t),a=JSON.parse(o||"{}"),c=Qe({...a,backend:s},s);return{backend:s,brief:c,promptContext:gn(c),debugPreview:Tt(c),error:c.error||null}}catch(o){if(s==="mem0"&&n!==Ue&&Rt(i)){if(!Ot){Ot=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
683
- `)}catch{}}try{let d=await Ue.brief(e,i,t),l=JSON.parse(d||"{}"),p=Qe({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:gn(p),debugPreview:Tt(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=Qe({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:Tt(c),error:a}}},async handleToolCall(r,e,t){let i=t?.options?.workspace||process.cwd(),n=ce(i,ur),s=await _n(i,t),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!Rt(n))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(r){case"memory_store":return d.store(e,n,i);case"memory_recall":return d.recall(e,n,i);case"memory_brief":return d.brief(e,n,i);case"memory_end_session":return d.endSession(e,n,i);case"task_log":return d.logTask(e,n,i);case"task_history":return d.taskHistory(e,n,i);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(d){if(o==="mem0"&&s!==Ue){if(Rt(n)){if(!Ot){Ot=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
684
- `)}catch{}}try{return await c(Ue)}catch(l){return JSON.stringify({error:l.message,backend:"dolt",degradedFrom:"mem0"})}}return JSON.stringify({error:`mem0 unavailable (${d.message}); dolt fallback also unavailable`,backend:"mem0"})}return JSON.stringify({error:d.message})}},tools:[{name:"memory_store",description:"Save a fact, decision, or context to persistent memory. Survives across sessions.",input_schema:{type:"object",properties:{memoryKey:{type:"string",description:"Stable semantic identity key (e.g. user.jira.default_board)"},content:{type:"string",description:"The information to remember"},category:{type:"string",enum:["fact","decision","context","insight","preference","credential","url","error","workaround"],description:"Category of memory"},tier:{type:"string",enum:["short","mid","long"],description:"Memory tier: short (session/24h), mid (days/weeks), long (permanent)"},source:{type:"string",description:'Where this info came from (e.g. "jira", "github", "user", "test_run")'},ticketKey:{type:"string",description:"Related ticket key (optional)"},infer:{type:"boolean",description:"true = LLM distills/dedupes facts (costs tokens); false = store raw, embed-only, free",default:!1}},required:["content","category"]}},{name:"memory_recall",description:"Search persistent memory by keyword, category, ticket, or tier. Returns matching facts and context.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search text (matches content)"},category:{type:"string",description:"Filter by category"},ticketKey:{type:"string",description:"Filter by ticket key"},tier:{type:"string",enum:["short","mid","long"],description:"Filter by memory tier"},limit:{type:"number",description:"Max results (default: 20)"}}}},{name:"memory_brief",description:"Get a compact briefing: recent session summaries + top relevant facts. Call at the start of a conversation.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Focus briefing on a specific ticket (optional)"}}}},{name:"memory_end_session",description:"End the current session and save a summary for future recall. Call when a task is complete.",input_schema:{type:"object",properties:{summary:{type:"string",description:"What happened in this session (1-3 sentences)"},tickets:{type:"string",description:"Comma-separated ticket keys covered"},tasksRun:{type:"number",description:"Number of tasks/tests run"},tasksPassed:{type:"number",description:"Number passed"},tasksFailed:{type:"number",description:"Number failed"},keyFacts:{type:"string",description:"Key facts worth remembering from this session (semicolon-separated)"}},required:["summary"]}},{name:"task_log",description:"Record a completed task (test run, analysis, generation) to persistent history.",input_schema:{type:"object",properties:{title:{type:"string",description:"Task description"},type:{type:"string",enum:["test_run","generate","analysis","research","other"],description:"Task type"},status:{type:"string",enum:["passed","failed","cancelled","error"],description:"Outcome"},ticketKey:{type:"string",description:"Related ticket key"},specPath:{type:"string",description:"Spec file path (if test run)"},resultSummary:{type:"string",description:"Brief result description"}},required:["title","type","status"]}},{name:"task_history",description:"Query past tasks by ticket, status, or type. See what was done before.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Filter by ticket key"},type:{type:"string",description:"Filter by task type"},status:{type:"string",description:"Filter by status"},limit:{type:"number",description:"Max results (default: 20)"}}}}]};function An(r,e){let{content:t,category:i,source:n,ticketKey:s,tier:o,memoryKey:a}=r;if(!t||!i)return JSON.stringify({error:"content and category are required"});let c=fr(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=gr(o,i),l=d==="long"?1:d==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let y=ge(e,`SELECT id, tier, relevance
682
+ fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(r,e={}){let t=r?.options?.workspace||process.cwd(),i=ce(t,pr),n=await _n(t,r),s=n.id;if(s==="dolt"&&!Rt(i)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:Qe({backend:s,error:o},s),promptContext:"",debugPreview:Tt(Qe({backend:s,error:o},s)),error:o}}try{let o=await n.brief(e,i,t),a=JSON.parse(o||"{}"),c=Qe({...a,backend:s},s);return{backend:s,brief:c,promptContext:gn(c),debugPreview:Tt(c),error:c.error||null}}catch(o){if(s==="mem0"&&n!==Ue&&Rt(i)){if(!Ot){Ot=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
683
+ `)}catch{}}try{let d=await Ue.brief(e,i,t),l=JSON.parse(d||"{}"),p=Qe({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:gn(p),debugPreview:Tt(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=Qe({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:Tt(c),error:a}}},async handleToolCall(r,e,t){let i=t?.options?.workspace||process.cwd(),n=ce(i,pr),s=await _n(i,t),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!Rt(n))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(r){case"memory_store":return d.store(e,n,i);case"memory_recall":return d.recall(e,n,i);case"memory_brief":return d.brief(e,n,i);case"memory_end_session":return d.endSession(e,n,i);case"task_log":return d.logTask(e,n,i);case"task_history":return d.taskHistory(e,n,i);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(d){if(o==="mem0"&&s!==Ue){if(Rt(n)){if(!Ot){Ot=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
684
+ `)}catch{}}try{return await c(Ue)}catch(l){return JSON.stringify({error:l.message,backend:"dolt",degradedFrom:"mem0"})}}return JSON.stringify({error:`mem0 unavailable (${d.message}); dolt fallback also unavailable`,backend:"mem0"})}return JSON.stringify({error:d.message})}},tools:[{name:"memory_store",description:"Save a fact, decision, or context to persistent memory. Survives across sessions.",input_schema:{type:"object",properties:{memoryKey:{type:"string",description:"Stable semantic identity key (e.g. user.jira.default_board)"},content:{type:"string",description:"The information to remember"},category:{type:"string",enum:["fact","decision","context","insight","preference","credential","url","error","workaround"],description:"Category of memory"},tier:{type:"string",enum:["short","mid","long"],description:"Memory tier: short (session/24h), mid (days/weeks), long (permanent)"},source:{type:"string",description:'Where this info came from (e.g. "jira", "github", "user", "test_run")'},ticketKey:{type:"string",description:"Related ticket key (optional)"},infer:{type:"boolean",description:"true = LLM distills/dedupes facts (costs tokens); false = store raw, embed-only, free",default:!1}},required:["content","category"]}},{name:"memory_recall",description:"Search persistent memory by keyword, category, ticket, or tier. Returns matching facts and context.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search text (matches content)"},category:{type:"string",description:"Filter by category"},ticketKey:{type:"string",description:"Filter by ticket key"},tier:{type:"string",enum:["short","mid","long"],description:"Filter by memory tier"},limit:{type:"number",description:"Max results (default: 20)"}}}},{name:"memory_brief",description:"Get a compact briefing: recent session summaries + top relevant facts. Call at the start of a conversation.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Focus briefing on a specific ticket (optional)"}}}},{name:"memory_end_session",description:"End the current session and save a summary for future recall. Call when a task is complete.",input_schema:{type:"object",properties:{summary:{type:"string",description:"What happened in this session (1-3 sentences)"},tickets:{type:"string",description:"Comma-separated ticket keys covered"},tasksRun:{type:"number",description:"Number of tasks/tests run"},tasksPassed:{type:"number",description:"Number passed"},tasksFailed:{type:"number",description:"Number failed"},keyFacts:{type:"string",description:"Key facts worth remembering from this session (semicolon-separated)"}},required:["summary"]}},{name:"task_log",description:"Record a completed task (test run, analysis, generation) to persistent history.",input_schema:{type:"object",properties:{title:{type:"string",description:"Task description"},type:{type:"string",enum:["test_run","generate","analysis","research","other"],description:"Task type"},status:{type:"string",enum:["passed","failed","cancelled","error"],description:"Outcome"},ticketKey:{type:"string",description:"Related ticket key"},specPath:{type:"string",description:"Spec file path (if test run)"},resultSummary:{type:"string",description:"Brief result description"}},required:["title","type","status"]}},{name:"task_history",description:"Query past tasks by ticket, status, or type. See what was done before.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Filter by ticket key"},type:{type:"string",description:"Filter by task type"},status:{type:"string",description:"Filter by status"},limit:{type:"number",description:"Max results (default: 20)"}}}}]};function An(r,e){let{content:t,category:i,source:n,ticketKey:s,tier:o,memoryKey:a}=r;if(!t||!i)return JSON.stringify({error:"content and category are required"});let c=mr(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=hr(o,i),l=d==="long"?1:d==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let y=ge(e,`SELECT id, tier, relevance
685
685
  FROM chat_memory
686
686
  WHERE memory_key = ${S(p)}
687
687
  ORDER BY created_at DESC
@@ -697,11 +697,11 @@ fact, decision, context, insight, credential, url, error, workaround`,resolve(){
697
697
  FROM chat_memory
698
698
  WHERE category = ${S(i)}
699
699
  ORDER BY created_at DESC
700
- LIMIT 200`).find(b=>fr(b.content)===c);if(m){let b=String(m.tier||"mid"),y=Number(m.relevance||0),_=Ce(d)>Ce(b),g=l>y;if(_||g){K(e,`UPDATE chat_memory
700
+ LIMIT 200`).find(b=>mr(b.content)===c);if(m){let b=String(m.tier||"mid"),y=Number(m.relevance||0),_=Ce(d)>Ce(b),g=l>y;if(_||g){K(e,`UPDATE chat_memory
701
701
  SET tier = ${S(_?d:b)},
702
702
  relevance = ${Math.max(l,y)}
703
703
  WHERE id = ${S(m.id)}`);try{F(e,["add","."]),F(e,["commit","-m",`memory promote: ${i} \u2014 ${String(t).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:i,tier:_?d:b,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:i,tier:b,deduped:!0,promoted:!1})}let f=Et(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;K(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
704
- VALUES (${S(f)}, ${S(p||null)}, ${S(i)}, ${S(t)}, ${S(n)}, ${S(s)}, ${S(h)}, ${S(d)}, ${l}, ${S(Ie())})`);try{F(e,["add","."]),F(e,["commit","-m",`memory: ${i} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:i,tier:d,memoryKey:p||null,stored:t.slice(0,100)})}function Od(r){let e=String(r||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var pr=new Map;async function Rd(r,e){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return Od(process.env.ZIBBY_MEM0_INFER);let t=e||process.cwd();if(pr.has(t))return pr.get(t);let i=!1;try{let n=ce(t,".zibby.config.mjs");hr(n)&&(i=(await import(Xe(n).href))?.default?.memory?.infer===!0)}catch{}return pr.set(t,i),i}async function Td(r,e,t){let{content:i,category:n,source:s,ticketKey:o,tier:a,memoryKey:c,infer:d}=r;if(!i||!n)return JSON.stringify({error:"content and category are required"});try{let l=await Rn(t),p=Nn(t),u=gr(a,n),m=await Rd(d,t);return await l.add([{role:"user",content:String(i)}],{userId:p,infer:m,metadata:{memoryKey:c||null,category:n,tier:u,source:s||"zibby-chat",ticketKey:o||null,created_at:Ie()}}),JSON.stringify({ok:!0,backend:"mem0",userId:p,category:n,tier:u,infer:m,memoryKey:c||null,stored:String(i).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function Ad(r,e){let{query:t,category:i,ticketKey:n,tier:s,limit:o=20}=r,a=[];t&&a.push(`content LIKE ${S(`%${t}%`)}`),i&&a.push(`category = ${S(i)}`),n&&a.push(`ticket_key = ${S(n)}`),s&&a.push(`tier = ${S(s)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
704
+ VALUES (${S(f)}, ${S(p||null)}, ${S(i)}, ${S(t)}, ${S(n)}, ${S(s)}, ${S(h)}, ${S(d)}, ${l}, ${S(Ie())})`);try{F(e,["add","."]),F(e,["commit","-m",`memory: ${i} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:i,tier:d,memoryKey:p||null,stored:t.slice(0,100)})}function Od(r){let e=String(r||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var dr=new Map;async function Rd(r,e){if(typeof r=="boolean")return r;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return Od(process.env.ZIBBY_MEM0_INFER);let t=e||process.cwd();if(dr.has(t))return dr.get(t);let i=!1;try{let n=ce(t,".zibby.config.mjs");fr(n)&&(i=(await import(Xe(n).href))?.default?.memory?.infer===!0)}catch{}return dr.set(t,i),i}async function Td(r,e,t){let{content:i,category:n,source:s,ticketKey:o,tier:a,memoryKey:c,infer:d}=r;if(!i||!n)return JSON.stringify({error:"content and category are required"});try{let l=await Rn(t),p=Nn(t),u=hr(a,n),m=await Rd(d,t);return await l.add([{role:"user",content:String(i)}],{userId:p,infer:m,metadata:{memoryKey:c||null,category:n,tier:u,source:s||"zibby-chat",ticketKey:o||null,created_at:Ie()}}),JSON.stringify({ok:!0,backend:"mem0",userId:p,category:n,tier:u,infer:m,memoryKey:c||null,stored:String(i).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function Ad(r,e){let{query:t,category:i,ticketKey:n,tier:s,limit:o=20}=r,a=[];t&&a.push(`content LIKE ${S(`%${t}%`)}`),i&&a.push(`category = ${S(i)}`),n&&a.push(`ticket_key = ${S(n)}`),s&&a.push(`tier = ${S(s)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
705
705
  FROM chat_memory ${a.length>0?`WHERE ${a.join(" AND ")}`:""}
706
706
  ORDER BY relevance DESC, created_at DESC
707
707
  LIMIT ${o}`,l=ge(e,d);return JSON.stringify({total:l.length,memories:l})}async function En(r,e,t){let{query:i,category:n,ticketKey:s,tier:o,limit:a=20}=r;try{let c=await Rn(t),d=Nn(t),l=[];if(i&&String(i).trim()){let p=await c.search(String(i),{filters:{user_id:d},topK:a});l=yn(p)}else{let p=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=yn(p)}return n&&(l=l.filter(p=>p.category===n)),s&&(l=l.filter(p=>p.ticket_key===s)),o&&(l=l.filter(p=>p.tier===o)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function Ed(r,e){let{ticketKey:t}=r;Ld(e);let n=ge(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
@@ -712,7 +712,7 @@ fact, decision, context, insight, credential, url, error, workaround`,resolve(){
712
712
  VALUES (${S(c)}, ${S(t)}, ${S(i)}, ${n}, ${s}, ${o}, ${S(a)}, ${S(Ie())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))An({content:d,category:"fact",source:"session_summary",tier:"mid"},e);jd(e);try{F(e,["add","."]),F(e,["commit","-m",`session end: ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:t.slice(0,200)})}function jn(r,e){let{title:t,type:i,status:n,ticketKey:s,specPath:o,resultSummary:a}=r;if(!t||!i||!n)return JSON.stringify({error:"title, type, and status are required"});let c=Et(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;K(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
713
713
  VALUES (${S(c)}, ${S(s)}, ${S(i)}, ${S(t)}, ${S(n)}, ${S(o)}, ${S(d)}, ${S(a)}, ${S(Ie())}, ${S(Ie())})`);try{F(e,["add","."]),F(e,["commit","-m",`task: ${n} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:t,type:i,status:n})}function Ln(r,e){let{ticketKey:t,type:i,status:n,limit:s=20}=r,o=[];t&&o.push(`ticket_key = ${S(t)}`),i&&o.push(`type = ${S(i)}`),n&&o.push(`status = ${S(n)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
714
714
  FROM chat_tasks ${o.length>0?`WHERE ${o.join(" AND ")}`:""}
715
- ORDER BY created_at DESC LIMIT ${s}`,d=ge(e,c);return JSON.stringify({total:d.length,tasks:d})}function jd(r){try{K(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),K(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),K(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),K(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function Ld(r){try{let e=new Date(Date.now()-864e5).toISOString();K(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(e)}`)}catch{}}import{existsSync as $n,readFileSync as $d}from"node:fs";import{homedir as Pd}from"node:os";import{join as Cd,dirname as Ud,resolve as Jd}from"node:path";import{fileURLToPath as qd}from"node:url";function Dd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ud(qd(import.meta.url)),e=Jd(r,"..","bin","mcp-skill.mjs");return $n(e)?e:null}function Bd(){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=Cd(Pd(),".zibby","config.json");return $n(r)&&JSON.parse($d(r,"utf-8")).sessionToken||null}catch{return null}}function Md(){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 Fd(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function yr(r){return`${Fd()}:${r}`}async function _r(r,e){let t=Bd();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let i=`${Md()}/credits/review-memory`,n=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${n.status}): ${s.slice(0,300)}`)}return n.json()}var Pn={id:"kv-memory",serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
715
+ ORDER BY created_at DESC LIMIT ${s}`,d=ge(e,c);return JSON.stringify({total:d.length,tasks:d})}function jd(r){try{K(r,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),K(r,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),K(r,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),K(r,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function Ld(r){try{let e=new Date(Date.now()-864e5).toISOString();K(r,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${S(e)}`)}catch{}}import{existsSync as $n,readFileSync as $d}from"node:fs";import{homedir as Pd}from"node:os";import{join as Cd,dirname as Ud,resolve as Jd}from"node:path";import{fileURLToPath as qd}from"node:url";function Dd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ud(qd(import.meta.url)),e=Jd(r,"..","bin","mcp-skill.mjs");return $n(e)?e:null}function Bd(){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=Cd(Pd(),".zibby","config.json");return $n(r)&&JSON.parse($d(r,"utf-8")).sessionToken||null}catch{return null}}function Md(){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 Fd(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function gr(r){return`${Fd()}:${r}`}async function yr(r,e){let t=Bd();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let i=`${Md()}/credits/review-memory`,n=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${n.status}): ${s.slice(0,300)}`)}return n.json()}var Pn={id:"kv-memory",serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
716
716
  You have a PRIVATE per-agent key-value memory that survives across your
717
717
  stateless runs. It is automatically namespaced to YOU (this agent type) \u2014 other
718
718
  agents cannot see or collide with your entries, and you don't need to prefix
@@ -727,7 +727,7 @@ Tools:
727
727
  Use to record durable facts \u2014 e.g. dedup markers, prior decisions, summaries.
728
728
 
729
729
  Your namespace is added for you automatically; pass plain keys like
730
- "seen#owner/repo#42" or "lastRun".`,resolve(){let r=Dd();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 i=await _r("recall",{scope:yr(t)});return JSON.stringify(i)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let i=await _r("recall-prefix",{scopePrefix:yr(t)});return JSON.stringify(i)}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 i={scope:yr(t),content:e.content};e.metadata!=null&&(i.metadata=e.metadata);let n=await _r("store",i);return JSON.stringify(n)}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 Un,readFileSync as Kd}from"node:fs";import{homedir as Gd}from"node:os";import{join as Hd,dirname as zd,resolve as Yd}from"node:path";import{fileURLToPath as Wd}from"node:url";function Zd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=zd(Wd(import.meta.url)),e=Yd(r,"..","bin","mcp-skill.mjs");return Un(e)?e:null}function Jn(){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=Hd(Gd(),".zibby","config.json");return Un(r)&&JSON.parse(Kd(r,"utf-8")).sessionToken||null}catch{return null}}function qn(){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 Cn(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Vd(){let r={};for(let[e,t]of Object.entries(process.env)){let i=/^ZIBBY_STORE__(.+)$/.exec(e);if(!i)continue;let n=typeof t=="string"?t.trim():"";n&&(r[i[1]]=n)}return r}var Dn={};function br(r){let e={...Vd(),...Dn},t=Object.keys(e),i=typeof r=="string"?r.trim():"";return i?Object.prototype.hasOwnProperty.call(e,i)?{storeId:e[i],name:i}:{error:`unknown store '${i}'; 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 Qd(r){let e=Jn();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${qn()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`ensure_store failed (${t.status}): ${i.slice(0,300)}`)}return t.json()}async function kr(r,e,t){let i=Jn();if(!i)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let n=`${qn()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${e} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var Bn={id:"dataset-store",serverName:"dataset_store",allowedTools:["mcp__dataset_store__*"],description:"Dataset store \u2014 a durable, queryable store for structured JSON records; append rows now, run SQL-style aggregations/reports later",promptFragment:`## Dataset Store (durable, queryable structured-record store)
730
+ "seen#owner/repo#42" or "lastRun".`,resolve(){let r=Dd();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 i=await yr("recall",{scope:gr(t)});return JSON.stringify(i)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let i=await yr("recall-prefix",{scopePrefix:gr(t)});return JSON.stringify(i)}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 i={scope:gr(t),content:e.content};e.metadata!=null&&(i.metadata=e.metadata);let n=await yr("store",i);return JSON.stringify(n)}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 Un,readFileSync as Kd}from"node:fs";import{homedir as Gd}from"node:os";import{join as Hd,dirname as zd,resolve as Yd}from"node:path";import{fileURLToPath as Wd}from"node:url";function Zd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=zd(Wd(import.meta.url)),e=Yd(r,"..","bin","mcp-skill.mjs");return Un(e)?e:null}function Jn(){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=Hd(Gd(),".zibby","config.json");return Un(r)&&JSON.parse(Kd(r,"utf-8")).sessionToken||null}catch{return null}}function qn(){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 Cn(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Vd(){let r={};for(let[e,t]of Object.entries(process.env)){let i=/^ZIBBY_STORE__(.+)$/.exec(e);if(!i)continue;let n=typeof t=="string"?t.trim():"";n&&(r[i[1]]=n)}return r}var Dn={};function _r(r){let e={...Vd(),...Dn},t=Object.keys(e),i=typeof r=="string"?r.trim():"";return i?Object.prototype.hasOwnProperty.call(e,i)?{storeId:e[i],name:i}:{error:`unknown store '${i}'; 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 Qd(r){let e=Jn();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${qn()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`ensure_store failed (${t.status}): ${i.slice(0,300)}`)}return t.json()}async function br(r,e,t){let i=Jn();if(!i)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let n=`${qn()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${e} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var Bn={id:"dataset-store",serverName:"dataset_store",allowedTools:["mcp__dataset_store__*"],description:"Dataset store \u2014 a durable, queryable store for structured JSON records; append rows now, run SQL-style aggregations/reports later",promptFragment:`## Dataset Store (durable, queryable structured-record store)
731
731
  You have one or more durable stores for STRUCTURED records that survive across
732
732
  your stateless runs. Unlike key-value memory (for picking up where you left
733
733
  off), this is for accumulating DATA you want to QUERY and AGGREGATE later \u2014 e.g.
@@ -763,7 +763,7 @@ Tools:
763
763
  - sqlite_query: (sqlite stores) Run a SELECT (optionally with \`params\` for safe
764
764
  binding). Returns { columns, rows }. Read-only \u2014 never changes data.
765
765
  Pick the tool that matches the store's TYPE; using a dataset tool on a sqlite
766
- store (or vice-versa) is rejected.`,resolve(){let r=Zd();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=br(e?.store);if(t.error)return JSON.stringify({error:t.error});let i=typeof e?.agent=="string"&&e.agent.trim()?e.agent.trim():Cn(),n={record:e.record,agent:i};typeof e?.description=="string"&&e.description.trim()&&(n.description=e.description.trim());let s=await kr(t.storeId,"append",n);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"dataset_query":{let t=br(e?.store);if(t.error)return JSON.stringify({error:t.error});let i={};for(let s of["select","where","groupBy","orderBy","limit","since","until","agent"])e?.[s]!=null&&(i[s]=e[s]);let n=await kr(t.storeId,"query",i);return JSON.stringify({...n,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 i=typeof e?.type=="string"&&e.type.trim()?e.type.trim().toLowerCase():"sqlite",n=typeof e?.description=="string"?e.description.trim():"",s=await Qd({name:t,type:i,description:n,namespace:Cn()});return s?.storeId&&(Dn[t]=s.storeId),JSON.stringify({...s,store:t})}case"sqlite_exec":case"sqlite_query":{let t=br(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 i={sql:e.sql};Array.isArray(e?.params)&&(i.params=e.params);let n=await kr(t.storeId,"sql",i);return JSON.stringify({...n,store:t.name,storeId:t.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics.'},description:{type:"string",description:"What this store is for (shown in the Storage UI)."}},required:["name"]}},{name:"sqlite_exec",description:"For SQLITE-type stores: run SQL that CHANGES data \u2014 CREATE TABLE (use IF NOT EXISTS), INSERT, UPDATE, DELETE (one or more statements in one call). The store is a real, mutable SQLite database that persists across your stateless runs. Returns { rowsModified, wrote }. Use this to build schema on the fly and to update rows / track changing state (e.g. a queue with a status column).",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:'The SQL to run. May contain multiple statements separated by ";". Prefer CREATE TABLE IF NOT EXISTS for idempotent schema.'},params:{type:"array",description:'Optional positional bind params for a SINGLE parameterized statement (safe binding of values), e.g. sql "UPDATE t SET s=? WHERE id=?" with params ["done", 1].'}},required:["sql"]}},{name:"sqlite_query",description:"For SQLITE-type stores: run a read-only SELECT (optionally with `params` for safe binding) against the store's SQLite database. Returns { columns, rows }. Never changes data. Use to read back rows/state you stored earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:"A single SELECT statement. Use ? placeholders + `params` for any values."},params:{type:"array",description:'Optional positional bind params for the SELECT, e.g. ["linkedin_personal"].'}},required:["sql"]}}]};import{SKILL_META as Xd}from"@zibby/skill-ids";import{existsSync as Gn,readFileSync as ep}from"node:fs";import{homedir as tp}from"node:os";import{join as rp,dirname as ip,resolve as np}from"node:path";import{fileURLToPath as sp}from"node:url";function op(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ip(sp(import.meta.url)),e=np(r,"..","bin","mcp-skill.mjs");return Gn(e)?e:null}function xt(){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=rp(tp(),".zibby","config.json");return Gn(r)&&JSON.parse(ep(r,"utf-8")).sessionToken||null}catch{return null}}function jt(){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 ap(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Hn(r){return`${ap()}:artifact:${r}`}async function Mn(r){let e=xt();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let t=await fetch(`${jt()}/credits/artifacts`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`artifact write failed (${t.status}): ${i.slice(0,300)}`)}return t.json()}async function cp(r){let e=xt();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let t=await fetch(`${jt()}/credits/artifacts/${encodeURIComponent(r)}`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`artifact get failed (${t.status}): ${i.slice(0,300)}`)}return t.json()}async function Fn(r,e){let t=xt();if(!t)return;let i=await fetch(`${jt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:"store",scope:Hn(r),content:JSON.stringify(e)})});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`artifact index write failed (${i.status}): ${n.slice(0,200)}`)}}async function lp(r){let e=xt();if(!e)return null;let t=await fetch(`${jt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:"recall",scope:Hn(r)})});if(!t.ok)return null;let i=await t.json().catch(()=>null);if(!i?.found||!i?.memory?.content)return null;try{return JSON.parse(i.memory.content)}catch{return null}}function Kn(r){return typeof r?.html=="string"&&r.html.length>0?{format:"html",content:r.html}:typeof r?.markdown=="string"&&r.markdown.length>0?{format:"markdown",content:r.markdown}:null}var zn={id:"artifact",meta:Xd.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)
766
+ store (or vice-versa) is rejected.`,resolve(){let r=Zd();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=_r(e?.store);if(t.error)return JSON.stringify({error:t.error});let i=typeof e?.agent=="string"&&e.agent.trim()?e.agent.trim():Cn(),n={record:e.record,agent:i};typeof e?.description=="string"&&e.description.trim()&&(n.description=e.description.trim());let s=await br(t.storeId,"append",n);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"dataset_query":{let t=_r(e?.store);if(t.error)return JSON.stringify({error:t.error});let i={};for(let s of["select","where","groupBy","orderBy","limit","since","until","agent"])e?.[s]!=null&&(i[s]=e[s]);let n=await br(t.storeId,"query",i);return JSON.stringify({...n,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 i=typeof e?.type=="string"&&e.type.trim()?e.type.trim().toLowerCase():"sqlite",n=typeof e?.description=="string"?e.description.trim():"",s=await Qd({name:t,type:i,description:n,namespace:Cn()});return s?.storeId&&(Dn[t]=s.storeId),JSON.stringify({...s,store:t})}case"sqlite_exec":case"sqlite_query":{let t=_r(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 i={sql:e.sql};Array.isArray(e?.params)&&(i.params=e.params);let n=await br(t.storeId,"sql",i);return JSON.stringify({...n,store:t.name,storeId:t.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics.'},description:{type:"string",description:"What this store is for (shown in the Storage UI)."}},required:["name"]}},{name:"sqlite_exec",description:"For SQLITE-type stores: run SQL that CHANGES data \u2014 CREATE TABLE (use IF NOT EXISTS), INSERT, UPDATE, DELETE (one or more statements in one call). The store is a real, mutable SQLite database that persists across your stateless runs. Returns { rowsModified, wrote }. Use this to build schema on the fly and to update rows / track changing state (e.g. a queue with a status column).",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:'The SQL to run. May contain multiple statements separated by ";". Prefer CREATE TABLE IF NOT EXISTS for idempotent schema.'},params:{type:"array",description:'Optional positional bind params for a SINGLE parameterized statement (safe binding of values), e.g. sql "UPDATE t SET s=? WHERE id=?" with params ["done", 1].'}},required:["sql"]}},{name:"sqlite_query",description:"For SQLITE-type stores: run a read-only SELECT (optionally with `params` for safe binding) against the store's SQLite database. Returns { columns, rows }. Never changes data. Use to read back rows/state you stored earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:"A single SELECT statement. Use ? placeholders + `params` for any values."},params:{type:"array",description:'Optional positional bind params for the SELECT, e.g. ["linkedin_personal"].'}},required:["sql"]}}]};import{SKILL_META as Xd}from"@zibby/skill-ids";import{existsSync as Gn,readFileSync as ep}from"node:fs";import{homedir as tp}from"node:os";import{join as rp,dirname as ip,resolve as np}from"node:path";import{fileURLToPath as sp}from"node:url";function op(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ip(sp(import.meta.url)),e=np(r,"..","bin","mcp-skill.mjs");return Gn(e)?e:null}function xt(){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=rp(tp(),".zibby","config.json");return Gn(r)&&JSON.parse(ep(r,"utf-8")).sessionToken||null}catch{return null}}function jt(){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 ap(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function Hn(r){return`${ap()}:artifact:${r}`}async function Mn(r){let e=xt();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let t=await fetch(`${jt()}/credits/artifacts`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`artifact write failed (${t.status}): ${i.slice(0,300)}`)}return t.json()}async function cp(r){let e=xt();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let t=await fetch(`${jt()}/credits/artifacts/${encodeURIComponent(r)}`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`artifact get failed (${t.status}): ${i.slice(0,300)}`)}return t.json()}async function Fn(r,e){let t=xt();if(!t)return;let i=await fetch(`${jt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:"store",scope:Hn(r),content:JSON.stringify(e)})});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`artifact index write failed (${i.status}): ${n.slice(0,200)}`)}}async function lp(r){let e=xt();if(!e)return null;let t=await fetch(`${jt()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:"recall",scope:Hn(r)})});if(!t.ok)return null;let i=await t.json().catch(()=>null);if(!i?.found||!i?.memory?.content)return null;try{return JSON.parse(i.memory.content)}catch{return null}}function Kn(r){return typeof r?.html=="string"&&r.html.length>0?{format:"html",content:r.html}:typeof r?.markdown=="string"&&r.markdown.length>0?{format:"markdown",content:r.markdown}:null}var zn={id:"artifact",meta:Xd.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)
767
767
  You can PUBLISH a standalone page \u2014 a status report, a plan, a comparison table,
768
768
  a dashboard-y summary, a diagram, a "here's what I found" write-up \u2014 and get back
769
769
  a shareable URL. The page is a self-contained HTML (or Markdown) document; it is
@@ -784,7 +784,7 @@ Tools:
784
784
  To recall WHAT YOU HAVE ALREADY PUBLISHED, use your kv-memory tool
785
785
  kv_recall_prefix with keyPrefix "artifact:" \u2014 each entry is the index record
786
786
  { id, title, url, kind, createdAt, summary } for a page you made. (Publishing
787
- records this automatically; you don't store it yourself.)`,resolve(){let r=op();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/artifact.js","artifactSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"artifact_publish":{let t=typeof e?.title=="string"?e.title.trim():"";if(!t)return JSON.stringify({error:"title is required"});let i=Kn(e);if(!i)return JSON.stringify({error:"provide exactly one of html or markdown (non-empty string)"});let n={title:t,[i.format]:i.content};typeof e?.kind=="string"&&e.kind.trim()&&(n.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(n.favicon=e.favicon.trim());let s=await Mn(n),o=s?.id,a=s?.url;if(!o||!a)return JSON.stringify({error:"artifact write returned no id/url",response:s});let c={id:o,title:t,url:a,kind:n.kind||null,createdAt:s.createdAt||new Date().toISOString(),summary:typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():t};try{await Fn(o,c)}catch(d){return JSON.stringify({id:o,url:a,indexWarning:d.message})}return JSON.stringify({id:o,url:a})}case"artifact_update":{let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let i=Kn(e),n=typeof e?.title=="string"?e.title.trim():"";if(!i&&!n)return JSON.stringify({error:"nothing to update \u2014 pass a new title and/or html|markdown"});let s={id:t};n&&(s.title=n),i&&(s[i.format]=i.content),typeof e?.kind=="string"&&e.kind.trim()&&(s.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(s.favicon=e.favicon.trim());let o=await Mn(s),a=o?.url;if(!a)return JSON.stringify({error:"artifact update returned no url",response:o});let c=await lp(t)||{},d={...c,id:t,url:a,title:n||c.title||"Untitled",kind:s.kind||c.kind||null,createdAt:c.createdAt||o.createdAt||new Date().toISOString(),updatedAt:o.updatedAt||new Date().toISOString()};typeof e?.summary=="string"&&e.summary.trim()?d.summary=e.summary.trim():d.summary||(d.summary=d.title);try{await Fn(t,d)}catch(l){return JSON.stringify({id:t,url:a,indexWarning:l.message})}return JSON.stringify({id:t,url:a})}case"artifact_get":{let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let i=await cp(t);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"artifact_publish",description:"Publish a NEW self-contained, shareable page (report/plan/table/dashboard/diagram/write-up) and get back a shareable URL. Pass a title and EITHER html OR markdown. Keep all CSS/JS/images INLINE (inline <style>/<script>, data: URIs) \u2014 the page is sandboxed on view and external URLs are blocked. Returns { id, url }.",input_schema:{type:"object",properties:{title:{type:"string",description:"The page title (also the browser tab title)."},html:{type:"string",description:"The page content as a self-contained HTML document (or fragment). Provide this OR markdown, not both."},markdown:{type:"string",description:"The page content as Markdown (rendered to HTML on serve). Provide this OR html, not both."},kind:{type:"string",description:'Optional label for what this is, e.g. "report", "plan", "dashboard", "diagram". Stored in your index.'},favicon:{type:"string",description:'Optional emoji used as the browser-tab icon, e.g. "\u{1F4CA}".'},summary:{type:"string",description:"Optional one-line summary for your own index (defaults to the title). Helps you recall later what this page was."}},required:["title"]}},{name:"artifact_update",description:"Revise an EXISTING artifact by id \u2014 the shareable URL stays the same, the content is replaced (new version). Pass the fields to change (title and/or html|markdown). Returns { id, url }.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to update (from a prior artifact_publish, or your kv-memory "artifact:" index).'},title:{type:"string",description:"New title (optional)."},html:{type:"string",description:"New HTML content (optional). Provide this OR markdown."},markdown:{type:"string",description:"New Markdown content (optional). Provide this OR html."},kind:{type:"string",description:"Optional updated kind label."},favicon:{type:"string",description:"Optional updated emoji favicon."},summary:{type:"string",description:"Optional updated one-line index summary."}},required:["id"]}},{name:"artifact_get",description:'Fetch ONE artifact you published, by id \u2192 { metadata, content }. Use to reuse / edit / re-publish a page. To LIST what you have published, use your kv-memory tool kv_recall_prefix with keyPrefix "artifact:".',input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id."}},required:["id"]}}]};import{createRequire as dp}from"node:module";import{existsSync as Vn,mkdirSync as pp,writeFileSync as Yn}from"node:fs";import{dirname as Qn,join as Je,resolve as Xn}from"node:path";import{fileURLToPath as es}from"node:url";var ts=dp(import.meta.url),wr=null;function up(){return wr||(wr=ts("echarts")),wr}var Sr=null;function mp(){return Sr||(Sr=ts("@resvg/resvg-js")),Sr}var fp=800,hp=600,gp=4096,yp=16,Wn=60,rs="Noto Sans";function _p(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Qn(es(import.meta.url)),e=Xn(r,"..","bin","mcp-skill.mjs");return Vn(e)?e:null}function bp(){let r=Qn(es(import.meta.url)),e=Xn(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>Je(e,t)).filter(t=>Vn(t))}function kp(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?Je(e,"chart-render"):Je(process.cwd(),".zibby","output","charts"));return pp(t,{recursive:!0}),t}function Ne(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function Zn(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(yp,Math.min(gp,Math.round(t))):e}function vr(r){return typeof r!="string"||r.length<=Wn?r:`${r.slice(0,Wn-1)}\u2026`}function Lt(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=vr(t):Ne(t)&&typeof t.name=="string"&&(t.name=vr(t.name))}}function wp(r){for(let i of["xAxis","yAxis"]){let n=Array.isArray(r[i])?r[i]:r[i]?[r[i]]:[];for(let s of n)Ne(s)&&Lt(s.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let i of e)Ne(i)&&Lt(i.indicator);Ne(r.legend)&&Lt(r.legend.data);let t=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let i of t)Ne(i)&&(typeof i.name=="string"&&(i.name=vr(i.name)),Lt(i.data))}function Sp(r){let e=JSON.parse(JSON.stringify(r));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),Ne(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=rs),wp(e),e}function vp(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Ip(r,e,t){let n=up().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return n.setOption(r),n.renderToSVGString()}finally{n.dispose()}}function Np(r){let{Resvg:e}=mp();return new e(r,{font:{fontFiles:bp(),loadSystemFonts:!0,defaultFontFamily:rs}}).render().asPng()}var is={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)
787
+ records this automatically; you don't store it yourself.)`,resolve(){let r=op();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/artifact.js","artifactSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"artifact_publish":{let t=typeof e?.title=="string"?e.title.trim():"";if(!t)return JSON.stringify({error:"title is required"});let i=Kn(e);if(!i)return JSON.stringify({error:"provide exactly one of html or markdown (non-empty string)"});let n={title:t,[i.format]:i.content};typeof e?.kind=="string"&&e.kind.trim()&&(n.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(n.favicon=e.favicon.trim());let s=await Mn(n),o=s?.id,a=s?.url;if(!o||!a)return JSON.stringify({error:"artifact write returned no id/url",response:s});let c={id:o,title:t,url:a,kind:n.kind||null,createdAt:s.createdAt||new Date().toISOString(),summary:typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():t};try{await Fn(o,c)}catch(d){return JSON.stringify({id:o,url:a,indexWarning:d.message})}return JSON.stringify({id:o,url:a})}case"artifact_update":{let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let i=Kn(e),n=typeof e?.title=="string"?e.title.trim():"";if(!i&&!n)return JSON.stringify({error:"nothing to update \u2014 pass a new title and/or html|markdown"});let s={id:t};n&&(s.title=n),i&&(s[i.format]=i.content),typeof e?.kind=="string"&&e.kind.trim()&&(s.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(s.favicon=e.favicon.trim());let o=await Mn(s),a=o?.url;if(!a)return JSON.stringify({error:"artifact update returned no url",response:o});let c=await lp(t)||{},d={...c,id:t,url:a,title:n||c.title||"Untitled",kind:s.kind||c.kind||null,createdAt:c.createdAt||o.createdAt||new Date().toISOString(),updatedAt:o.updatedAt||new Date().toISOString()};typeof e?.summary=="string"&&e.summary.trim()?d.summary=e.summary.trim():d.summary||(d.summary=d.title);try{await Fn(t,d)}catch(l){return JSON.stringify({id:t,url:a,indexWarning:l.message})}return JSON.stringify({id:t,url:a})}case"artifact_get":{let t=typeof e?.id=="string"?e.id.trim():"";if(!t)return JSON.stringify({error:"id is required"});let i=await cp(t);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"artifact_publish",description:"Publish a NEW self-contained, shareable page (report/plan/table/dashboard/diagram/write-up) and get back a shareable URL. Pass a title and EITHER html OR markdown. Keep all CSS/JS/images INLINE (inline <style>/<script>, data: URIs) \u2014 the page is sandboxed on view and external URLs are blocked. Returns { id, url }.",input_schema:{type:"object",properties:{title:{type:"string",description:"The page title (also the browser tab title)."},html:{type:"string",description:"The page content as a self-contained HTML document (or fragment). Provide this OR markdown, not both."},markdown:{type:"string",description:"The page content as Markdown (rendered to HTML on serve). Provide this OR html, not both."},kind:{type:"string",description:'Optional label for what this is, e.g. "report", "plan", "dashboard", "diagram". Stored in your index.'},favicon:{type:"string",description:'Optional emoji used as the browser-tab icon, e.g. "\u{1F4CA}".'},summary:{type:"string",description:"Optional one-line summary for your own index (defaults to the title). Helps you recall later what this page was."}},required:["title"]}},{name:"artifact_update",description:"Revise an EXISTING artifact by id \u2014 the shareable URL stays the same, the content is replaced (new version). Pass the fields to change (title and/or html|markdown). Returns { id, url }.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to update (from a prior artifact_publish, or your kv-memory "artifact:" index).'},title:{type:"string",description:"New title (optional)."},html:{type:"string",description:"New HTML content (optional). Provide this OR markdown."},markdown:{type:"string",description:"New Markdown content (optional). Provide this OR html."},kind:{type:"string",description:"Optional updated kind label."},favicon:{type:"string",description:"Optional updated emoji favicon."},summary:{type:"string",description:"Optional updated one-line index summary."}},required:["id"]}},{name:"artifact_get",description:'Fetch ONE artifact you published, by id \u2192 { metadata, content }. Use to reuse / edit / re-publish a page. To LIST what you have published, use your kv-memory tool kv_recall_prefix with keyPrefix "artifact:".',input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id."}},required:["id"]}}]};import{createRequire as dp}from"node:module";import{existsSync as Vn,mkdirSync as pp,writeFileSync as Yn}from"node:fs";import{dirname as Qn,join as Je,resolve as Xn}from"node:path";import{fileURLToPath as es}from"node:url";var ts=dp(import.meta.url),kr=null;function up(){return kr||(kr=ts("echarts")),kr}var wr=null;function mp(){return wr||(wr=ts("@resvg/resvg-js")),wr}var fp=800,hp=600,gp=4096,yp=16,Wn=60,rs="Noto Sans";function _p(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Qn(es(import.meta.url)),e=Xn(r,"..","bin","mcp-skill.mjs");return Vn(e)?e:null}function bp(){let r=Qn(es(import.meta.url)),e=Xn(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>Je(e,t)).filter(t=>Vn(t))}function kp(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?Je(e,"chart-render"):Je(process.cwd(),".zibby","output","charts"));return pp(t,{recursive:!0}),t}function Ne(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function Zn(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(yp,Math.min(gp,Math.round(t))):e}function Sr(r){return typeof r!="string"||r.length<=Wn?r:`${r.slice(0,Wn-1)}\u2026`}function Lt(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=Sr(t):Ne(t)&&typeof t.name=="string"&&(t.name=Sr(t.name))}}function wp(r){for(let i of["xAxis","yAxis"]){let n=Array.isArray(r[i])?r[i]:r[i]?[r[i]]:[];for(let s of n)Ne(s)&&Lt(s.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let i of e)Ne(i)&&Lt(i.indicator);Ne(r.legend)&&Lt(r.legend.data);let t=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let i of t)Ne(i)&&(typeof i.name=="string"&&(i.name=Sr(i.name)),Lt(i.data))}function Sp(r){let e=JSON.parse(JSON.stringify(r));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),Ne(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=rs),wp(e),e}function vp(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Ip(r,e,t){let n=up().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return n.setOption(r),n.renderToSVGString()}finally{n.dispose()}}function Np(r){let{Resvg:e}=mp();return new e(r,{font:{fontFiles:bp(),loadSystemFonts:!0,defaultFontFamily:rs}}).render().asPng()}var is={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)
788
788
  You can render charts LOCALLY with the chart_render tool \u2014 pass a standard
789
789
  Apache ECharts option object as \`spec\` (any chart type: bar, line, pie,
790
790
  radar, scatter, heatmap, \u2026). It renders server-side to SVG/PNG files in the
@@ -818,8 +818,8 @@ notify. Post brief milestones so they know it's alive:
818
818
  commits, continuing\u2026"). Pass the chat target from your \`notify\` input when
819
819
  you have it (provider + chatId); otherwise it resolves from the runtime.
820
820
  Fire-and-forget \u2014 if it can't post, just keep working; never treat a failed
821
- progress ping as an error.`,resolve(){let r=Gp();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:i,chatId:n,mention:s}=Hp(e);if(!i||!n)return JSON.stringify({ok:!1,skipped:"no chat target"});let o=s&&i==="slack"?`<@${s}> ${t}`:t,a;i==="lark"?a=await B.handleToolCall("lark_send_message",{receive_id:n,text:t}):a=await $.handleToolCall("slack_post_message",{channel:n,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:i,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 zp}from"node:module";import{existsSync as ls,mkdirSync as Yp,writeFileSync as os}from"node:fs";import{dirname as ds,join as De,resolve as ps}from"node:path";import{fileURLToPath as us}from"node:url";var Wp=zp(import.meta.url),Ir=null;function Zp(){return Ir||(Ir=Wp("@resvg/resvg-js")),Ir}var ms=1200,Vp=627,Qp=4096,Xp=320,eu="#3b82f6",Oe="Noto Sans",tu=3;function ru(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ds(us(import.meta.url)),e=ps(r,"..","bin","mcp-skill.mjs");return ls(e)?e:null}function iu(){let r=ds(us(import.meta.url)),e=ps(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>De(e,t)).filter(t=>ls(t))}function nu(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?De(e,"social-card"):De(process.cwd(),".zibby","output","social-cards"));return Yp(t,{recursive:!0}),t}function as(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(Xp,Math.min(Qp,Math.round(t))):e}function qe(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function su(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function ou(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 fs(r,e,t){return String(r).length*e*t}function Nr(r,e,t,i){let n=String(r).trim().split(/\s+/).filter(Boolean),s=[],o="";for(let a of n){let c=o?`${o} ${a}`:a;o&&fs(c,t,i)>e?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function au(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 cs(r,e,t,i,n){let s=(Array.isArray(r)?r:[]).map(b=>String(b??"").trim()).filter(Boolean).slice(0,tu);if(s.length<2)return null;let o=24,a=54,c=26,d=90,l=17,p=s.map(b=>Math.max(96,fs(b,o,.58)+c*2)),u=p.reduce((b,y)=>b+y,0)+d*(s.length-1),m=e-u/2,f=t+a/2,h=[];for(let b=0;b<s.length;b++){let y=p[b];if(h.push(`<rect x="${m.toFixed(1)}" y="${t}" width="${y.toFixed(1)}" height="${a}" rx="${a/2}" fill="${n}" fill-opacity="0.12" stroke="${n}" stroke-opacity="0.55" stroke-width="1.5"/>`,`<text x="${(m+y/2).toFixed(1)}" y="${(f+o*.35).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${o}" font-weight="700" fill="${i.pillText}">${qe(s[b])}</text>`),m+=y,b<s.length-1){let _=m,g=m+d,k=(_+g)/2;h.push(`<line x1="${_.toFixed(1)}" y1="${f}" x2="${g.toFixed(1)}" y2="${f}" stroke="${n}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${k.toFixed(1)}" cy="${f}" r="${l}" fill="${n}"/>`,`<path d="M ${(k-8).toFixed(1)} ${f.toFixed(1)} l 5 5 l 9 -11" fill="none" stroke="${i.checkFg}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`),m=g}}return{svg:h.join(`
822
- `),height:a}}function cu(r){let{width:e,height:t,theme:i,accent:n}=r,s=au(i),o=e/2,a=Math.round(e*.07),c=e-a*2,d=String(r.headline).trim(),l=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",p=r.subhead?String(r.subhead).trim():"",u=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=e/ms,h=Math.round(22*f),b=Math.round(29*f),y=p?Nr(p,c,b,.52):[],_=Math.round(b*1.28),g=4,k=Math.round(26*f),O=Math.round(20*f),H=Math.round(24*f),Te=Math.round(30*f),A=!!(u||m),R=a,D=A?Math.round(110*f):a,x=t-R-D,ye=cs(r.diagram,o,0,s,n),Dr=(P,de)=>{let Me=g+k;return l&&(Me+=h+O),Me+=de.length*Math.round(P*1.16),y.length&&(Me+=H+y.length*_),ye&&(Me+=Te+ye.height),Me},Ft=[76,66,58,50,44,38].map(P=>Math.round(P*f)),Vs=4,Ae=Ft[Ft.length-1],Kt=Nr(d,c,Ae,.6);for(let P of Ft){let de=Nr(d,c,P,.6);if(de.length<=Vs&&Dr(P,de)<=x){Ae=P,Kt=de;break}}let Qs=Math.round(Ae*1.16),Xs=Dr(Ae,Kt),z=R+Math.max(0,(x-Xs)/2),se=[];se.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${s.bg}"/>`);let Br=Math.round(60*f);se.push(`<rect x="${(o-Br/2).toFixed(1)}" y="${z}" width="${Br}" height="${g}" rx="2" fill="${n}"/>`),z+=g+k,l&&(se.push(`<text x="${o}" y="${(z+h*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${n}">${qe(l)}</text>`),z+=h+O);for(let P of Kt)se.push(`<text x="${o}" y="${(z+Ae*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${Ae}" font-weight="700" fill="${s.fg}">${qe(P)}</text>`),z+=Qs;if(y.length){z+=H;for(let P of y)se.push(`<text x="${o}" y="${(z+b*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${b}" font-weight="400" fill="${s.muted}">${qe(P)}</text>`),z+=_}if(ye){z+=Te;let P=cs(r.diagram,o,z,s,n);P&&se.push(P.svg)}if(A){let P=Math.round(24*f),de=t-Math.round(46*f);m&&se.push(`<text x="${a}" y="${de}" text-anchor="start" font-family="${Oe}" font-size="${P}" font-weight="400" fill="${s.muted}">${qe(m)}</text>`),u&&se.push(`<text x="${e-a}" y="${de}" text-anchor="end" font-family="${Oe}" font-size="${P}" font-weight="700" fill="${n}">${qe(u)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
821
+ progress ping as an error.`,resolve(){let r=Gp();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:i,chatId:n,mention:s}=Hp(e);if(!i||!n)return JSON.stringify({ok:!1,skipped:"no chat target"});let o=s&&i==="slack"?`<@${s}> ${t}`:t,a;i==="lark"?a=await B.handleToolCall("lark_send_message",{receive_id:n,text:t}):a=await $.handleToolCall("slack_post_message",{channel:n,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:i,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 zp}from"node:module";import{existsSync as ls,mkdirSync as Yp,writeFileSync as os}from"node:fs";import{dirname as ds,join as De,resolve as ps}from"node:path";import{fileURLToPath as us}from"node:url";var Wp=zp(import.meta.url),vr=null;function Zp(){return vr||(vr=Wp("@resvg/resvg-js")),vr}var ms=1200,Vp=627,Qp=4096,Xp=320,eu="#3b82f6",Oe="Noto Sans",tu=3;function ru(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ds(us(import.meta.url)),e=ps(r,"..","bin","mcp-skill.mjs");return ls(e)?e:null}function iu(){let r=ds(us(import.meta.url)),e=ps(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>De(e,t)).filter(t=>ls(t))}function nu(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?De(e,"social-card"):De(process.cwd(),".zibby","output","social-cards"));return Yp(t,{recursive:!0}),t}function as(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(Xp,Math.min(Qp,Math.round(t))):e}function qe(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function su(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function ou(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 fs(r,e,t){return String(r).length*e*t}function Ir(r,e,t,i){let n=String(r).trim().split(/\s+/).filter(Boolean),s=[],o="";for(let a of n){let c=o?`${o} ${a}`:a;o&&fs(c,t,i)>e?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function au(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 cs(r,e,t,i,n){let s=(Array.isArray(r)?r:[]).map(b=>String(b??"").trim()).filter(Boolean).slice(0,tu);if(s.length<2)return null;let o=24,a=54,c=26,d=90,l=17,p=s.map(b=>Math.max(96,fs(b,o,.58)+c*2)),u=p.reduce((b,y)=>b+y,0)+d*(s.length-1),m=e-u/2,f=t+a/2,h=[];for(let b=0;b<s.length;b++){let y=p[b];if(h.push(`<rect x="${m.toFixed(1)}" y="${t}" width="${y.toFixed(1)}" height="${a}" rx="${a/2}" fill="${n}" fill-opacity="0.12" stroke="${n}" stroke-opacity="0.55" stroke-width="1.5"/>`,`<text x="${(m+y/2).toFixed(1)}" y="${(f+o*.35).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${o}" font-weight="700" fill="${i.pillText}">${qe(s[b])}</text>`),m+=y,b<s.length-1){let _=m,g=m+d,k=(_+g)/2;h.push(`<line x1="${_.toFixed(1)}" y1="${f}" x2="${g.toFixed(1)}" y2="${f}" stroke="${n}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${k.toFixed(1)}" cy="${f}" r="${l}" fill="${n}"/>`,`<path d="M ${(k-8).toFixed(1)} ${f.toFixed(1)} l 5 5 l 9 -11" fill="none" stroke="${i.checkFg}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`),m=g}}return{svg:h.join(`
822
+ `),height:a}}function cu(r){let{width:e,height:t,theme:i,accent:n}=r,s=au(i),o=e/2,a=Math.round(e*.07),c=e-a*2,d=String(r.headline).trim(),l=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",p=r.subhead?String(r.subhead).trim():"",u=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=e/ms,h=Math.round(22*f),b=Math.round(29*f),y=p?Ir(p,c,b,.52):[],_=Math.round(b*1.28),g=4,k=Math.round(26*f),O=Math.round(20*f),H=Math.round(24*f),Te=Math.round(30*f),A=!!(u||m),R=a,D=A?Math.round(110*f):a,x=t-R-D,ye=cs(r.diagram,o,0,s,n),Dr=(P,de)=>{let Me=g+k;return l&&(Me+=h+O),Me+=de.length*Math.round(P*1.16),y.length&&(Me+=H+y.length*_),ye&&(Me+=Te+ye.height),Me},Mt=[76,66,58,50,44,38].map(P=>Math.round(P*f)),Vs=4,Ae=Mt[Mt.length-1],Ft=Ir(d,c,Ae,.6);for(let P of Mt){let de=Ir(d,c,P,.6);if(de.length<=Vs&&Dr(P,de)<=x){Ae=P,Ft=de;break}}let Qs=Math.round(Ae*1.16),Xs=Dr(Ae,Ft),z=R+Math.max(0,(x-Xs)/2),se=[];se.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${s.bg}"/>`);let Br=Math.round(60*f);se.push(`<rect x="${(o-Br/2).toFixed(1)}" y="${z}" width="${Br}" height="${g}" rx="2" fill="${n}"/>`),z+=g+k,l&&(se.push(`<text x="${o}" y="${(z+h*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${n}">${qe(l)}</text>`),z+=h+O);for(let P of Ft)se.push(`<text x="${o}" y="${(z+Ae*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${Ae}" font-weight="700" fill="${s.fg}">${qe(P)}</text>`),z+=Qs;if(y.length){z+=H;for(let P of y)se.push(`<text x="${o}" y="${(z+b*.82).toFixed(1)}" text-anchor="middle" font-family="${Oe}" font-size="${b}" font-weight="400" fill="${s.muted}">${qe(P)}</text>`),z+=_}if(ye){z+=Te;let P=cs(r.diagram,o,z,s,n);P&&se.push(P.svg)}if(A){let P=Math.round(24*f),de=t-Math.round(46*f);m&&se.push(`<text x="${a}" y="${de}" text-anchor="start" font-family="${Oe}" font-size="${P}" font-weight="400" fill="${s.muted}">${qe(m)}</text>`),u&&se.push(`<text x="${e-a}" y="${de}" text-anchor="end" font-family="${Oe}" font-size="${P}" font-weight="700" fill="${n}">${qe(u)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
823
823
  ${se.join(`
824
824
  `)}
825
825
  </svg>`}function lu(r){let{Resvg:e}=Zp();return new e(r,{font:{fontFiles:iu(),loadSystemFonts:!0,defaultFontFamily:Oe}}).render().asPng()}var hs={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)
@@ -836,7 +836,7 @@ fields that capture the ONE key idea of your post:
836
836
  It renders server-side to a PNG in the run's output folder and returns
837
837
  { ok:true, files:[{ path, format:'png', bytes }] }. Pass the returned \`path\` as
838
838
  \`imagePath\` when you draft/publish a LinkedIn post to ATTACH the card as the
839
- post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=ru();if(!t)return{command:null,args:[],env:{},description:this.description};let i={},n=r&&e?De(r,e):null;n&&(i.ZIBBY_NODE_SESSION_PATH=n),r&&(i.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!i[s]&&process.env[s]&&(i[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/socialCard.js","socialCardSkill"],env:i,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 i=as(e?.width,ms),n=as(e?.height,Vp),s=e?.theme==="light"?"light":"dark",o=ou(e?.accent,eu),a;try{a=cu({width:i,height:n,theme:s,accent:o,headline:t,eyebrow:e?.eyebrow,subhead:e?.subhead,stat:e?.stat,footer:e?.footer,diagram:e?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=lu(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=nu(),l=su(e?.filename)||`social-card-${Date.now()}`,p=De(d,`${l}.png`);os(p,c);let u=[{path:p,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=De(d,`${l}.svg`);os(m,a,"utf-8"),u.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:i,height:n,theme:s,files:u})}catch(t){return JSON.stringify({error:`social_card_render failed: ${t.message}`})}},tools:[{name:"social_card_render",description:'Render a BRANDED "concept card" PNG LOCALLY (no external service) from structured fields \u2014 the clean LinkedIn concept-card style: bold headline + small uppercase eyebrow + optional supporting subhead, stat, footer, and an A\u2014\u2713\u2014B diagram. Returns { ok:true, files:[{ path, format:"png", bytes }] }. Pass the returned `path` as `imagePath` to a LinkedIn post tool to attach it as the post image. Example: { "headline":"No more copy-paste between AI tools", "eyebrow":"MY WORKFLOW", "stat":"11.8k stars", "footer":"Apache 2.0", "diagram":["Claude Code","Codex"] }.',input_schema:{type:"object",properties:{headline:{type:"string",description:"REQUIRED. The big, bold line \u2014 the single key idea/takeaway. Word-wrapped + auto-sized."},eyebrow:{type:"string",description:'Small uppercase kicker above the headline (e.g. "MY WORKFLOW", "OPEN SOURCE"). Rendered uppercased in the accent color.'},subhead:{type:"string",description:"One supporting line under the headline (muted)."},stat:{type:"string",description:'Optional stat, shown bottom-right in the accent color (e.g. "11.8k stars", "3x faster").'},footer:{type:"string",description:'Optional footer, shown bottom-left (muted) (e.g. "Apache 2.0", a repo name).'},diagram:{type:"array",items:{type:"string"},description:'Optional 2-3 short labels rendered as a chain of pills joined by a checkmark (A \u2014\u2713\u2014 B), e.g. ["Claude Code","Codex"].'},theme:{type:"string",enum:["dark","light"],description:"Card theme (default 'dark' \u2014 near-black bg, off-white text)."},accent:{type:"string",description:'Accent hex color (e.g. "#f97316"). Defaults to a tasteful blue (#3b82f6).'},width:{type:"number",description:"Image width in px (default 1200 \u2014 LinkedIn 1.91:1 link image)."},height:{type:"number",description:"Image height in px (default 627)."},filename:{type:"string",description:"Optional file basename (no extension); defaults to social-card-<timestamp>."},output:{type:"string",enum:["png","both"],description:"Which file(s) to write (default 'png'; 'both' also writes the .svg)."}},required:["headline"]}}]};import{spawnSync as du}from"node:child_process";import{existsSync as q,readdirSync as _s,statSync as bs,writeFileSync as Rr,mkdirSync as Tr}from"node:fs";import{dirname as Or,extname as Ut,join as C,relative as pu,resolve as Ct}from"node:path";import{tmpdir as Ar}from"node:os";import{fileURLToPath as uu}from"node:url";import{SKILL_META as mu}from"@zibby/skill-ids";import{binPath as fu}from"@zibby/bin-oxlint";import{binPath as hu}from"@zibby/bin-semgrep";function gu(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=fu();if(r&&q(r))return r}catch{}return"oxlint"}function yu(){if(process.env.SEMGREP_CORE_BIN)return process.env.SEMGREP_CORE_BIN;try{let r=hu();if(r&&q(r))return r}catch{}return"semgrep-core"}function _u(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Or(uu(import.meta.url)),e=Ct(r,"..","bin","mcp-skill.mjs");return q(e)?e:null}var ks=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),bu=400,ku={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"}},wu=[".oxlintrc.json",".oxlintrc","oxlint.json"],$t=null;function Su(){if($t&&q($t))return $t;try{let r=C(Ar(),"zibby-code-scan");Tr(r,{recursive:!0});let e=C(r,"oxlintrc.curated.json");return Rr(e,JSON.stringify(ku),"utf-8"),$t=e,e}catch{return null}}var ws={".java":"java",".py":"python",".go":"go",".rb":"ruby",".php":"php"},gs=Object.keys(ws),Ss={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(...);"}]}]}]},vu=[".semgrep.yml",".semgrep.yaml","semgrep.yml","semgrep.yaml"],Pt=null;function Iu(){if(Pt&&q(Pt))return Pt;try{let r=C(Ar(),"zibby-code-scan");Tr(r,{recursive:!0});let e=C(r,"semgrep.curated.rules.json");return Rr(e,JSON.stringify(Ss),"utf-8"),Pt=e,e}catch{return null}}function Nu(r){return vu.map(t=>C(r,t)).find(t=>q(t))||Iu()}function Ou(r){let e=[];for(let t of Array.isArray(r)?r:[]){if(typeof t!="string"||!t)continue;let i=ws[Ut(t).toLowerCase()];if(!i)continue;let n=t.replace(/\\/g,"/");e.push(["CodeTarget",{path:{fpath:n,ppath:`/${n.replace(/^\/+/,"")}`},analyzer:i,products:["sast"]}])}return["Targets",e]}var Ru=0;function Tu(r){let e=Ou(r),t=e[1].length,i=C(Ar(),"zibby-code-scan");Tr(i,{recursive:!0});let n=C(i,`semgrep.targets.${process.pid}.${Ru++}.json`);return Rr(n,JSON.stringify(e),"utf-8"),{path:n,count:t}}function ys(r){let e=typeof r=="string"?r.toUpperCase():"";return e==="ERROR"?"error":e==="INFO"||e==="INVENTORY"||e==="EXPERIMENT"?"info":"warning"}var Au=Object.fromEntries(Ss.rules.map(r=>[r.id,r.severity]));function Eu(r,e){if(e)return ys(e);let t=Au[r];return t?ys(t):"warning"}function xu(r){let e=String(r||""),t=e.indexOf("{");if(t<0)return[];let i;try{i=JSON.parse(e.slice(t))}catch{return[]}return(i&&Array.isArray(i.results)?i.results:[]).map(s=>{if(!s||typeof s!="object")return null;let o=s.start&&typeof s.start=="object"?s.start:{},a=s.extra&&typeof s.extra=="object"?s.extra:{};return{file:s.path||"",line:Number.isFinite(o.line)?o.line:"",severity:Eu(s.check_id,a.severity),rule:s.check_id||"",message:(a.message||"").trim()}}).filter(s=>s&&(s.file||s.message))}function ju(r,e,t=4e3){let i=new Set(e.map(o=>o.toLowerCase())),n=[r],s=0;for(;n.length;){let o=n.pop(),a;try{a=_s(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(++s>t)return!1;if(c.isDirectory())!ks.has(c.name)&&!c.name.startsWith(".")&&n.push(C(o,c.name));else if(c.isFile()&&i.has(Ut(c.name).toLowerCase()))return!0}}return!1}function Lu(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(n=>{if(!n||typeof n!="object")return null;let s=Array.isArray(n.labels)&&n.labels.length?n.labels[0]:null,o=s&&s.span?s.span:null;return{file:n.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:n.severity||"warning",rule:n.code||"",message:n.message||""}}).filter(n=>n&&(n.file||n.message))}function $u(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?{file:i.filename||"",line:i.location&&Number.isFinite(i.location.row)?i.location.row:"",severity:"warning",rule:i.code||"",message:i.message||""}:null).filter(i=>i&&(i.file||i.message)):[]}function Pu(r){let e=String(r||"").trim();if(!e)return[];let t=[];for(let i of e.split(`
839
+ post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=ru();if(!t)return{command:null,args:[],env:{},description:this.description};let i={},n=r&&e?De(r,e):null;n&&(i.ZIBBY_NODE_SESSION_PATH=n),r&&(i.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!i[s]&&process.env[s]&&(i[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/socialCard.js","socialCardSkill"],env:i,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 i=as(e?.width,ms),n=as(e?.height,Vp),s=e?.theme==="light"?"light":"dark",o=ou(e?.accent,eu),a;try{a=cu({width:i,height:n,theme:s,accent:o,headline:t,eyebrow:e?.eyebrow,subhead:e?.subhead,stat:e?.stat,footer:e?.footer,diagram:e?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=lu(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=nu(),l=su(e?.filename)||`social-card-${Date.now()}`,p=De(d,`${l}.png`);os(p,c);let u=[{path:p,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=De(d,`${l}.svg`);os(m,a,"utf-8"),u.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:i,height:n,theme:s,files:u})}catch(t){return JSON.stringify({error:`social_card_render failed: ${t.message}`})}},tools:[{name:"social_card_render",description:'Render a BRANDED "concept card" PNG LOCALLY (no external service) from structured fields \u2014 the clean LinkedIn concept-card style: bold headline + small uppercase eyebrow + optional supporting subhead, stat, footer, and an A\u2014\u2713\u2014B diagram. Returns { ok:true, files:[{ path, format:"png", bytes }] }. Pass the returned `path` as `imagePath` to a LinkedIn post tool to attach it as the post image. Example: { "headline":"No more copy-paste between AI tools", "eyebrow":"MY WORKFLOW", "stat":"11.8k stars", "footer":"Apache 2.0", "diagram":["Claude Code","Codex"] }.',input_schema:{type:"object",properties:{headline:{type:"string",description:"REQUIRED. The big, bold line \u2014 the single key idea/takeaway. Word-wrapped + auto-sized."},eyebrow:{type:"string",description:'Small uppercase kicker above the headline (e.g. "MY WORKFLOW", "OPEN SOURCE"). Rendered uppercased in the accent color.'},subhead:{type:"string",description:"One supporting line under the headline (muted)."},stat:{type:"string",description:'Optional stat, shown bottom-right in the accent color (e.g. "11.8k stars", "3x faster").'},footer:{type:"string",description:'Optional footer, shown bottom-left (muted) (e.g. "Apache 2.0", a repo name).'},diagram:{type:"array",items:{type:"string"},description:'Optional 2-3 short labels rendered as a chain of pills joined by a checkmark (A \u2014\u2713\u2014 B), e.g. ["Claude Code","Codex"].'},theme:{type:"string",enum:["dark","light"],description:"Card theme (default 'dark' \u2014 near-black bg, off-white text)."},accent:{type:"string",description:'Accent hex color (e.g. "#f97316"). Defaults to a tasteful blue (#3b82f6).'},width:{type:"number",description:"Image width in px (default 1200 \u2014 LinkedIn 1.91:1 link image)."},height:{type:"number",description:"Image height in px (default 627)."},filename:{type:"string",description:"Optional file basename (no extension); defaults to social-card-<timestamp>."},output:{type:"string",enum:["png","both"],description:"Which file(s) to write (default 'png'; 'both' also writes the .svg)."}},required:["headline"]}}]};import{spawnSync as du}from"node:child_process";import{existsSync as q,readdirSync as _s,statSync as bs,writeFileSync as Or,mkdirSync as Rr}from"node:fs";import{dirname as Nr,extname as Ut,join as C,relative as pu,resolve as Ct}from"node:path";import{tmpdir as Tr}from"node:os";import{fileURLToPath as uu}from"node:url";import{SKILL_META as mu}from"@zibby/skill-ids";import{binPath as fu}from"@zibby/bin-oxlint";import{binPath as hu}from"@zibby/bin-semgrep";function gu(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=fu();if(r&&q(r))return r}catch{}return"oxlint"}function yu(){if(process.env.SEMGREP_CORE_BIN)return process.env.SEMGREP_CORE_BIN;try{let r=hu();if(r&&q(r))return r}catch{}return"semgrep-core"}function _u(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Nr(uu(import.meta.url)),e=Ct(r,"..","bin","mcp-skill.mjs");return q(e)?e:null}var ks=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),bu=400,ku={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"}},wu=[".oxlintrc.json",".oxlintrc","oxlint.json"],$t=null;function Su(){if($t&&q($t))return $t;try{let r=C(Tr(),"zibby-code-scan");Rr(r,{recursive:!0});let e=C(r,"oxlintrc.curated.json");return Or(e,JSON.stringify(ku),"utf-8"),$t=e,e}catch{return null}}var ws={".java":"java",".py":"python",".go":"go",".rb":"ruby",".php":"php"},gs=Object.keys(ws),Ss={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(...);"}]}]}]},vu=[".semgrep.yml",".semgrep.yaml","semgrep.yml","semgrep.yaml"],Pt=null;function Iu(){if(Pt&&q(Pt))return Pt;try{let r=C(Tr(),"zibby-code-scan");Rr(r,{recursive:!0});let e=C(r,"semgrep.curated.rules.json");return Or(e,JSON.stringify(Ss),"utf-8"),Pt=e,e}catch{return null}}function Nu(r){return vu.map(t=>C(r,t)).find(t=>q(t))||Iu()}function Ou(r){let e=[];for(let t of Array.isArray(r)?r:[]){if(typeof t!="string"||!t)continue;let i=ws[Ut(t).toLowerCase()];if(!i)continue;let n=t.replace(/\\/g,"/");e.push(["CodeTarget",{path:{fpath:n,ppath:`/${n.replace(/^\/+/,"")}`},analyzer:i,products:["sast"]}])}return["Targets",e]}var Ru=0;function Tu(r){let e=Ou(r),t=e[1].length,i=C(Tr(),"zibby-code-scan");Rr(i,{recursive:!0});let n=C(i,`semgrep.targets.${process.pid}.${Ru++}.json`);return Or(n,JSON.stringify(e),"utf-8"),{path:n,count:t}}function ys(r){let e=typeof r=="string"?r.toUpperCase():"";return e==="ERROR"?"error":e==="INFO"||e==="INVENTORY"||e==="EXPERIMENT"?"info":"warning"}var Au=Object.fromEntries(Ss.rules.map(r=>[r.id,r.severity]));function Eu(r,e){if(e)return ys(e);let t=Au[r];return t?ys(t):"warning"}function xu(r){let e=String(r||""),t=e.indexOf("{");if(t<0)return[];let i;try{i=JSON.parse(e.slice(t))}catch{return[]}return(i&&Array.isArray(i.results)?i.results:[]).map(s=>{if(!s||typeof s!="object")return null;let o=s.start&&typeof s.start=="object"?s.start:{},a=s.extra&&typeof s.extra=="object"?s.extra:{};return{file:s.path||"",line:Number.isFinite(o.line)?o.line:"",severity:Eu(s.check_id,a.severity),rule:s.check_id||"",message:(a.message||"").trim()}}).filter(s=>s&&(s.file||s.message))}function ju(r,e,t=4e3){let i=new Set(e.map(o=>o.toLowerCase())),n=[r],s=0;for(;n.length;){let o=n.pop(),a;try{a=_s(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(++s>t)return!1;if(c.isDirectory())!ks.has(c.name)&&!c.name.startsWith(".")&&n.push(C(o,c.name));else if(c.isFile()&&i.has(Ut(c.name).toLowerCase()))return!0}}return!1}function Lu(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(n=>{if(!n||typeof n!="object")return null;let s=Array.isArray(n.labels)&&n.labels.length?n.labels[0]:null,o=s&&s.span?s.span:null;return{file:n.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:n.severity||"warning",rule:n.code||"",message:n.message||""}}).filter(n=>n&&(n.file||n.message))}function $u(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?{file:i.filename||"",line:i.location&&Number.isFinite(i.location.row)?i.location.row:"",severity:"warning",rule:i.code||"",message:i.message||""}:null).filter(i=>i&&(i.file||i.message)):[]}function Pu(r){let e=String(r||"").trim();if(!e)return[];let t=[];for(let i of e.split(`
840
840
  `)){let n=i.trim();if(!n)continue;let s;try{s=JSON.parse(n)}catch{continue}if(!s||typeof s!="object")continue;let o=s.location||{};t.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""})}return t.filter(i=>i.file||i.message)}var Cu=[{id:"oxlint",detect:r=>q(C(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>gu(),args:(r,e={})=>{let t=e.baseDir||".",n=wu.some(o=>q(C(t,o)))?null:Su();return["--format","json",...n?["--config",n]:[],...r]},parse:Lu},{id:"semgrep",detect:r=>ju(r,gs),langs:gs,bin:()=>yu(),args:(r,e={})=>{let t=e.baseDir||".",i=Nu(t),{path:n}=Tu(r);return[...i?["-rules",i]:[],"-targets",n,"-json"]},parse:xu},{id:"ruff",detect:r=>q(C(r,"pyproject.toml"))||q(C(r,"requirements.txt"))||q(C(r,"setup.py")),langs:[".py"],bin:()=>process.env.RUFF_BIN||"ruff",args:r=>["check","--output-format","json",...r],parse:$u},{id:"staticcheck",detect:r=>q(C(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:Pu}];function Uu(r,e,t){let i=[],n=new Set(e.map(o=>o.toLowerCase())),s=[r];for(;s.length&&i.length<t;){let o=s.pop(),a;try{a=_s(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(i.length>=t)break;c.isDirectory()?!ks.has(c.name)&&!c.name.startsWith(".")&&s.push(C(o,c.name)):c.isFile()&&n.has(Ut(c.name).toLowerCase())&&i.push(C(o,c.name))}}return i}function Ju(r,e,t){let i=t.map(a=>pu(e,a)).filter(Boolean);if(!i.length)return{scanner:r.id,skipped:"no matching files"};let n=r.bin(),s=du(n,r.args(i,{baseDir:e}),{cwd:e,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(s.error){let a=s.error.code==="ENOENT"?`binary not installed (${n})`:String(s.error.message||s.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(s.stdout,s.stderr,s.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:i.length,findings:o}}var vs={id:"code-scan",serverName:"code_scan",meta:mu["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)
841
841
  After you've cloned the repo, call \`scan_code\` to get DETERMINISTIC linter
842
842
  findings for WHATEVER stack this repo is \u2014 it auto-detects (JS/TS\u2192oxlint;
@@ -844,7 +844,7 @@ Java/Python/Go/Ruby/PHP\u2192semgrep) and runs the matching tool. Pass \`files\`
844
844
  a review) or \`dir\` (a directory to scan). Findings are GROUND-TRUTH CANDIDATES:
845
845
  triage them for THIS change, verify each in context (false positives exist \u2014
846
846
  trace before asserting), fold noise, and turn the real ones into inline
847
- suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=_u();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,i;if(e?.dir&&typeof e.dir=="string"?i=Ct(e.dir):t&&t.length?i=qu(t.map(a=>Ct(a))):i=process.cwd(),!q(i)||!bs(i).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${i}`});let n=t?t.map(a=>Ct(i,a)):null,s=[],o=0;for(let a of Cu){let c=!1;try{c=!!a.detect(i)}catch{c=!1}if(!c)continue;let d=new Set(a.langs.map(u=>u.toLowerCase())),l=n?n.filter(u=>d.has(Ut(u).toLowerCase())):Uu(i,a.langs,bu),p=Ju(a,i,l);Array.isArray(p.findings)&&(o+=p.findings.length),s.push(p)}return s.length?JSON.stringify({ok:!0,baseDir:i,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:i,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 qu(r){if(!r.length)return process.cwd();if(r.length===1)return Or(r[0]);let e=r.map(s=>s.split("/")),t=e[0],i=[];for(let s=0;s<t.length;s++){let o=t[s];if(e.every(a=>a[s]===o))i.push(o);else break}let n=i.join("/");return n&&q(n)&&bs(n).isDirectory()?n:Or(r[0])}import{dirname as Du,resolve as Bu}from"path";import{fileURLToPath as Mu}from"url";import{existsSync as Fu}from"fs";function Ku(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Du(Mu(import.meta.url)),e=Bu(r,"..","bin","mcp-skill.mjs");return Fu(e)?e:null}function Gu(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function Hu(){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 zu={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:[]}},Is={id:"trigger-agent",serverName:"trigger",allowedTools:["mcp__trigger__*"],envKeys:[],description:"Trigger another Zibby workflow/agent run in this project (agent-driven, fire-and-forget; cloud + self-hosted).",promptFragment:"## Trigger another agent (agent-driven)\nYou can start another Zibby agent run yourself with the `trigger_agent`\ntool \u2014 and YOU decide when and how many times to call it. Each call starts ONE\nindependent run (fire-and-forget) and returns its executionId; it does NOT wait for\nthat run to finish.\n- To re-run THIS same agent (self-dispatch) \u2014 e.g. to hand an item to another of\n this agent's scenarios \u2014 OMIT `workflowType` and pass the `input` for that run.\n- To trigger a DIFFERENT agent in the project, pass its `workflowType` + `input`.\nCall it once per run you want to start (loop over your items and call it for each).\nIt never throws \u2014 a failure comes back as { ok:false, error }; log it and move on.",resolve(){let r=Ku();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,i=Gu(),n=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(!i)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!n)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let s=`${Hu()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(n)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(s,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({input:e.input&&typeof e.input=="object"?e.input:{}}),signal:o.signal})}finally{clearTimeout(a)}let d=await c.text().catch(()=>""),l;try{l=d?JSON.parse(d):{}}catch{l={raw:d}}if(!c.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${c.status})`,detail:l&&(l.error||l.message)||d.slice(0,300)});let p=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:n,executionId:p,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[zu]};import{spawnSync as Yu}from"node:child_process";import{existsSync as Jt,mkdirSync as Ns,readdirSync as Wu,writeFileSync as Zu}from"node:fs";import{createHash as Vu}from"node:crypto";import{join as qt}from"node:path";import{SKILL_META as Qu}from"@zibby/skill-ids";function Os(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function Rs(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?qt(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function Xu(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=qt(r,".zibby","repos");try{if(Jt(e)){let t=Wu(e,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>qt(e,i.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return Jt(r)?r:null}function em(r){return Vu("sha256").update(r).digest("hex").slice(0,16)}var Ts={id:"codebase-memory",serverName:"codebase_memory",meta:Qu["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)
847
+ suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=_u();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,i;if(e?.dir&&typeof e.dir=="string"?i=Ct(e.dir):t&&t.length?i=qu(t.map(a=>Ct(a))):i=process.cwd(),!q(i)||!bs(i).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${i}`});let n=t?t.map(a=>Ct(i,a)):null,s=[],o=0;for(let a of Cu){let c=!1;try{c=!!a.detect(i)}catch{c=!1}if(!c)continue;let d=new Set(a.langs.map(u=>u.toLowerCase())),l=n?n.filter(u=>d.has(Ut(u).toLowerCase())):Uu(i,a.langs,bu),p=Ju(a,i,l);Array.isArray(p.findings)&&(o+=p.findings.length),s.push(p)}return s.length?JSON.stringify({ok:!0,baseDir:i,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:i,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 qu(r){if(!r.length)return process.cwd();if(r.length===1)return Nr(r[0]);let e=r.map(s=>s.split("/")),t=e[0],i=[];for(let s=0;s<t.length;s++){let o=t[s];if(e.every(a=>a[s]===o))i.push(o);else break}let n=i.join("/");return n&&q(n)&&bs(n).isDirectory()?n:Nr(r[0])}import{dirname as Du,resolve as Bu}from"path";import{fileURLToPath as Mu}from"url";import{existsSync as Fu}from"fs";function Ku(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Du(Mu(import.meta.url)),e=Bu(r,"..","bin","mcp-skill.mjs");return Fu(e)?e:null}function Gu(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function Hu(){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 zu={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:[]}},Is={id:"trigger-agent",serverName:"trigger",allowedTools:["mcp__trigger__*"],envKeys:[],description:"Trigger another Zibby workflow/agent run in this project (agent-driven, fire-and-forget; cloud + self-hosted).",promptFragment:"## Trigger another agent (agent-driven)\nYou can start another Zibby agent run yourself with the `trigger_agent`\ntool \u2014 and YOU decide when and how many times to call it. Each call starts ONE\nindependent run (fire-and-forget) and returns its executionId; it does NOT wait for\nthat run to finish.\n- To re-run THIS same agent (self-dispatch) \u2014 e.g. to hand an item to another of\n this agent's scenarios \u2014 OMIT `workflowType` and pass the `input` for that run.\n- To trigger a DIFFERENT agent in the project, pass its `workflowType` + `input`.\nCall it once per run you want to start (loop over your items and call it for each).\nIt never throws \u2014 a failure comes back as { ok:false, error }; log it and move on.",resolve(){let r=Ku();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,i=Gu(),n=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(!i)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!n)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let s=`${Hu()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(n)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(s,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({input:e.input&&typeof e.input=="object"?e.input:{}}),signal:o.signal})}finally{clearTimeout(a)}let d=await c.text().catch(()=>""),l;try{l=d?JSON.parse(d):{}}catch{l={raw:d}}if(!c.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${c.status})`,detail:l&&(l.error||l.message)||d.slice(0,300)});let p=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:n,executionId:p,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[zu]};import{spawnSync as Yu}from"node:child_process";import{existsSync as Ar,mkdirSync as Ns,readdirSync as Wu,writeFileSync as Zu}from"node:fs";import{createHash as Vu}from"node:crypto";import{join as Jt}from"node:path";import{SKILL_META as Qu}from"@zibby/skill-ids";function Os(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function Rs(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?Jt(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function Xu(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=Jt(r,".zibby","repos");try{if(Ar(e)){let t=Wu(e,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>Jt(e,i.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return null}function em(r){return Vu("sha256").update(r).digest("hex").slice(0,16)}var Ts={id:"codebase-memory",serverName:"codebase_memory",meta:Qu["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)
848
848
  The checked-out repository is indexed into a queryable code graph + semantic
849
849
  index. Reach for these instead of blindly grepping when you need structure,
850
850
  relationships, or "where does X live / what depends on Y":
@@ -856,7 +856,7 @@ relationships, or "where does X live / what depends on Y":
856
856
  - get_code_snippet / search_code: pull the exact code for a node / text match.
857
857
  - index_status / list_projects: confirm the index is present before querying.
858
858
  The repo is indexed for you at the start of the run; if a query comes back
859
- empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=Rs();try{Ns(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:Os(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=Xu();if(!r)return{};let e=Rs();try{Ns(e,{recursive:!0})}catch{}let t=qt(e,`.cbm-indexed-${em(r)}`);if(Jt(t))return{};let i=Os();if(!Jt(i)&&!process.env.CBM_BIN)return{};let n=Yu(i,["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{Zu(t,`${new Date().toISOString()} status=${n.status}
859
+ empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=Rs();try{Ns(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:Os(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=Xu();if(!r)return{};let e=Rs();try{Ns(e,{recursive:!0})}catch{}let t=Jt(e,`.cbm-indexed-${em(r)}`);if(Ar(t))return{};let i=Os();if(!Ar(i)&&!process.env.CBM_BIN)return{};let n=Yu(i,["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{Zu(t,`${new Date().toISOString()} status=${n.status}
860
860
  `)}catch{}}catch{}return{}}};import{existsSync as As,readFileSync as tm}from"node:fs";import{homedir as rm}from"node:os";import{join as im,dirname as nm,resolve as sm}from"node:path";import{fileURLToPath as om}from"node:url";import{SKILL_META as am}from"@zibby/skill-ids";var cm=3e4,Er=1;function lm(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=nm(om(import.meta.url)),e=sm(r,"..","bin","mcp-skill.mjs");return As(e)?e:null}function dm(){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=im(rm(),".zibby","config.json");return As(r)&&JSON.parse(tm(r,"utf-8")).sessionToken||null}catch{return null}}function pm(){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 um(){let r={};for(let[e,t]of Object.entries(process.env)){let i=/^ZIBBY_STORE__(.+)$/.exec(e);if(!i)continue;let n=typeof t=="string"?t.trim():"";n&&(r[i[1]]=n)}return r}function xr(r){let e=um(),t=Object.keys(e),i=typeof r=="string"?r.trim():"";return i?Object.prototype.hasOwnProperty.call(e,i)?{storeId:e[i],name:i}:{error:`unknown store '${i}'; 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 jr(r,e,t){let i=dm();if(!i)throw new Error("No backend credential (PROJECT_API_TOKEN). The knowledge base is only available inside a Zibby run.");let n=`${pm()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s={Authorization:`Bearer ${i}`,"Content-Type":"application/json"},o=JSON.stringify(t),a;for(let c=0;c<=Er;c++){let d=new AbortController,l=setTimeout(()=>d.abort(),cm);try{let p=await fetch(n,{method:"POST",headers:s,body:o,signal:d.signal}),u=await p.text().catch(()=>"");if(p.status>=500&&c<Er){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<Er))break}finally{clearTimeout(l)}}throw a||new Error(`gbrain ${e} request failed`)}var Es={id:"gbrain",serverName:"gbrain",allowedTools:["mcp__gbrain__*"],meta:am.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)
861
861
  You have a per-tenant KNOWLEDGE BASE (a Postgres + pgvector "brain"), bound as a
862
862
  \`postgres\`-type store in the "AVAILABLE STORES" block below. Ingested documents
@@ -1106,16 +1106,16 @@ ${m}
1106
1106
  }
1107
1107
  `;Be(E(o,"graph.mjs"),f,"utf-8");let h={name:n,description:t.description||`${s} workflow`,entryClass:s,triggers:{api:!0}};Be(E(o,"workflow.json"),`${JSON.stringify(h,null,2)}
1108
1108
  `,"utf-8");let b=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(y=>`nodes/${y.replace(/_/g,"-")}.mjs`)];return{workflowDir:$s(r,o),files:b,className:s,slug:n}}async function Im(r){let{name:e,description:t,nodes:i,edges:n}=r;if(!e||!Cs.test(e.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${e}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!i||i.length===0)return JSON.stringify({error:"At least one node is required."});let s={name:e.toLowerCase(),description:t||`${Us(e.toLowerCase())} workflow`,nodes:i.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:n||[]};if(s.edges.length===0&&s.nodes.length>0){for(let o=0;o<s.nodes.length-1;o++)s.edges.push({from:s.nodes[o].name,to:s.nodes[o+1].name});s.edges.push({from:s.nodes[s.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:s,message:`Workflow "${s.name}" designed with ${s.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:s.nodes.map(o=>o.name),flow:s.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function Nm(r,e){let{name:t,spec:i}=r,n=(t||i?.name||"").toLowerCase();if(!n||!Cs.test(n))return JSON.stringify({error:`Invalid workflow name "${n}".`});if(!i||!i.nodes||i.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let s=E(e,".zibby","workflows",n);if(le(s))return JSON.stringify({error:`Workflow "${n}" already exists at .zibby/workflows/${n}/. Delete it first or choose a different name.`});let o=await Ds(i,e),a=vm(e,n,i,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${n}" created at ${a.workflowDir}/`,nextSteps:[`Test locally: zibby start ${n}`,`Deploy to cloud: zibby deploy ${n} --project <project-id>`,`Tail logs: zibby logs --workflow ${n} --project <project-id>`]})}async function Om(r,e){let{workflowName:t,nodeName:i,description:n,inputFields:s,outputFields:o}=r,a=(t||"").toLowerCase(),c=(i||"").replace(/-/g,"_"),d=E(e,".zibby","workflows",a);if(!le(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:n||`Process ${c}`,inputFields:s||[],outputFields:o||[]}],edges:[]},u=(await Ds(l,e)).nodes?.[c]?.code;if(!u)return JSON.stringify({error:"Failed to generate node code."});let m=E(d,"nodes"),f=`${c.replace(/_/g,"-")}.mjs`;Be(E(m,f),u,"utf-8");let h=E(m,"index.mjs"),b=et(c),y=`export { ${b} } from './${c.replace(/_/g,"-")}.mjs';
1109
- `,_=le(h)?tt(h,"utf-8"):"";return _.includes(b)||Be(h,_+y,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:b,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Rm(r,e){let{name:t,projectId:i}=r,n=(t||"").toLowerCase();if(!n)return JSON.stringify({error:"Workflow name is required."});if(!i)return JSON.stringify({error:"projectId is required."});let s=E(e,".zibby","workflows",n);if(!le(s))return JSON.stringify({error:`Workflow "${n}" not found at .zibby/workflows/${n}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${E(e,"packages/cli/bin/zibby.js")}" deploy ${n} --project ${i}`,{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 ${n} --project ${i}`,{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 Tm(r){let e=E(r,".zibby","workflows");if(!le(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let i=Lr(e).filter(n=>{try{return Ls(E(e,n)).isDirectory()}catch{return!1}}).map(n=>{let s=E(e,n,"workflow.json"),o={};try{o=JSON.parse(tt(s,"utf-8"))}catch{}let a=E(e,n,"nodes"),c=0;try{c=Lr(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:n,description:o.description||"",nodeCount:c,path:$s(r,E(e,n))}});return JSON.stringify({workflows:i})}var Bs={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:ym,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 i=t?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Im(e);case"build_workflow":return await Nm(e,i);case"add_node":return await Om(e,i);case"deploy_workflow":return await Rm(e,i);case"list_workflows":return Tm(i);case"explore_framework_docs":{let n=(e.topic||"").trim();if(!n){let o=js();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=qs(n);if(!s){let o=js();return JSON.stringify({error:`Doc "${n}" not found.`,available:o})}return JSON.stringify({topic:n,content:s})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(n){return JSON.stringify({error:n.message})}},resolve(){return null}};import{resolveIntegrationToken as Am}from"@zibby/core/backend-client.js";var Cr=Object.freeze({id:"openai_billing",requiresIntegration:N.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),Ur=Object.freeze({id:"anthropic_billing",requiresIntegration:N.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),Jr=Object.freeze({id:"cursor_admin",requiresIntegration:N.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Ms(r){return Math.floor(r/1e3)}function Pr(r){return new Date(r).toISOString().slice(0,10)}function Fs(r){return new Date(r).toISOString()}async function rt(r){let e=await Am(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function Ks({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let i=await rt("openai_billing"),n=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.openai.com/v1/organization/costs?${[`start_time=${Ms(r)}`,`end_time=${Ms(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{Authorization:`Bearer ${i}`}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=Pr((m.start_time||0)*1e3);for(let h of m.results||[])n.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:n,rawBuckets:s}}async function Em(){let r=await rt("openai_billing"),t=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${s.slice(0,200)}`)}let i=await t.json(),n=new Map;for(let s of i.data||[])n.set(s.id,s.name);return n}async function Gs({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let i=await rt("anthropic_billing"),n=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(Fs(r))}`,`ending_at=${encodeURIComponent(Fs(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{"x-api-key":i,"anthropic-version":"2023-06-01"}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])n.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:n,rawBuckets:s}}async function xm(){let r=await rt("anthropic_billing"),t=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${s.slice(0,200)}`)}let i=await t.json(),n=new Map;for(let s of i.data||[])n.set(s.id,s.name);return n}async function Hs({startMs:r,endMs:e}){let t=await rt("cursor_admin"),i=Pr(r),n=Pr(e),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${i}&endDate=${n}`,o=await fetch(s,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${l.slice(0,200)}`)}let a=await o.json(),c=[],d=0;for(let l of a.data||[]){d+=1;let p=l.date;for(let u of l.userMetrics||[]){for(let m of u.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:p,costUsd:Number(m.totalCents??0)/100,userEmail:u.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!u.modelUsage||u.modelUsage.length===0)&&c.push({provider:"cursor",day:p,costUsd:Number(u.totalCents??0)/100,userEmail:u.email})}}return{ok:!0,items:c,rawBuckets:d}}async function jm({startMs:r,endMs:e}){let[t,i,n]=await Promise.allSettled([Ks({startMs:r,endMs:e}),Gs({startMs:r,endMs:e}),Hs({startMs:r,endMs:e})]),s=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=s(t),a=s(i),c=s(n),d=[{provider:"openai",totalUsd:o.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,p)=>l+(p.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function Lm(r,e){let t=new Map;for(let i of r){let n=e(i);if(!n)continue;let s=t.get(n)||{key:n,totalUsd:0,count:0};s.totalUsd+=i.costUsd||0,s.count+=1,t.set(n,s)}return[...t.values()].sort((i,n)=>n.totalUsd-i.totalUsd)}function $m(r){if(!r.length)return{mean:0,stddev:0};let e=r.reduce((i,n)=>i+n,0)/r.length,t=r.reduce((i,n)=>i+(n-e)**2,0)/r.length;return{mean:e,stddev:Math.sqrt(t)}}import{SKILL_IDS as K_}from"@zibby/skill-ids";import{z as w}from"zod";var it=["ok","info","warn","critical"],Pm=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(it).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.')}),Cm=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(it).optional()}),Um=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.")}),Jm=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(it).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.")}),qm=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(it).optional()})).min(1).max(20)}),Dm=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),Bm=w.discriminatedUnion("kind",[Cm,Um,Jm,qm,Dm]),nt=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:Pm,sections:w.array(Bm).max(20).default([]).superRefine((r,e)=>{r.forEach((t,i)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:w.ZodIssueCode.custom,path:[i,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(n=>n.length===t.headers.length)&&e.addIssue({code:w.ZodIssueCode.custom,path:[i,"rows"],message:"every row must have headers.length entries"})})}),footer:w.object({viewUrl:w.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:w.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),U=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),Dt=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),Mm=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Bt(r,e,t=12){if(!Number.isFinite(r)||!Number.isFinite(e)||e<=0)return"";let i=Math.max(0,Math.min(1,r/e)),n=Math.round(i*t);return"\u2593".repeat(n)+"\u2591".repeat(t-n)}function st(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function Mt(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function Ws({headers:r,rows:e}){let t=r.map((o,a)=>{let c=Math.max(String(o).length,...e.map(d=>String(d[a]??"").length));return Math.min(c,32)}),i=o=>o.map((a,c)=>st(a,t[c])).join(" "),n=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[i(r),n,...e.map(o=>i(o))].join(`
1110
- `)+"\n```"}function Fm(r){let e=nt.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 i=[`*${e.headline.primary}*`];if(e.headline.delta){let s=Dt[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"";i.push(`${s} ${e.headline.delta.value} ${o}`.trim())}let n=i.join(" ");e.headline.summary&&(n+=`
1111
- `+e.headline.summary),t.push({type:"section",text:{type:"mrkdwn",text:n}});for(let s of e.sections)switch(t.push({type:"divider"}),s.title&&t.push({type:"section",text:{type:"mrkdwn",text:`*${s.title}*`}}),s.kind){case"trend":{let o=Math.max(...s.values),a=s.labels.map((c,d)=>{let l=s.values[d],p=Bt(l,o),m=(s.highlight==="last"&&d===s.labels.length-1||s.highlight==="max"&&l===o||s.highlight==="min"&&l===Math.min(...s.values))&&s.severity?` ${U[s.severity]}`:"";return`${st(c,10)} ${Mt(l.toLocaleString(),8)} ${p}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1109
+ `,_=le(h)?tt(h,"utf-8"):"";return _.includes(b)||Be(h,_+y,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:b,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Rm(r,e){let{name:t,projectId:i}=r,n=(t||"").toLowerCase();if(!n)return JSON.stringify({error:"Workflow name is required."});if(!i)return JSON.stringify({error:"projectId is required."});let s=E(e,".zibby","workflows",n);if(!le(s))return JSON.stringify({error:`Workflow "${n}" not found at .zibby/workflows/${n}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${E(e,"packages/cli/bin/zibby.js")}" deploy ${n} --project ${i}`,{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 ${n} --project ${i}`,{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 Tm(r){let e=E(r,".zibby","workflows");if(!le(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let i=Lr(e).filter(n=>{try{return Ls(E(e,n)).isDirectory()}catch{return!1}}).map(n=>{let s=E(e,n,"workflow.json"),o={};try{o=JSON.parse(tt(s,"utf-8"))}catch{}let a=E(e,n,"nodes"),c=0;try{c=Lr(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:n,description:o.description||"",nodeCount:c,path:$s(r,E(e,n))}});return JSON.stringify({workflows:i})}var Bs={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:ym,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 i=t?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Im(e);case"build_workflow":return await Nm(e,i);case"add_node":return await Om(e,i);case"deploy_workflow":return await Rm(e,i);case"list_workflows":return Tm(i);case"explore_framework_docs":{let n=(e.topic||"").trim();if(!n){let o=js();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=qs(n);if(!s){let o=js();return JSON.stringify({error:`Doc "${n}" not found.`,available:o})}return JSON.stringify({topic:n,content:s})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(n){return JSON.stringify({error:n.message})}},resolve(){return null}};import{resolveIntegrationToken as Am}from"@zibby/core/backend-client.js";var Cr=Object.freeze({id:"openai_billing",requiresIntegration:N.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),Ur=Object.freeze({id:"anthropic_billing",requiresIntegration:N.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),Jr=Object.freeze({id:"cursor_admin",requiresIntegration:N.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Ms(r){return Math.floor(r/1e3)}function Pr(r){return new Date(r).toISOString().slice(0,10)}function Fs(r){return new Date(r).toISOString()}async function rt(r){let e=await Am(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function Ks({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let i=await rt("openai_billing"),n=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.openai.com/v1/organization/costs?${[`start_time=${Ms(r)}`,`end_time=${Ms(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{Authorization:`Bearer ${i}`}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=Pr((m.start_time||0)*1e3);for(let h of m.results||[])n.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:n,rawBuckets:s}}async function Em(){let r=await rt("openai_billing"),t=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${s.slice(0,200)}`)}let i=await t.json(),n=new Map;for(let s of i.data||[])n.set(s.id,s.name);return n}async function Gs({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let i=await rt("anthropic_billing"),n=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(Fs(r))}`,`ending_at=${encodeURIComponent(Fs(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{"x-api-key":i,"anthropic-version":"2023-06-01"}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])n.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:n,rawBuckets:s}}async function xm(){let r=await rt("anthropic_billing"),t=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${s.slice(0,200)}`)}let i=await t.json(),n=new Map;for(let s of i.data||[])n.set(s.id,s.name);return n}async function Hs({startMs:r,endMs:e}){let t=await rt("cursor_admin"),i=Pr(r),n=Pr(e),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${i}&endDate=${n}`,o=await fetch(s,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${l.slice(0,200)}`)}let a=await o.json(),c=[],d=0;for(let l of a.data||[]){d+=1;let p=l.date;for(let u of l.userMetrics||[]){for(let m of u.modelUsage||[]){let f=Number(m.acceptedLines??0),h=Number(m.suggestedLines??0);c.push({provider:"cursor",day:p,costUsd:Number(m.totalCents??0)/100,userEmail:u.email,model:m.model,requestCount:Number(m.requestCount??0),acceptanceRate:h>0?f/h:void 0})}(!u.modelUsage||u.modelUsage.length===0)&&c.push({provider:"cursor",day:p,costUsd:Number(u.totalCents??0)/100,userEmail:u.email})}}return{ok:!0,items:c,rawBuckets:d}}async function jm({startMs:r,endMs:e}){let[t,i,n]=await Promise.allSettled([Ks({startMs:r,endMs:e}),Gs({startMs:r,endMs:e}),Hs({startMs:r,endMs:e})]),s=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=s(t),a=s(i),c=s(n),d=[{provider:"openai",totalUsd:o.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"anthropic",totalUsd:a.items.reduce((l,p)=>l+(p.costUsd||0),0)},{provider:"cursor",totalUsd:c.items.reduce((l,p)=>l+(p.costUsd||0),0)}];return{openai:o,anthropic:a,cursor:c,totals:d}}function Lm(r,e){let t=new Map;for(let i of r){let n=e(i);if(!n)continue;let s=t.get(n)||{key:n,totalUsd:0,count:0};s.totalUsd+=i.costUsd||0,s.count+=1,t.set(n,s)}return[...t.values()].sort((i,n)=>n.totalUsd-i.totalUsd)}function $m(r){if(!r.length)return{mean:0,stddev:0};let e=r.reduce((i,n)=>i+n,0)/r.length,t=r.reduce((i,n)=>i+(n-e)**2,0)/r.length;return{mean:e,stddev:Math.sqrt(t)}}import{SKILL_IDS as K_}from"@zibby/skill-ids";import{z as w}from"zod";var it=["ok","info","warn","critical"],Pm=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(it).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.')}),Cm=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(it).optional()}),Um=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.")}),Jm=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(it).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.")}),qm=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(it).optional()})).min(1).max(20)}),Dm=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),Bm=w.discriminatedUnion("kind",[Cm,Um,Jm,qm,Dm]),nt=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:Pm,sections:w.array(Bm).max(20).default([]).superRefine((r,e)=>{r.forEach((t,i)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:w.ZodIssueCode.custom,path:[i,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(n=>n.length===t.headers.length)&&e.addIssue({code:w.ZodIssueCode.custom,path:[i,"rows"],message:"every row must have headers.length entries"})})}),footer:w.object({viewUrl:w.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:w.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),U=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),qt=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),Mm=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Dt(r,e,t=12){if(!Number.isFinite(r)||!Number.isFinite(e)||e<=0)return"";let i=Math.max(0,Math.min(1,r/e)),n=Math.round(i*t);return"\u2593".repeat(n)+"\u2591".repeat(t-n)}function st(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function Bt(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function Ws({headers:r,rows:e}){let t=r.map((o,a)=>{let c=Math.max(String(o).length,...e.map(d=>String(d[a]??"").length));return Math.min(c,32)}),i=o=>o.map((a,c)=>st(a,t[c])).join(" "),n=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[i(r),n,...e.map(o=>i(o))].join(`
1110
+ `)+"\n```"}function Fm(r){let e=nt.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 i=[`*${e.headline.primary}*`];if(e.headline.delta){let s=qt[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"";i.push(`${s} ${e.headline.delta.value} ${o}`.trim())}let n=i.join(" ");e.headline.summary&&(n+=`
1111
+ `+e.headline.summary),t.push({type:"section",text:{type:"mrkdwn",text:n}});for(let s of e.sections)switch(t.push({type:"divider"}),s.title&&t.push({type:"section",text:{type:"mrkdwn",text:`*${s.title}*`}}),s.kind){case"trend":{let o=Math.max(...s.values),a=s.labels.map((c,d)=>{let l=s.values[d],p=Dt(l,o),m=(s.highlight==="last"&&d===s.labels.length-1||s.highlight==="max"&&l===o||s.highlight==="min"&&l===Math.min(...s.values))&&s.severity?` ${U[s.severity]}`:"";return`${st(c,10)} ${Bt(l.toLocaleString(),8)} ${p}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1112
1112
  `)+"\n```"}});break}case"table":{t.push({type:"section",text:{type:"mrkdwn",text:Ws(s)}});break}case"callouts":{let o=U[s.tone||"info"];t.push({type:"section",text:{type:"mrkdwn",text:s.items.map(a=>`${o} ${a}`).join(`
1113
1113
  `)}});break}case"breakdown":{let o=s.rows.map(a=>({type:"mrkdwn",text:`*${a.label}*
1114
1114
  ${a.value}${a.sub?`
1115
- _${a.sub}_`:""}${a.severity?` ${U[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)t.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{t.push({type:"section",text:{type:"mrkdwn",text:s.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let s=[];e.footer.viewUrl&&s.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:e.footer.viewUrl,style:"primary"}),e.footer.rerunUrl&&s.push({type:"button",text:{type:"plain_text",text:"Run again"},url:e.footer.rerunUrl}),t.push({type:"divider"}),t.push({type:"actions",elements:s})}return t}function Km(r){let e=nt.parse(r),t=[],i=[`**${e.headline.primary}**`];if(e.headline.delta){let o=Dt[e.headline.delta.direction]||"",a=e.headline.delta.severity?U[e.headline.delta.severity]:"";i.push(`${o} ${e.headline.delta.value} ${a}`.trim())}let n=i.join(" ");e.headline.summary&&(n+=`
1116
- `+e.headline.summary),t.push({tag:"div",text:{tag:"lark_md",content:n}});for(let o of e.sections)switch(t.push({tag:"hr"}),o.title&&t.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let a=Math.max(...o.values),c=o.labels.map((d,l)=>{let p=o.values[l],u=Bt(p,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&p===a||o.highlight==="min"&&p===Math.min(...o.values))&&o.severity?` ${U[o.severity]}`:"";return`${st(d,10)} ${Mt(p.toLocaleString(),8)} ${u}${f}`});t.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1115
+ _${a.sub}_`:""}${a.severity?` ${U[a.severity]}`:""}`}));for(let a=0;a<o.length;a+=10)t.push({type:"section",fields:o.slice(a,a+10)});break}case"paragraph":{t.push({type:"section",text:{type:"mrkdwn",text:s.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let s=[];e.footer.viewUrl&&s.push({type:"button",text:{type:"plain_text",text:"View in Zibby"},url:e.footer.viewUrl,style:"primary"}),e.footer.rerunUrl&&s.push({type:"button",text:{type:"plain_text",text:"Run again"},url:e.footer.rerunUrl}),t.push({type:"divider"}),t.push({type:"actions",elements:s})}return t}function Km(r){let e=nt.parse(r),t=[],i=[`**${e.headline.primary}**`];if(e.headline.delta){let o=qt[e.headline.delta.direction]||"",a=e.headline.delta.severity?U[e.headline.delta.severity]:"";i.push(`${o} ${e.headline.delta.value} ${a}`.trim())}let n=i.join(" ");e.headline.summary&&(n+=`
1116
+ `+e.headline.summary),t.push({tag:"div",text:{tag:"lark_md",content:n}});for(let o of e.sections)switch(t.push({tag:"hr"}),o.title&&t.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let a=Math.max(...o.values),c=o.labels.map((d,l)=>{let p=o.values[l],u=Dt(p,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&p===a||o.highlight==="min"&&p===Math.min(...o.values))&&o.severity?` ${U[o.severity]}`:"";return`${st(d,10)} ${Bt(p.toLocaleString(),8)} ${u}${f}`});t.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
1117
1117
  `)+"\n```"}});break}case"table":{t.push({tag:"div",text:{tag:"lark_md",content:Ws(o)}});break}case"callouts":{let a=U[o.tone||"info"];t.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
1118
1118
  `)}});break}case"breakdown":{let a=o.rows.map(c=>{let d=c.severity?` ${U[c.severity]}`:"",l=c.sub?` *${c.sub}*`:"";return`**${c.label}** ${c.value}${l}${d}`});t.push({tag:"div",text:{tag:"lark_md",content:a.join(`
1119
- `)}});break}case"paragraph":{t.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let o=[];e.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:e.footer.viewUrl,type:"primary"}),e.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:e.footer.rerunUrl,type:"default"}),t.push({tag:"hr"}),t.push({tag:"action",actions:o})}let s="blue";return e.headline.delta?.severity&&(s=Mm[e.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:e.title.slice(0,200)},subtitle:e.subtitle?{tag:"plain_text",content:e.subtitle.slice(0,200)}:void 0,template:s},elements:t}}var Gm=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),zs=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function Re(r,e={}){let t={type:"text",text:{content:String(r).slice(0,2e3)}};return e.annotations&&(t.annotations=e.annotations),[t]}function qr(r,e){let t={object:"block",type:"paragraph",paragraph:{rich_text:Re(r)}};return e&&(t.paragraph.color=e),t}function Hm(r){return{object:"block",type:"code",code:{rich_text:Re(r),language:"plain text"}}}function zm(r){let e=nt.parse(r),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:Re(e.title.slice(0,200))}}),e.subtitle&&t.push(qr(e.subtitle,"gray_background"));let i=[{type:"text",text:{content:e.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(e.headline.delta){let s=Dt[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"",a=` ${s} ${e.headline.delta.value} ${o}`.trimEnd();i.push({type:"text",text:{content:a}})}t.push({object:"block",type:"paragraph",paragraph:{rich_text:i}}),e.headline.summary&&t.push(qr(e.headline.summary));for(let s of e.sections)switch(t.push({object:"block",type:"divider",divider:{}}),s.title&&t.push({object:"block",type:"heading_2",heading_2:{rich_text:Re(s.title)}}),s.kind){case"trend":{let o=Math.max(...s.values),a=Math.min(...s.values),c=s.labels.map((d,l)=>{let p=s.values[l],u=Bt(p,o),f=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&p===o||s.highlight==="min"&&p===a)&&s.severity?` ${U[s.severity]}`:"";return`${st(d,10)} ${Mt(p.toLocaleString(),8)} ${u}${f}`});t.push(Hm(c.join(`
1120
- `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>Re(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>Re(String(d)))}}));t.push({object:"block",type:"table",table:{table_width:s.headers.length,has_column_header:!0,has_row_header:!1,children:[o,...a]}});break}case"callouts":{let o=s.tone||"info",a=zs[o],c=Gm[o];for(let d of s.items)t.push({object:"block",type:"callout",callout:{rich_text:Re(d),icon:{type:"emoji",emoji:a},color:c}});break}case"breakdown":{for(let o of s.rows){let a=[{type:"text",text:{content:`${o.label}: `},annotations:{bold:!0}},{type:"text",text:{content:String(o.value)}}];o.sub&&a.push({type:"text",text:{content:` (${o.sub})`},annotations:{italic:!0}}),o.severity&&a.push({type:"text",text:{content:` ${U[o.severity]}`}}),t.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{t.push(qr(s.text));break}}e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)&&(t.push({object:"block",type:"divider",divider:{}}),e.footer.viewUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.viewUrl}}),e.footer.rerunUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.rerunUrl}}));let n=e.headline.delta?.severity?zs[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:n}}function Ys(r){return String(r??"").replace(/\|/g,"\\|")}function Ym(r){let e=nt.parse(r),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let i=[`**${e.headline.primary}**`];if(e.headline.delta){let n=Dt[e.headline.delta.direction]||"",s=e.headline.delta.severity?U[e.headline.delta.severity]:"";i.push(`${n} ${e.headline.delta.value} ${s}`.trim())}t.push("",i.join(" ")),e.headline.summary&&t.push("",e.headline.summary);for(let n of e.sections)switch(t.push("","---",""),n.title&&t.push(`## ${n.title}`,""),n.kind){case"trend":{let s=Math.max(...n.values),o=Math.min(...n.values),a=n.labels.map((c,d)=>{let l=n.values[d],p=Bt(l,s),m=(n.highlight==="last"&&d===n.labels.length-1||n.highlight==="max"&&l===s||n.highlight==="min"&&l===o)&&n.severity?` ${U[n.severity]}`:"";return`${st(c,10)} ${Mt(l.toLocaleString(),8)} ${p}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${n.headers.map(Ys).join(" | ")} |`),t.push(`| ${n.headers.map(()=>"---").join(" | ")} |`);for(let s of n.rows)t.push(`| ${s.map(Ys).join(" | ")} |`);break}case"callouts":{let s=U[n.tone||"info"];for(let o of n.items)t.push(`- ${s} ${o}`);break}case"breakdown":{for(let s of n.rows){let o=s.sub?` _${s.sub}_`:"",a=s.severity?` ${U[s.severity]}`:"";t.push(`- **${s.label}**: ${s.value}${o}${a}`)}break}case"paragraph":{t.push(n.text);break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let n=[];e.footer.viewUrl&&n.push(`[View in Zibby](${e.footer.viewUrl})`),e.footer.rerunUrl&&n.push(`[Run again](${e.footer.rerunUrl})`),t.push("","---","",n.join(" \xB7 "))}return t.join(`
1119
+ `)}});break}case"paragraph":{t.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let o=[];e.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:e.footer.viewUrl,type:"primary"}),e.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:e.footer.rerunUrl,type:"default"}),t.push({tag:"hr"}),t.push({tag:"action",actions:o})}let s="blue";return e.headline.delta?.severity&&(s=Mm[e.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:e.title.slice(0,200)},subtitle:e.subtitle?{tag:"plain_text",content:e.subtitle.slice(0,200)}:void 0,template:s},elements:t}}var Gm=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),zs=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function Re(r,e={}){let t={type:"text",text:{content:String(r).slice(0,2e3)}};return e.annotations&&(t.annotations=e.annotations),[t]}function qr(r,e){let t={object:"block",type:"paragraph",paragraph:{rich_text:Re(r)}};return e&&(t.paragraph.color=e),t}function Hm(r){return{object:"block",type:"code",code:{rich_text:Re(r),language:"plain text"}}}function zm(r){let e=nt.parse(r),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:Re(e.title.slice(0,200))}}),e.subtitle&&t.push(qr(e.subtitle,"gray_background"));let i=[{type:"text",text:{content:e.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(e.headline.delta){let s=qt[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"",a=` ${s} ${e.headline.delta.value} ${o}`.trimEnd();i.push({type:"text",text:{content:a}})}t.push({object:"block",type:"paragraph",paragraph:{rich_text:i}}),e.headline.summary&&t.push(qr(e.headline.summary));for(let s of e.sections)switch(t.push({object:"block",type:"divider",divider:{}}),s.title&&t.push({object:"block",type:"heading_2",heading_2:{rich_text:Re(s.title)}}),s.kind){case"trend":{let o=Math.max(...s.values),a=Math.min(...s.values),c=s.labels.map((d,l)=>{let p=s.values[l],u=Dt(p,o),f=(s.highlight==="last"&&l===s.labels.length-1||s.highlight==="max"&&p===o||s.highlight==="min"&&p===a)&&s.severity?` ${U[s.severity]}`:"";return`${st(d,10)} ${Bt(p.toLocaleString(),8)} ${u}${f}`});t.push(Hm(c.join(`
1120
+ `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>Re(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>Re(String(d)))}}));t.push({object:"block",type:"table",table:{table_width:s.headers.length,has_column_header:!0,has_row_header:!1,children:[o,...a]}});break}case"callouts":{let o=s.tone||"info",a=zs[o],c=Gm[o];for(let d of s.items)t.push({object:"block",type:"callout",callout:{rich_text:Re(d),icon:{type:"emoji",emoji:a},color:c}});break}case"breakdown":{for(let o of s.rows){let a=[{type:"text",text:{content:`${o.label}: `},annotations:{bold:!0}},{type:"text",text:{content:String(o.value)}}];o.sub&&a.push({type:"text",text:{content:` (${o.sub})`},annotations:{italic:!0}}),o.severity&&a.push({type:"text",text:{content:` ${U[o.severity]}`}}),t.push({object:"block",type:"bulleted_list_item",bulleted_list_item:{rich_text:a}})}break}case"paragraph":{t.push(qr(s.text));break}}e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)&&(t.push({object:"block",type:"divider",divider:{}}),e.footer.viewUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.viewUrl}}),e.footer.rerunUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.rerunUrl}}));let n=e.headline.delta?.severity?zs[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:n}}function Ys(r){return String(r??"").replace(/\|/g,"\\|")}function Ym(r){let e=nt.parse(r),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let i=[`**${e.headline.primary}**`];if(e.headline.delta){let n=qt[e.headline.delta.direction]||"",s=e.headline.delta.severity?U[e.headline.delta.severity]:"";i.push(`${n} ${e.headline.delta.value} ${s}`.trim())}t.push("",i.join(" ")),e.headline.summary&&t.push("",e.headline.summary);for(let n of e.sections)switch(t.push("","---",""),n.title&&t.push(`## ${n.title}`,""),n.kind){case"trend":{let s=Math.max(...n.values),o=Math.min(...n.values),a=n.labels.map((c,d)=>{let l=n.values[d],p=Dt(l,s),m=(n.highlight==="last"&&d===n.labels.length-1||n.highlight==="max"&&l===s||n.highlight==="min"&&l===o)&&n.severity?` ${U[n.severity]}`:"";return`${st(c,10)} ${Bt(l.toLocaleString(),8)} ${p}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${n.headers.map(Ys).join(" | ")} |`),t.push(`| ${n.headers.map(()=>"---").join(" | ")} |`);for(let s of n.rows)t.push(`| ${s.map(Ys).join(" | ")} |`);break}case"callouts":{let s=U[n.tone||"info"];for(let o of n.items)t.push(`- ${s} ${o}`);break}case"breakdown":{for(let s of n.rows){let o=s.sub?` _${s.sub}_`:"",a=s.severity?` ${U[s.severity]}`:"";t.push(`- **${s.label}**: ${s.value}${o}${a}`)}break}case"paragraph":{t.push(n.text);break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let n=[];e.footer.viewUrl&&n.push(`[View in Zibby](${e.footer.viewUrl})`),e.footer.rerunUrl&&n.push(`[Run again](${e.footer.rerunUrl})`),t.push("","---","",n.join(" \xB7 "))}return t.join(`
1121
1121
  `)}import{createRequire as Wm}from"module";import{fileURLToPath as Zm}from"url";import{registerHandlers as Vm}from"@zibby/core/function-skill-registry.js";import{registerSkill as Qm}from"@zibby/agent-workflow";var Xm=Wm(import.meta.url);function ef(){try{return Xm.resolve("@zibby/core/function-bridge.js")}catch{return null}}var tf=import.meta.url;function rf(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(i,n)=>n;let t=new Error().stack;for(let i=2;i<t.length;i++){let n=t[i].getFileName();if(n&&n!==tf&&!n.startsWith("node:"))return n.startsWith("file://")?Zm(n):n}return null}finally{Error.prepareStackTrace=r}}function nf(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let e={},t=[];for(let[i,n]of Object.entries(r))if(typeof n=="string")e[i]={type:n},t.push(i);else{let{required:s,...o}=n;e[i]=o,s!==!1&&t.push(i)}return{type:"object",properties:e,required:t}}function sf(r,e,t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let i={[r]:t.handler},n=[{name:r,description:t.description||"",input_schema:nf(t.input)}];return Vm(r,i,n),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:t.description||`Function skill: ${r}`,envKeys:[],tools:n,resolve(){let s=ef();return s?{command:"node",args:[s,e,r]}:null}}}function of(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 Zs(r,e){let t;if("handler"in e){if(typeof e.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let i=rf();if(!i)throw new Error(`Could not resolve caller file for skill "${r}".`);t=sf(r,i,e)}else if(typeof e.resolve=="function")t=of(r,e);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return Qm(t),t}var af=Zs;import{registerSkill as W_,getSkill as Z_,hasSkill as V_,getAllSkills as Q_,listSkillIds as X_}from"@zibby/agent-workflow";v(Mr);v(Gr);v(xe);v(je);v(Xr);v(ti);v(ii);v(ni);v(ai);v($);v(B);v(di);v(_i);v(Si);v(Ri);v(Pi);v(Ci);v(kt);v(Ji);v(ln);v(ue);v(fn);v(Di);v(Gi);v(Tn);v(Pn);v(Bn);v(zn);v(is);v(ns);v(ss);v(hs);v(vs);v(Is);v(Ts);v(Es);v(Bs);v(Cr);v(Ur);v(Jr);v({...$,id:"slack_notify"});export{N as INTEGRATIONS,co as INTEGRATION_REGISTRY,it as REPORT_SEVERITIES,K_ as SKILLS,Ur as anthropicBillingSkill,zn as artifactSkill,Mr as browserSkill,is as chartRenderSkill,Tn as chatMemorySkill,Ci as chatNotifySkill,ss as chatProgressSkill,vs as codeScanSkill,ns as codeStatsSkill,Ts as codebaseMemorySkill,Gi as coreToolsSkill,Jr as cursorAdminSkill,Bn as datasetStoreSkill,di as discordSkill,jm as fetchAllProviders,Gs as fetchAnthropicCosts,xm as fetchAnthropicWorkspaces,Hs as fetchCursorSpend,Ks as fetchOpenAICosts,Em as fetchOpenAIProjects,Xr as figmaSkill,af as functionSkill,Es as gbrainSkill,Q_ as getAllSkills,Z_ as getSkill,ue as gitSkill,fn as gitWriteSkill,xe as githubSkill,je as gitlabSkill,Ri as googleDocsSkill,Lm as groupByKey,V_ as hasSkill,ti as hubspotSkill,Gr as jiraSkill,Pn as kvMemorySkill,Pi as larkDocsSkill,B as larkSkill,ii as linearSkill,Si as linkedinSkill,X_ as listSkillIds,$m as meanStddev,Ji as memorySkill,_i as notionSkill,Cr as openaiBillingSkill,ai as opendesignSkill,ni as planeSkill,W_ as registerSkill,nt as reportObjectSchema,Fm as reportToBlockKit,Km as reportToLarkCard,Ym as reportToMarkdown,zm as reportToNotionBlocks,ln as runnerSkill,kt as sentrySkill,Zs as skill,Di as skillInstallerSkill,$ as slackSkill,hs as socialCardSkill,ln as testRunnerSkill,Bs as workflowBuilderSkill};