@zibby/skills 0.2.6 → 0.2.7

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
@@ -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=yo();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 L("/rest/api/3/project"),n=(Array.isArray(t)?t:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await L(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let n=await L("/rest/api/3/status"),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let n=await Gr(t);return JSON.stringify({projectKey:t,count:n.length,issueTypes:n})}case"jira_search":{let t=e.jql||"",n=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await L(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let n=await L(`/rest/api/3/issue/${t}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name,labels:n.fields?.labels,created:n.fields?.created,updated:n.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=e;if(!t||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await Gr(t),f=bo(i,h)}catch{}let b={project:{key:t},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(b.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(b.priority={name:o}),a?.length&&(b.labels=a),c&&(b.assignee={id:c});let g=await L("/rest/api/3/issue",{method:"POST",body:{fields:b}}),_={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(_.issueType=f.resolved.name,_.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&ue(f.requested)!==ue(f.resolved.name)&&(_.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(_.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(_.sprintMove=await zt({issueKey:g.key,projectKey:t,sprintId:p,sprintName:u,target:m})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,i=await Hr(t,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await zt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await zt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:n,projectKey:i,status:s,maxResults:o}=e;if(!t&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${t}"`,d=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",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 L(`/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:n}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await L(`/rest/api/3/issue/${t}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=dt(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:n}=e;return!t||!n?JSON.stringify({error:"issueKey and body are required"}):(await L(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:n}=e;return!t||!n?JSON.stringify({error:"issueKey and fields are required"}):(await L(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:n,toStatus:i,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let p=((await L(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:p})}let c=n;if(!c){let p=(await L(`/rest/api/3/issue/${t}/transitions`)).transitions||[],u=Le(a),m=p.find(f=>Le(f?.name||"")===u||Le(f?.to?.name||"")===u);if(!m){let f=Ht(a);f.length>=2&&(m=p.find(h=>{let b=Ht(h?.name||""),g=Ht(h?.to?.name||""),_=b.length>=2&&(b.includes(f)||f.includes(b)),y=g.length>=2&&(g.includes(f)||f.includes(g));return _||y}))}if(!m){let f=p.map(_=>{let y=pt(a,_?.name||""),k=pt(a,_?.to?.name||"");return{t:_,score:Math.max(y,k)}}).sort((_,y)=>y.score-_.score),h=f[0],b=f[1];h&&h.score>=.45&&(!b||h.score-b.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await L(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await L(`/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 Uo}from"fs";import{fileURLToPath as Jo}from"url";import{dirname as qo,resolve as Bo}from"path";import{resolveIntegrationToken as Xr}from"@zibby/core/backend-client.js";import{spawn as Io,execSync as vo}from"child_process";import{existsSync as Q,mkdirSync as No,readdirSync as Zr,statSync as Oo,readFileSync as To}from"fs";import{resolve as Yt,join as X,basename as Ro}from"path";var Wt=".zibby/repos";function Yr(r,e){try{let t=new URL(r);return t.protocol==="https:"&&t.host.toLowerCase()===e.toLowerCase()}catch{return!1}}function Wr(r,e,t){let n=new URL(r);return n.username=encodeURIComponent(e),n.password=encodeURIComponent(t),n.toString()}function Ao(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 Ge(r,e,t,n,i="clone"){try{r(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);n&&(o=o.split(n).join("***")),console.error(`[${i}] WARNING: failed to strip token from .git/config: ${o}`)}}function ut(r,e,t={}){return new Promise((n,i)=>{let s=Io(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),s.on("error",c=>i(c))})}var me={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],inProcessOnly:!0,promptFragment:`## Git Repositories
74
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=yo();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 L("/rest/api/3/project"),n=(Array.isArray(t)?t:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await L(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let n=await L("/rest/api/3/status"),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let n=await Gr(t);return JSON.stringify({projectKey:t,count:n.length,issueTypes:n})}case"jira_search":{let t=e.jql||"",n=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await L(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let n=await L(`/rest/api/3/issue/${t}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name,labels:n.fields?.labels,created:n.fields?.created,updated:n.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=e;if(!t||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await Gr(t),f=bo(i,h)}catch{}let b={project:{key:t},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(b.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(b.priority={name:o}),a?.length&&(b.labels=a),c&&(b.assignee={id:c});let g=await L("/rest/api/3/issue",{method:"POST",body:{fields:b}}),_={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(_.issueType=f.resolved.name,_.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&ue(f.requested)!==ue(f.resolved.name)&&(_.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(_.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(_.sprintMove=await zt({issueKey:g.key,projectKey:t,sprintId:p,sprintName:u,target:m})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,i=await Hr(t,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await zt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await zt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:n,projectKey:i,status:s,maxResults:o}=e;if(!t&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${t}"`,d=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",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 L(`/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:n}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await L(`/rest/api/3/issue/${t}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=dt(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:n}=e;return!t||!n?JSON.stringify({error:"issueKey and body are required"}):(await L(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:n}=e;return!t||!n?JSON.stringify({error:"issueKey and fields are required"}):(await L(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:n,toStatus:i,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let p=((await L(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:p})}let c=n;if(!c){let p=(await L(`/rest/api/3/issue/${t}/transitions`)).transitions||[],u=Le(a),m=p.find(f=>Le(f?.name||"")===u||Le(f?.to?.name||"")===u);if(!m){let f=Ht(a);f.length>=2&&(m=p.find(h=>{let b=Ht(h?.name||""),g=Ht(h?.to?.name||""),_=b.length>=2&&(b.includes(f)||f.includes(b)),y=g.length>=2&&(g.includes(f)||f.includes(g));return _||y}))}if(!m){let f=p.map(_=>{let y=pt(a,_?.name||""),k=pt(a,_?.to?.name||"");return{t:_,score:Math.max(y,k)}}).sort((_,y)=>y.score-_.score),h=f[0],b=f[1];h&&h.score>=.45&&(!b||h.score-b.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await L(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await L(`/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 Uo}from"fs";import{fileURLToPath as Jo}from"url";import{dirname as Bo,resolve as qo}from"path";import{resolveIntegrationToken as Xr}from"@zibby/core/backend-client.js";import{spawn as Io,execSync as vo}from"child_process";import{existsSync as Q,mkdirSync as No,readdirSync as Zr,statSync as Oo,readFileSync as To}from"fs";import{resolve as Yt,join as X,basename as Ro}from"path";var Wt=".zibby/repos";function Yr(r,e){try{let t=new URL(r);return t.protocol==="https:"&&t.host.toLowerCase()===e.toLowerCase()}catch{return!1}}function Wr(r,e,t){let n=new URL(r);return n.username=encodeURIComponent(e),n.password=encodeURIComponent(t),n.toString()}function Ao(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 Ge(r,e,t,n,i="clone"){try{r(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);n&&(o=o.split(n).join("***")),console.error(`[${i}] WARNING: failed to strip token from .git/config: ${o}`)}}function ut(r,e,t={}){return new Promise((n,i)=>{let s=Io(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),s.on("error",c=>i(c))})}var me={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],inProcessOnly:!0,promptFragment:`## Git Repositories
75
75
  You can clone and explore git repositories locally for codebase analysis:
76
76
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
77
77
  - git_list_repos: List locally cloned repos
@@ -85,7 +85,7 @@ When your task needs repository context you don't have yet:
85
85
 
86
86
  <!-- zbfp:${r} -->`}var mt=`
87
87
 
88
- <!-- zbreview-summary -->`;function ft(r){let e=Vr.exec(String(r||""));return e?e[1].toLowerCase():null}function ht(r){return Qr.test(String(r||""))}function yt(r,e){let t=new Set([...e||[]].map(s=>String(s).toLowerCase())),n=[],i=0;for(let s of Array.isArray(r)?r:[]){if(!s||!s.body)continue;let o=Po(s.path,s.body);if(t.has(o)){i+=1;continue}t.add(o),n.push({...s,_fp:o,body:`${String(s.body)}${Co(o)}`})}return{toPost:n,skipped:i}}function Do(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=qo(Jo(import.meta.url)),e=Bo(r,"..","bin","mcp-skill.mjs");return Uo(e)?e:null}async function v(r,e={}){let{token:t}=await Xr("github"),n=r.startsWith("https://")?r:`https://api.github.com${r}`,i={Authorization:`Bearer ${t}`,Accept:e.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`)}return e.raw?s.text():s.json()}var je={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:N.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
88
+ <!-- zbreview-summary -->`;function ft(r){let e=Vr.exec(String(r||""));return e?e[1].toLowerCase():null}function ht(r){return Qr.test(String(r||""))}function yt(r,e){let t=new Set([...e||[]].map(s=>String(s).toLowerCase())),n=[],i=0;for(let s of Array.isArray(r)?r:[]){if(!s||!s.body)continue;let o=Po(s.path,s.body);if(t.has(o)){i+=1;continue}t.add(o),n.push({...s,_fp:o,body:`${String(s.body)}${Co(o)}`})}return{toPost:n,skipped:i}}function Do(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Bo(Jo(import.meta.url)),e=qo(r,"..","bin","mcp-skill.mjs");return Uo(e)?e:null}async function v(r,e={}){let{token:t}=await Xr("github"),n=r.startsWith("https://")?r:`https://api.github.com${r}`,i={Authorization:`Bearer ${t}`,Accept:e.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...e.body?{"Content-Type":"application/json"}:{}},s=await fetch(n,{method:e.method||"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`)}return e.raw?s.text():s.json()}var je={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:N.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
89
89
  You have access to the user's GitHub repositories. Available tools:
90
90
 
91
91
  ### Discovery
@@ -130,7 +130,7 @@ When user says "check out repo-name" or "clone repo-name":
130
130
  When user just wants to "look at" or "read" files (not clone):
131
131
  - Use github_get_file to read individual files via API`,resolve(){let r=Do();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/github.js","githubSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"github_search_issues":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let n=await v(`/search/issues?q=${encodeURIComponent(t)}&per_page=${e.limit||20}`),i=(n.items||[]).map(s=>({number:s.number,title:s.title,state:s.state,repo:s.repository_url?.split("/").slice(-2).join("/"),url:s.html_url,user:s.user?.login,isPR:!!s.pull_request,labels:(s.labels||[]).map(o=>o.name),createdAt:s.created_at}));return JSON.stringify({total:n.total_count,items:i})}case"github_search_code":{let t=e.query;if(!t)return JSON.stringify({error:"query is required"});let n=e.repo?`+repo:${e.repo}`:"",i=e.language?`+language:${e.language}`:"",s=await v(`/search/code?q=${encodeURIComponent(t)}${n}${i}&per_page=${e.limit||15}`),o=(s.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:s.total_count,items:o})}case"github_get_pr":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await v(`/repos/${t}/${n}/pulls/${i}`);return JSON.stringify({number:s.number,title:s.title,state:s.state,merged:s.merged,body:s.body?.slice(0,5e3),user:s.user?.login,branch:s.head?.ref,headSha:s.head?.sha,base:s.base?.ref,changedFiles:s.changed_files,additions:s.additions,deletions:s.deletions,createdAt:s.created_at,mergedAt:s.merged_at,url:s.html_url,labels:(s.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await v(`/repos/${t}/${n}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=s.length>15e3;return JSON.stringify({number:i,diff:o?s.slice(0,15e3):s,truncated:o,totalLength:s.length})}case"github_list_pr_files":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await v(`/repos/${t}/${n}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:s.length,files:s.map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:n,number:i}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await v(`/repos/${t}/${n}/pulls/${i}/comments?per_page=50`),o=await v(`/repos/${t}/${n}/issues/${i}/comments?per_page=50`),a=[...s.map(c=>({type:"review",user:c.user?.login,body:c.body?.slice(0,1e3),path:c.path,line:c.line,createdAt:c.created_at})),...o.map(c=>({type:"issue",user:c.user?.login,body:c.body?.slice(0,1e3),createdAt:c.created_at}))].sort((c,d)=>new Date(c.createdAt)-new Date(d.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:t,repo:n,number:i,commentId:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await v(`/repos/${t}/${n}/pulls/comments/${s}`),a=o.in_reply_to_id||o.id,c=[];try{c=await v(`/repos/${t}/${n}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let d=c.filter(u=>u.id===a||u.in_reply_to_id===a).sort((u,m)=>new Date(u.created_at)-new Date(m.created_at)),l=d.length?d:[o],p=l.find(u=>u.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:l.map(u=>({id:u.id,user:u.user?.login,body:(u.body||"").slice(0,4e3),createdAt:u.created_at,isRoot:u.id===a,url:u.html_url}))})}case"github_reply_review_thread":{let{owner:t,repo:n,number:i,commentId:s,body:o}=e||{};if(!t||!n||!i||!s||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await v(`/repos/${t}/${n}/pulls/${i}/comments/${s}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:t,repo:n,number:i,body:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await v(`/repos/${t}/${n}/issues/${i}/comments`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:t,repo:n,number:i,body:s,event:o,comments:a}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let c=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(c))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let d=Array.isArray(a)?a.filter(_=>_&&_.path&&_.body&&(_.line!=null||_.position!=null)).map(_=>{let y={path:_.path,body:String(_.body)};return _.line!=null?(y.line=Number(_.line),y.side=_.side==="LEFT"?"LEFT":"RIGHT"):y.position=Number(_.position),y}):[];if(c!=="APPROVE"&&!s&&d.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l=new Set,p=null;try{for(let _=1;_<=20;_+=1){let y=await v(`/repos/${t}/${n}/pulls/${i}/comments?per_page=100&page=${_}`);if(!Array.isArray(y)||y.length===0)break;for(let k of y){let O=ft(k.body);O&&l.add(O)}if(y.length<100)break}for(let _=1;_<=20&&p==null;_+=1){let y=await v(`/repos/${t}/${n}/issues/${i}/comments?per_page=100&page=${_}`);if(!Array.isArray(y)||y.length===0)break;for(let k of y)if(ht(k.body)){p=k.id;break}if(y.length<100)break}}catch{}let u=!1,m=!1;if(s){let _=`${String(s)}${mt}`;try{p!=null?(await v(`/repos/${t}/${n}/issues/comments/${p}`,{method:"PATCH",body:{body:_}}),u=!0):await v(`/repos/${t}/${n}/issues/${i}/comments`,{method:"POST",body:{body:_}}),m=!0}catch{}}let{toPost:f,skipped:h}=yt(d,l),b=f.map(({_fp:_,...y})=>y),g=null;if(b.length>0||c==="APPROVE"||c==="REQUEST_CHANGES"){let _={event:c};b.length>0&&(_.comments=b),b.length===0&&c==="REQUEST_CHANGES"&&(_.body="Changes requested \u2014 see the review summary comment."),g=await v(`/repos/${t}/${n}/pulls/${i}/reviews`,{method:"POST",body:_})}return JSON.stringify({ok:!0,id:g?g.id:void 0,state:g?g.state:void 0,event:c,notePosted:m,summaryUpdated:u,commentsPosted:b.length,inlineSkipped:h||void 0,url:g?g.html_url:void 0})}case"github_list_commits":{let{owner:t,repo:n,branch:i,path:s,limit:o,since:a,until:c,page:d}=e;if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let l=Math.min(Number(o)||20,100),p=`/repos/${t}/${n}/commits?per_page=${l}&page=${Number(d)||1}`;i&&(p+=`&sha=${encodeURIComponent(i)}`),s&&(p+=`&path=${encodeURIComponent(s)}`),a&&(p+=`&since=${encodeURIComponent(a)}`),c&&(p+=`&until=${encodeURIComponent(c)}`);let u=await v(p);return JSON.stringify({total:u.length,page:Number(d)||1,hasMore:u.length>=l,commits:u.map(m=>({sha:m.sha?.slice(0,8),fullSha:m.sha,message:m.commit?.message?.slice(0,300),author:m.commit?.author?.name,authorEmail:m.commit?.author?.email,date:m.commit?.author?.date,url:m.html_url}))})}case"github_get_commit":{let{owner:t,repo:n,sha:i,includePrs:s}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let o=await v(`/repos/${t}/${n}/commits/${i}`),a;if(s)try{let c=await v(`/repos/${t}/${n}/commits/${i}/pulls`);a=(Array.isArray(c)?c:[]).map(d=>({number:d.number,title:d.title,state:d.state,merged:!!d.merged_at,webUrl:d.html_url}))}catch{a=[]}return JSON.stringify({sha:o.sha?.slice(0,8),message:o.commit?.message,author:o.commit?.author?.name,date:o.commit?.author?.date,stats:o.stats,files:(o.files||[]).map(c=>({filename:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:t,repo:n,path:i,ref:s}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${t}/${n}/contents/${encodeURIComponent(i)}`;s&&(o+=`?ref=${encodeURIComponent(s)}`);let a=await v(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:i,entries:a.map(l=>({name:l.name,type:l.type,size:l.size,path:l.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),d=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:d?c.slice(0,2e4):c,truncated:d})}case"github_get_user":try{let t=await v("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let n=t.repositories[0],i=n.owner.login,s=n.owner.type,o=s==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await v(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:s,isOrg:s==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(t){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${t.message})`})}case"github_list_orgs":try{let n=(await v("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of n)o.owner.type==="Organization"&&(i.has(o.owner.login)||i.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let s=Array.from(i.values());return JSON.stringify({count:s.length,orgs:s,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(t){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${t.message}`})}case"github_clone":{let f=function(_){let y=_.replace(/^~(?=$|\/|\\)/,m);return a(y)},{owner:t,repo:n,destination:i}=e;if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let{execSync:s}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:d}=await import("fs"),{homedir:l,platform:p}=await import("os"),{token:u}=await Xr("github"),m=l(),h=i?f(i):o(m,"zibby-repos"),b=o(h,n);if(d(h,{recursive:!0}),c(b))return JSON.stringify({error:`Directory ${b} already exists. Remove it first or use a different destination.`,existingPath:b});let g=`https://x-access-token:${u}@github.com/${t}/${n}.git`;try{s(`git clone ${g} "${b}"`,{stdio:"pipe"});let _=`https://github.com/${t}/${n}.git`;Ge(s,b,_,u,"github_clone");let y=p()==="win32",k;return y?k=s(`dir "${b}"`,{encoding:"utf-8",shell:"cmd.exe"}):k=s(`ls -la "${b}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:b,message:`Cloned ${t}/${n} to ${b}`,contents:k.split(`
132
132
  `).slice(0,30).join(`
133
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(_){let k=String(_.message||_).split(u).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${k}`})}}case"github_search_repos":{let{query:t,limit:n}=e;if(!t)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),s=JSON.parse(i);if(s.error)return JSON.stringify(s);let o=t.toLowerCase(),a=s.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:t,count:a.length,repos:a.slice(0,n||20)})}case"github_list_repos":{let{owner:t,type:n,sort:i,direction:s,limit:o,query:a}=e,c=100,d=o||200,l=[],p=y=>({name:y.name,fullName:y.full_name,private:y.private,description:y.description,language:y.language,defaultBranch:y.default_branch,updatedAt:y.updated_at,stars:y.stargazers_count,url:y.html_url,fullPath:y.full_name,webUrl:y.html_url,visibility:y.visibility||(y.private?"private":"public")}),u=y=>{if(!a)return!0;let k=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(k)||y.fullName&&y.fullName.toLowerCase().includes(k)||y.description&&y.description.toLowerCase().includes(k)};if(!t){let y=1,k=!0;for(;k&&l.length<d;){let B=`/installation/repositories?per_page=${c}&page=${y}`,_e=(await v(B)).repositories||[];if(_e.length===0)break;l=l.concat(_e),k=_e.length===c,y++}let O=l.map(p).filter(u),z=O.slice(0,d),Ee=O.length>z.length,A=z.filter(B=>B.private).length,T=z.filter(B=>!B.private).length;return JSON.stringify({count:z.length,repos:z,truncated:Ee,privateCount:A,publicCount:T,message:`Found ${A} private and ${T} public repos`})}let m=await v(`/orgs/${t}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&l.length<d;){let y;m?y=`/orgs/${t}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:y=`/users/${t}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let k=await v(y),O=Array.isArray(k)?k:[];if(O.length===0)break;l=l.concat(O),h=O.length===c,f++}let b=l.map(p).filter(u),g=b.slice(0,d),_=b.length>g.length;return JSON.stringify({count:g.length,repos:g,truncated:_})}case"github_create_pr":{let{owner:t,repo:n,head:i,title:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=e.base;if(!o)try{o=(await v(`/repos/${t}/${n}`)).default_branch||"main"}catch{o="main"}let a={title:String(s),head:String(i),base:String(o),body:e.body?String(e.body):"",draft:!!e.draft};try{let c=await v(`/repos/${t}/${n}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${t}/${n}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let d=String(c.message||c);if(/GitHub API 422/.test(d))return JSON.stringify({success:!1,branch:i,base:o,repo:`${t}/${n}`,provider:"github",skippedReason:d});throw c}}case"github_merge_pr":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=e.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(s))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${s})`});let o={merge_method:s};e.commitTitle&&(o.commit_title=String(e.commitTitle)),e.commitMessage&&(o.commit_message=String(e.commitMessage));try{let a=await v(`/repos/${t}/${n}/pulls/${i}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:i,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:t,repo:n,title:i,body:s}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await v(`/repos/${t}/${n}/issues`,{method:"POST",body:{title:i,body:s||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:t,repo:n,state:i,labels:s,since:o,assignee:a,sort:c,direction:d,limit:l}=e||{};if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",i||"open"),p.set("per_page",String(l||30)),p.set("sort",c||"updated"),p.set("direction",d||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),o&&p.set("since",o),a&&p.set("assignee",a);let u=await v(`/repos/${t}/${n}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await v(`/repos/${t}/${n}/issues/${i}`);return s.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:s.number,title:s.title,body:s.body||"",state:s.state,stateReason:s.state_reason||null,labels:(s.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:s.assignee?.login||null,assignees:(s.assignees||[]).map(o=>o.login),user:s.user?.login,milestone:s.milestone?.title||null,comments:s.comments,url:s.html_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:n,number:i,limit:s}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await v(`/repos/${t}/${n}/issues/${i}/comments?per_page=${s||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:t,repo:n,number:i,body:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await v(`/repos/${t}/${n}/issues/${i}/comments`,{method:"POST",body:{body:s}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:t,repo:n,number:i,stateReason:s}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};s&&(o.state_reason=s);let a=await v(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await v(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:s.number,state:s.state,url:s.html_url})}case"github_label_issue":{let{owner:t,repo:n,number:i,labels:s,mode:o}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(s)?s:s?[s]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await v(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await v(`/repos/${t}/${n}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await v(`/repos/${t}/${n}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let d=await v(`/repos/${t}/${n}/issues/${i}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(d)?d:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};import{existsSync as Mo}from"fs";import{fileURLToPath as Fo}from"url";import{dirname as Ko,resolve as Go}from"path";function Ho(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ko(Fo(import.meta.url)),e=Go(r,"..","bin","mcp-skill.mjs");return Mo(e)?e:null}function zo(){let r=process.env.GITLAB_API_URL;if(r)return r.replace(/\/+$/,"");let e=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(e)?e:`${e}/api/v4`}function Yo(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let r=process.env.GITLAB_TOKEN;if(!r)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":r}}async function R(r,e={}){let t=/^https?:\/\//.test(r)?r:`${zo()}${r}`,n={Accept:"application/json","User-Agent":"Zibby-App",...Yo(),...e.body?{"Content-Type":"application/json"}:{}},i=await fetch(t,{method:e.method||"GET",headers:n,body:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`GitLab API ${i.status}: ${s.slice(0,300)}`)}return e.raw?i.text():i.json()}function en(){let r=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(r?r.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Wo(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function j(r){let e=String(r);return/^\d+$/.test(e)?e:encodeURIComponent(e)}var $e={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:N.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
133
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(_){let k=String(_.message||_).split(u).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${k}`})}}case"github_search_repos":{let{query:t,limit:n}=e;if(!t)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),s=JSON.parse(i);if(s.error)return JSON.stringify(s);let o=t.toLowerCase(),a=s.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:t,count:a.length,repos:a.slice(0,n||20)})}case"github_list_repos":{let{owner:t,type:n,sort:i,direction:s,limit:o,query:a}=e,c=100,d=o||200,l=[],p=y=>({name:y.name,fullName:y.full_name,private:y.private,description:y.description,language:y.language,defaultBranch:y.default_branch,updatedAt:y.updated_at,stars:y.stargazers_count,url:y.html_url,fullPath:y.full_name,webUrl:y.html_url,visibility:y.visibility||(y.private?"private":"public")}),u=y=>{if(!a)return!0;let k=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(k)||y.fullName&&y.fullName.toLowerCase().includes(k)||y.description&&y.description.toLowerCase().includes(k)};if(!t){let y=1,k=!0;for(;k&&l.length<d;){let q=`/installation/repositories?per_page=${c}&page=${y}`,_e=(await v(q)).repositories||[];if(_e.length===0)break;l=l.concat(_e),k=_e.length===c,y++}let O=l.map(p).filter(u),z=O.slice(0,d),Ee=O.length>z.length,A=z.filter(q=>q.private).length,T=z.filter(q=>!q.private).length;return JSON.stringify({count:z.length,repos:z,truncated:Ee,privateCount:A,publicCount:T,message:`Found ${A} private and ${T} public repos`})}let m=await v(`/orgs/${t}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&l.length<d;){let y;m?y=`/orgs/${t}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:y=`/users/${t}/repos?per_page=${c}&page=${f}&type=${n||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let k=await v(y),O=Array.isArray(k)?k:[];if(O.length===0)break;l=l.concat(O),h=O.length===c,f++}let b=l.map(p).filter(u),g=b.slice(0,d),_=b.length>g.length;return JSON.stringify({count:g.length,repos:g,truncated:_})}case"github_create_pr":{let{owner:t,repo:n,head:i,title:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=e.base;if(!o)try{o=(await v(`/repos/${t}/${n}`)).default_branch||"main"}catch{o="main"}let a={title:String(s),head:String(i),base:String(o),body:e.body?String(e.body):"",draft:!!e.draft};try{let c=await v(`/repos/${t}/${n}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${t}/${n}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let d=String(c.message||c);if(/GitHub API 422/.test(d))return JSON.stringify({success:!1,branch:i,base:o,repo:`${t}/${n}`,provider:"github",skippedReason:d});throw c}}case"github_merge_pr":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=e.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(s))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${s})`});let o={merge_method:s};e.commitTitle&&(o.commit_title=String(e.commitTitle)),e.commitMessage&&(o.commit_message=String(e.commitMessage));try{let a=await v(`/repos/${t}/${n}/pulls/${i}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:i,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:t,repo:n,title:i,body:s}=e;if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await v(`/repos/${t}/${n}/issues`,{method:"POST",body:{title:i,body:s||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:t,repo:n,state:i,labels:s,since:o,assignee:a,sort:c,direction:d,limit:l}=e||{};if(!t||!n)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",i||"open"),p.set("per_page",String(l||30)),p.set("sort",c||"updated"),p.set("direction",d||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),o&&p.set("since",o),a&&p.set("assignee",a);let u=await v(`/repos/${t}/${n}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await v(`/repos/${t}/${n}/issues/${i}`);return s.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:s.number,title:s.title,body:s.body||"",state:s.state,stateReason:s.state_reason||null,labels:(s.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:s.assignee?.login||null,assignees:(s.assignees||[]).map(o=>o.login),user:s.user?.login,milestone:s.milestone?.title||null,comments:s.comments,url:s.html_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:n,number:i,limit:s}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await v(`/repos/${t}/${n}/issues/${i}/comments?per_page=${s||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:t,repo:n,number:i,body:s}=e||{};if(!t||!n||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await v(`/repos/${t}/${n}/issues/${i}/comments`,{method:"POST",body:{body:s}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:t,repo:n,number:i,stateReason:s}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};s&&(o.state_reason=s);let a=await v(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:t,repo:n,number:i}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await v(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:s.number,state:s.state,url:s.html_url})}case"github_label_issue":{let{owner:t,repo:n,number:i,labels:s,mode:o}=e||{};if(!t||!n||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(s)?s:s?[s]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await v(`/repos/${t}/${n}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await v(`/repos/${t}/${n}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await v(`/repos/${t}/${n}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let d=await v(`/repos/${t}/${n}/issues/${i}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(d)?d:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};import{existsSync as Mo}from"fs";import{fileURLToPath as Fo}from"url";import{dirname as Ko,resolve as Go}from"path";function Ho(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ko(Fo(import.meta.url)),e=Go(r,"..","bin","mcp-skill.mjs");return Mo(e)?e:null}function zo(){let r=process.env.GITLAB_API_URL;if(r)return r.replace(/\/+$/,"");let e=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(e)?e:`${e}/api/v4`}function Yo(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let r=process.env.GITLAB_TOKEN;if(!r)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":r}}async function R(r,e={}){let t=/^https?:\/\//.test(r)?r:`${zo()}${r}`,n={Accept:"application/json","User-Agent":"Zibby-App",...Yo(),...e.body?{"Content-Type":"application/json"}:{}},i=await fetch(t,{method:e.method||"GET",headers:n,body:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`GitLab API ${i.status}: ${s.slice(0,300)}`)}return e.raw?i.text():i.json()}function en(){let r=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(r?r.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Wo(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function j(r){let e=String(r);return/^\d+$/.test(e)?e:encodeURIComponent(e)}var $e={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:N.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
134
134
  You have access to the user's GitLab projects via the REST API (cloud gitlab.com OR self-hosted). A "merge request" (MR) is GitLab's pull request. An MR is addressed by a PROJECT (numeric id OR full path like "group/repo") and an \`iid\` (the per-project MR number shown in the URL). For projects, prefer the full path form ("group/subgroup/repo") \u2014 it's what users have. Available tools:
135
135
 
136
136
  ### Discovery
@@ -336,14 +336,14 @@ You have access to the user's Slack workspace. Use these tools:
336
336
  - slack_add_reaction, slack_get_channel_history, slack_get_thread_replies
337
337
  - slack_get_users, slack_get_user_profile
338
338
  - slack_lookup_user_by_email (precise email\u2192user_id, prefer this over scanning slack_get_users)
339
- - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=Ea();if(!r)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[t]&&(e[t]=process.env[t]);for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"slack_list_channels":{let t=await G("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(t.channels||[]).map(n=>({id:n.id,name:n.name,topic:n.topic?.value}))})}case"slack_post_message":{if(!e.channel||!e.text)return JSON.stringify({error:"channel and text are required"});let t=await G("chat.postMessage",{channel:e.channel,text:e.text,...e.blocks?{blocks:e.blocks}:{}});return JSON.stringify({ok:!0,ts:t.ts,channel:t.channel})}case"slack_reply_to_thread":{if(!e.channel||!e.thread_ts||!e.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let t=await G("chat.postMessage",{channel:e.channel,thread_ts:e.thread_ts,text:e.text});return JSON.stringify({ok:!0,ts:t.ts})}case"slack_add_reaction":return!e.channel||!e.timestamp||!e.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await G("reactions.add",{channel:e.channel,timestamp:e.timestamp,name:e.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!e.channel)return JSON.stringify({error:"channel is required"});let t=await G("conversations.history",{channel:e.channel,limit:e.limit||20});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_thread_replies":{if(!e.channel||!e.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let t=await G("conversations.replies",{channel:e.channel,ts:e.thread_ts});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_users":{let t=await G("users.list",{limit:100});return JSON.stringify({users:(t.members||[]).filter(n=>!n.is_bot&&!n.deleted).map(n=>({id:n.id,name:n.real_name||n.name}))})}case"slack_get_user_profile":{if(!e.user_id)return JSON.stringify({error:"user_id is required"});let t=await G("users.profile.get",{user:e.user_id});return JSON.stringify({profile:t.profile})}case"slack_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});try{let t=await G("users.lookupByEmail",{email:e.email});return JSON.stringify({ok:!0,user:{id:t.user?.id,name:t.user?.real_name||t.user?.name,email:t.user?.profile?.email||e.email}})}catch(t){if(/users_not_found/.test(t.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw t}}case"slack_list_usergroups":{let t=await G("usergroups.list",{});return JSON.stringify({usergroups:(t.usergroups||[]).map(n=>({id:n.id,handle:n.handle,name:n.name,description:n.description||"",user_count:Number(n.user_count||0)}))})}case"slack_get_usergroup_members":{if(!e.usergroup)return JSON.stringify({error:"usergroup id is required"});let t=await G("usergroups.users.list",{usergroup:e.usergroup});return JSON.stringify({users:t.users||[]})}case"slack_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),i=[],s,o=5;for(let c=0;c<o;c+=1){let d={limit:200};s&&(d.cursor=s);let l=await G("users.list",d);for(let p of l.members||[])p.deleted||p.is_bot||i.push(p);if(s=l.response_metadata?.next_cursor,!s)break}let a=[];for(let c of i){let d=(c.real_name||"").toLowerCase(),l=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;d.includes(t)&&(u+=100-Math.abs(d.length-t.length)),l.includes(t)&&(u+=60-Math.abs(l.length-t.length)),p.includes(t)&&(u+=30-Math.abs(p.length-t.length)),(d===t||l===t)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,n).map(({_score:c,...d})=>d),scanned:i.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as xa}from"fs";import{fileURLToPath as La}from"url";import{dirname as ja,resolve as $a}from"path";import{resolveIntegrationToken as Pa}from"@zibby/core/backend-client.js";function Ca(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=ja(La(import.meta.url)),e=$a(r,"..","bin","mcp-lark.mjs");return xa(e)?e:null}var Ua=6e3*1e3,Ye=null;async function Ja(){let{appId:r,appSecret:e,host:t}=await Pa("lark");if(Ye&&Ye.appId===r&&Ye.expiresAt>Date.now())return{token:Ye.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return Ye={token:i.tenant_access_token,expiresAt:Date.now()+Ua,appId:r},{token:i.tenant_access_token,host:t}}async function be(r,e,t={}){let{token:n,host:i}=await Ja(),s=`${i}${e}`,o={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(o.body=JSON.stringify(t));let c=await(await fetch(s,o)).json();if(c.code!==0)throw new Error(`Lark API ${e} error: ${c.msg||c.code}`);return c.data||{}}function mn(r){return JSON.stringify({text:r})}function qa(r){return!r||typeof r!="string"||r.startsWith("oc_")?"chat_id":r.startsWith("ou_")?"open_id":r.startsWith("on_")?"union_id":r.startsWith("cli_")?"app_id":r.includes("@")?"email":"chat_id"}var D={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:N.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark
339
+ - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=Ea();if(!r)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[t]&&(e[t]=process.env[t]);for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r],env:e,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"slack_list_channels":{let t=await G("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(t.channels||[]).map(n=>({id:n.id,name:n.name,topic:n.topic?.value}))})}case"slack_post_message":{if(!e.channel||!e.text)return JSON.stringify({error:"channel and text are required"});let t=await G("chat.postMessage",{channel:e.channel,text:e.text,...e.blocks?{blocks:e.blocks}:{}});return JSON.stringify({ok:!0,ts:t.ts,channel:t.channel})}case"slack_reply_to_thread":{if(!e.channel||!e.thread_ts||!e.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let t=await G("chat.postMessage",{channel:e.channel,thread_ts:e.thread_ts,text:e.text});return JSON.stringify({ok:!0,ts:t.ts})}case"slack_add_reaction":return!e.channel||!e.timestamp||!e.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await G("reactions.add",{channel:e.channel,timestamp:e.timestamp,name:e.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!e.channel)return JSON.stringify({error:"channel is required"});let t=await G("conversations.history",{channel:e.channel,limit:e.limit||20});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_thread_replies":{if(!e.channel||!e.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let t=await G("conversations.replies",{channel:e.channel,ts:e.thread_ts});return JSON.stringify({messages:(t.messages||[]).map(n=>({user:n.user,text:n.text,ts:n.ts}))})}case"slack_get_users":{let t=await G("users.list",{limit:100});return JSON.stringify({users:(t.members||[]).filter(n=>!n.is_bot&&!n.deleted).map(n=>({id:n.id,name:n.real_name||n.name}))})}case"slack_get_user_profile":{if(!e.user_id)return JSON.stringify({error:"user_id is required"});let t=await G("users.profile.get",{user:e.user_id});return JSON.stringify({profile:t.profile})}case"slack_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});try{let t=await G("users.lookupByEmail",{email:e.email});return JSON.stringify({ok:!0,user:{id:t.user?.id,name:t.user?.real_name||t.user?.name,email:t.user?.profile?.email||e.email}})}catch(t){if(/users_not_found/.test(t.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw t}}case"slack_list_usergroups":{let t=await G("usergroups.list",{});return JSON.stringify({usergroups:(t.usergroups||[]).map(n=>({id:n.id,handle:n.handle,name:n.name,description:n.description||"",user_count:Number(n.user_count||0)}))})}case"slack_get_usergroup_members":{if(!e.usergroup)return JSON.stringify({error:"usergroup id is required"});let t=await G("usergroups.users.list",{usergroup:e.usergroup});return JSON.stringify({users:t.users||[]})}case"slack_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),i=[],s,o=5;for(let c=0;c<o;c+=1){let d={limit:200};s&&(d.cursor=s);let l=await G("users.list",d);for(let p of l.members||[])p.deleted||p.is_bot||i.push(p);if(s=l.response_metadata?.next_cursor,!s)break}let a=[];for(let c of i){let d=(c.real_name||"").toLowerCase(),l=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;d.includes(t)&&(u+=100-Math.abs(d.length-t.length)),l.includes(t)&&(u+=60-Math.abs(l.length-t.length)),p.includes(t)&&(u+=30-Math.abs(p.length-t.length)),(d===t||l===t)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,n).map(({_score:c,...d})=>d),scanned:i.length})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as xa}from"fs";import{fileURLToPath as La}from"url";import{dirname as ja,resolve as $a}from"path";import{resolveIntegrationToken as Pa}from"@zibby/core/backend-client.js";function Ca(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=ja(La(import.meta.url)),e=$a(r,"..","bin","mcp-lark.mjs");return xa(e)?e:null}var Ua=6e3*1e3,Ye=null;async function Ja(){let{appId:r,appSecret:e,host:t}=await Pa("lark");if(Ye&&Ye.appId===r&&Ye.expiresAt>Date.now())return{token:Ye.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return Ye={token:i.tenant_access_token,expiresAt:Date.now()+Ua,appId:r},{token:i.tenant_access_token,host:t}}async function be(r,e,t={}){let{token:n,host:i}=await Ja(),s=`${i}${e}`,o={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(o.body=JSON.stringify(t));let c=await(await fetch(s,o)).json();if(c.code!==0)throw new Error(`Lark API ${e} error: ${c.msg||c.code}`);return c.data||{}}function mn(r){return JSON.stringify({text:r})}function Ba(r){return!r||typeof r!="string"||r.startsWith("oc_")?"chat_id":r.startsWith("ou_")?"open_id":r.startsWith("on_")?"union_id":r.startsWith("cli_")?"app_id":r.includes("@")?"email":"chat_id"}var D={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:N.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],promptFragment:`## Lark
340
340
  You can send messages and replies on Lark. Use:
341
341
  - lark_send_message: post a message to a chat, user, or DM
342
342
  - lark_reply: reply to an existing message (threaded)
343
343
  - lark_list_chats: list chats the bot is a member of
344
344
  - lark_get_chat_history: fetch recent messages in a chat
345
345
  - 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)
346
- When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=Ca();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=qa(e.receive_id),n=await be("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:mn(e.text)});return JSON.stringify({ok:!0,message_id:n.message_id})}case"lark_reply":{if(!e.message_id||!e.text)return JSON.stringify({error:"message_id and text are required"});let t=await be("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:mn(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,i=((await be("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(s=>({chat_id:s.chat_id,name:s.name,description:s.description,owner_id:s.owner_id,chat_mode:s.chat_mode}));return JSON.stringify({chats:i})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,i=((await be("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(s=>({message_id:s.message_id,sender_id:s.sender?.id,sender_type:s.sender?.sender_type,msg_type:s.msg_type,content:s.body?.content,create_time:s.create_time}));return JSON.stringify({messages:i})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let n=((await be("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(i=>i.email===e.email&&i.user_id);return JSON.stringify(n?{ok:!0,user:{open_id:n.user_id,email:n.email,name:n.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),i=200,o=((await be("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(l=>l.chat_id),a=new Set,c=[];for(let l of o){if(c.length>=i)break;try{let p=await be("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=i))break}catch(p){console.warn(`[lark] member scan failed for ${l}: ${p.message}`)}}let d=[];for(let l of c){let p=(l.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(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,n).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 Ba}from"fs";import{fileURLToPath as Da}from"url";import{dirname as Ma,resolve as Fa}from"path";import{resolveIntegrationToken as Ka}from"@zibby/core/backend-client.js";function Ga(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ma(Da(import.meta.url)),e=Fa(r,"..","bin","mcp-skill.mjs");return Ba(e)?e:null}var Ha=process.env.DISCORD_API_URL||"https://discord.com/api/v10",za=2e3;function Ya(r,e=za){let t=String(r??"");if(!t.trim())return[];if(t.length<=e)return[t];let n=[],i=t;for(;i.length>e;){let o=i.slice(0,e).lastIndexOf(`
346
+ When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let r=Ca();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=Ba(e.receive_id),n=await be("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:mn(e.text)});return JSON.stringify({ok:!0,message_id:n.message_id})}case"lark_reply":{if(!e.message_id||!e.text)return JSON.stringify({error:"message_id and text are required"});let t=await be("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:mn(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,i=((await be("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(s=>({chat_id:s.chat_id,name:s.name,description:s.description,owner_id:s.owner_id,chat_mode:s.chat_mode}));return JSON.stringify({chats:i})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,i=((await be("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(s=>({message_id:s.message_id,sender_id:s.sender?.id,sender_type:s.sender?.sender_type,msg_type:s.msg_type,content:s.body?.content,create_time:s.create_time}));return JSON.stringify({messages:i})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let n=((await be("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(i=>i.email===e.email&&i.user_id);return JSON.stringify(n?{ok:!0,user:{open_id:n.user_id,email:n.email,name:n.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let n=Math.max(1,Math.min(Number(e.limit)||5,25)),i=200,o=((await be("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(l=>l.chat_id),a=new Set,c=[];for(let l of o){if(c.length>=i)break;try{let p=await be("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=i))break}catch(p){console.warn(`[lark] member scan failed for ${l}: ${p.message}`)}}let d=[];for(let l of c){let p=(l.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(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,n).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 qa}from"fs";import{fileURLToPath as Da}from"url";import{dirname as Ma,resolve as Fa}from"path";import{resolveIntegrationToken as Ka}from"@zibby/core/backend-client.js";function Ga(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Ma(Da(import.meta.url)),e=Fa(r,"..","bin","mcp-skill.mjs");return qa(e)?e:null}var Ha=process.env.DISCORD_API_URL||"https://discord.com/api/v10",za=2e3;function Ya(r,e=za){let t=String(r??"");if(!t.trim())return[];if(t.length<=e)return[t];let n=[],i=t;for(;i.length>e;){let o=i.slice(0,e).lastIndexOf(`
347
347
  `),a=o>e/2?o+1:e;n.push(i.slice(0,a)),i=i.slice(a)}return i&&n.push(i),n}async function fn(){let r=(process.env.DISCORD_BOT_TOKEN||"").trim();if(r)return{token:r,guildId:(process.env.DISCORD_GUILD_ID||"").trim()};let e=await Ka(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 Vt(r,e,{token:t,body:n}={}){let i=t.startsWith("Bot ")?t:`Bot ${t}`,s=await fetch(`${Ha}${e}`,{method:r,headers:{Authorization:i,...n!==void 0?{"Content-Type":"application/json"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),o=await s.json().catch(()=>null);if(!s.ok){let a=o&&(o.message||o.error)?o.message||o.error:`HTTP ${s.status}`;throw new Error(`Discord API error (${s.status}): ${a}`)}return o}async function Wa({token:r,guildId:e},t){let n=String(t||"").trim()||e||(process.env.DISCORD_GUILD_ID||"").trim();if(n)return n;let i=await Vt("GET","/users/@me/guilds",{token:r}),s=Array.isArray(i)?i:[];if(s.length===1)return s[0].id;if(s.length===0)throw new Error("The bot is not in any Discord server \u2014 invite it to a server first.");let o=s.slice(0,10).map(a=>`${a.name} (${a.id})`).join(", ");throw new Error(`The bot is in ${s.length} servers \u2014 pass guildId explicitly. Servers: ${o}`)}var hn={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
348
348
  You can post to the user's Discord server as their bot. Tools:
349
349
  - discord_send_message(channelId, text) \u2014 post a message to a channel (long text is auto-chunked to Discord's 2000-char limit)
@@ -378,10 +378,10 @@ Attaching an image (optional, both tools):
378
378
  Notes:
379
379
  - Org-page posts are ALWAYS created as a DRAFT; personal-profile posts are ALWAYS published live \u2014 choose the tool accordingly.
380
380
  - 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.
381
- - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=wc();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 ke("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(t.elements)?t.elements:[],i=[];for(let s of n){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=vn(o);if(!a)continue;let c="",d="";try{let l=(await ke(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=Nn(l),d=l.vanityName||""}catch{}i.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:i.length,organizations:i})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,n=vn(t);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u="";try{let m=(await ke(`/rest/organizations/${n}`,{},"linkedin_business")).body;u=Nn(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:n,urn:o},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await On("linkedin_business",o,a);d.content={media:{id:u,altText:c||""}}}let l=await ke("/rest/posts",{method:"POST",body:d},"linkedin_business"),p=kt(l.headers,"x-restli-id")||kt(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=er(),n=t?t.memberId:(await Xt("linkedin_personal")).memberId;if(!n)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u=(await ke("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",f=u?.sub?String(u.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await On("linkedin_personal",o,a);d.content={media:{id:u,altText:c||""}}}let l=await ke("/rest/posts",{method:"POST",body:d},"linkedin_personal"),p=kt(l.headers,"x-restli-id")||kt(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 xn,statSync as Ec,readFileSync as xc}from"fs";import{fileURLToPath as Lc}from"url";import{basename as jc,dirname as $c,resolve as Pc}from"path";import{resolveIntegrationToken as Cc,clearTokenCache as Uc}from"@zibby/core/backend-client.js";function Jc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=$c(Lc(import.meta.url)),e=Pc(r,"..","bin","mcp-skill.mjs");return xn(e)?e:null}var we="https://docs.googleapis.com/v1",Rn="https://www.googleapis.com/drive/v3",qc="https://www.googleapis.com/upload/drive/v3",Bc=5*1024*1024;function Dc(){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 Mc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Fc(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Kc="You haven't connected your own Google account \u2014 connect it at https://studio.zibby.dev/integrations (Google Docs). For privacy, I can't use anyone else's Google (including the project owner's) on your behalf.",rr=2e4,Gc=25;function tr(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 Hc(){let r,e=Dc();if(e)r=e.token;else{if(Fc()||Mc())throw new Error(Kc);({token:r}=await Cc("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function ne(r,e={}){let t=async()=>{let n=await Hc(),i=await fetch(r,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Google API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Uc("google"),t()}}function zc(r){let e=[],t="",n=0;for(;n<r.length;){let i=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(i){e.push({start:t.length,end:t.length+i[1].length,link:i[2]}),t+=i[1],n+=i[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(s){e.push({start:t.length,end:t.length+s[1].length,bold:!0}),t+=s[1],n+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(n));if(o){e.push({start:t.length,end:t.length+o[1].length,code:!0}),t+=o[1],n+=o[0].length;continue}t+=r[n],n+=1}return{text:t,styles:e}}function An(r,e){let t=String(r??"").replace(/\r\n/g,`
381
+ - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let r=wc();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 ke("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),n=Array.isArray(t.elements)?t.elements:[],i=[];for(let s of n){let o=s.organizationalTarget||s["organizationalTarget~"]||s.organization,a=vn(o);if(!a)continue;let c="",d="";try{let l=(await ke(`/rest/organizations/${a}`,{},"linkedin_business")).body;c=Nn(l),d=l.vanityName||""}catch{}i.push({id:a,urn:`urn:li:organization:${a}`,name:c,vanityName:d})}return JSON.stringify({ok:!0,count:i.length,organizations:i})}case"linkedin_create_draft_post":{let t=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,n=vn(t);if(!n)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:organization:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u="";try{let m=(await ke(`/rest/organizations/${n}`,{},"linkedin_business")).body;u=Nn(m)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:u,id:n,urn:o},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1};if(a){let u=await On("linkedin_business",o,a);d.content={media:{id:u,altText:c||""}}}let l=await ke("/rest/posts",{method:"POST",body:d},"linkedin_business"),p=kt(l.headers,"x-restli-id")||kt(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=er(),n=t?t.memberId:(await Xt("linkedin_personal")).memberId;if(!n)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let i=e?.text;if(typeof i!="string"||!i.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let s=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",o=`urn:li:person:${n}`,a=typeof e?.imagePath=="string"?e.imagePath.trim():"",c=typeof e?.imageAltText=="string"?e.imageAltText:"";if(e?.dry_run===!0)try{let u=(await ke("/v2/userinfo",{},"linkedin_personal")).body,m=u?.name||[u?.given_name,u?.family_name].filter(Boolean).join(" ")||"",f=u?.sub?String(u.sub):n;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:m,id:f,urn:`urn:li:person:${f}`},visibility:s,textPreview:i,...a?{imageWouldAttach:!0,imagePath:a}:{},note:"DRY RUN \u2014 nothing was posted"})}catch(u){return JSON.stringify({dryRun:!0,ok:!1,error:u.message})}let d={author:o,commentary:i,visibility:s,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(a){let u=await On("linkedin_personal",o,a);d.content={media:{id:u,altText:c||""}}}let l=await ke("/rest/posts",{method:"POST",body:d},"linkedin_personal"),p=kt(l.headers,"x-restli-id")||kt(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 xn,statSync as Ec,readFileSync as xc}from"fs";import{fileURLToPath as Lc}from"url";import{basename as jc,dirname as $c,resolve as Pc}from"path";import{resolveIntegrationToken as Cc,clearTokenCache as Uc}from"@zibby/core/backend-client.js";function Jc(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=$c(Lc(import.meta.url)),e=Pc(r,"..","bin","mcp-skill.mjs");return xn(e)?e:null}var we="https://docs.googleapis.com/v1",Rn="https://www.googleapis.com/drive/v3",Bc="https://www.googleapis.com/upload/drive/v3",qc=5*1024*1024;function Dc(){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 Mc(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function Fc(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Kc="You haven't connected your own Google account \u2014 connect it at https://studio.zibby.dev/integrations (Google Docs). For privacy, I can't use anyone else's Google (including the project owner's) on your behalf.",rr=2e4,Gc=25;function tr(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 Hc(){let r,e=Dc();if(e)r=e.token;else{if(Fc()||Mc())throw new Error(Kc);({token:r}=await Cc("google"))}if(typeof r!="string"||!r)throw new Error(`Invalid google token type: ${typeof r}`);return r}async function ne(r,e={}){let t=async()=>{let n=await Hc(),i=await fetch(r,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Google API ${i.status}: ${o.slice(0,300)}`)}let s=await i.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await t()}catch(n){let i=String(n?.message||n||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw n;return Uc("google"),t()}}function zc(r){let e=[],t="",n=0;for(;n<r.length;){let i=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(r.slice(n));if(i){e.push({start:t.length,end:t.length+i[1].length,link:i[2]}),t+=i[1],n+=i[0].length;continue}let s=/^\*\*([^*]+)\*\*/.exec(r.slice(n));if(s){e.push({start:t.length,end:t.length+s[1].length,bold:!0}),t+=s[1],n+=s[0].length;continue}let o=/^`([^`]+)`/.exec(r.slice(n));if(o){e.push({start:t.length,end:t.length+o[1].length,code:!0}),t+=o[1],n+=o[0].length;continue}t+=r[n],n+=1}return{text:t,styles:e}}function An(r,e){let t=String(r??"").replace(/\r\n/g,`
382
382
  `);if(!t.trim())return{requests:[],endIndex:e};let n=t.split(`
383
383
  `),i="",s=[],o=[];for(let l of n){let p=l,u=null,m=null,f=/^(#{1,3})\s+(.*)$/.exec(p),h=/^\s*[-*]\s+(.*)$/.exec(p),b=/^\s*\d+[.)]\s+(.*)$/.exec(p);f?(u=`HEADING_${f[1].length}`,p=f[2]):h?(m="BULLET_DISC_CIRCLE_SQUARE",p=h[1]):b&&(m="NUMBERED_DECIMAL_ALPHA_ROMAN",p=b[1]);let{text:g,styles:_}=zc(p),y=e+i.length;for(let k of _)o.push({...k,start:y+k.start,end:y+k.end});i+=`${g}
384
- `,s.push({start:y,end:e+i.length,named:u,bullet:m})}if(!i)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:i}}];for(let l of s)l.named&&a.push({updateParagraphStyle:{range:{startIndex:l.start,endIndex:l.end},paragraphStyle:{namedStyleType:l.named},fields:"namedStyleType"}});let c=null,d=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let l of s)l.bullet?c&&c.preset===l.bullet?c.end=l.end:(d(),c={start:l.start,end:l.end,preset:l.bullet}):d();d();for(let l of o)l.end<=l.start||(l.bold?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{bold:!0},fields:"bold"}}):l.link?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{link:{url:l.link}},fields:"link"}}):l.code&&a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:e+i.length}}function Yc(r){let e="",t=n=>{for(let i of Array.isArray(n)?n:[]){if(e.length>=rr)return;if(i.paragraph)for(let s of i.paragraph.elements||[])e+=s?.textRun?.content||"";else if(i.table)for(let s of i.table.tableRows||[])for(let o of s.tableCells||[])t(o.content);else i.tableOfContents&&t(i.tableOfContents.content)}};return t(r?.content),e.slice(0,rr)}var Ze=r=>`https://docs.google.com/document/d/${r}/edit`;function Wc(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!xn(e)||!Ec(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=xc(e);if(t.length>Bc)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:jc(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Zc(r,e,t){let n=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${n}\r
384
+ `,s.push({start:y,end:e+i.length,named:u,bullet:m})}if(!i)return{requests:[],endIndex:e};let a=[{insertText:{location:{index:e},text:i}}];for(let l of s)l.named&&a.push({updateParagraphStyle:{range:{startIndex:l.start,endIndex:l.end},paragraphStyle:{namedStyleType:l.named},fields:"namedStyleType"}});let c=null,d=()=>{c&&(a.push({createParagraphBullets:{range:{startIndex:c.start,endIndex:c.end},bulletPreset:c.preset}}),c=null)};for(let l of s)l.bullet?c&&c.preset===l.bullet?c.end=l.end:(d(),c={start:l.start,end:l.end,preset:l.bullet}):d();d();for(let l of o)l.end<=l.start||(l.bold?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{bold:!0},fields:"bold"}}):l.link?a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{link:{url:l.link}},fields:"link"}}):l.code&&a.push({updateTextStyle:{range:{startIndex:l.start,endIndex:l.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:a,endIndex:e+i.length}}function Yc(r){let e="",t=n=>{for(let i of Array.isArray(n)?n:[]){if(e.length>=rr)return;if(i.paragraph)for(let s of i.paragraph.elements||[])e+=s?.textRun?.content||"";else if(i.table)for(let s of i.table.tableRows||[])for(let o of s.tableCells||[])t(o.content);else i.tableOfContents&&t(i.tableOfContents.content)}};return t(r?.content),e.slice(0,rr)}var Ze=r=>`https://docs.google.com/document/d/${r}/edit`;function Wc(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!xn(e)||!Ec(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=xc(e);if(t.length>qc)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:jc(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function Zc(r,e,t){let n=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${n}\r
385
385
  Content-Type: application/json; charset=UTF-8\r
386
386
  \r
387
387
  ${JSON.stringify(r)}\r
@@ -399,9 +399,9 @@ Docs access is PER-USER: each teammate connects their OWN Google account (Integr
399
399
  - 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).
400
400
  - gdocs_list_created: list the Google Docs visible to this app (drive.file \u2192 only docs it created or the user picked).
401
401
  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=Jc();if(!r)return null;let e={};for(let t of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"gdocs_create_doc":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let i=(await ne(`${we}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!i)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let s=En(e);if(s&&s.trim()){let{requests:o}=An(s,1);o.length&&await ne(`${we}/documents/${i}:batchUpdate`,{method:"POST",body:{requests:o}})}return JSON.stringify({ok:!0,documentId:i,title:t,url:Ze(i)})}case"gdocs_append":{let t=tr(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=En(e);if(!n||!n.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=(await ne(`${we}/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:`
402
- `}}),l=c+1);let p=An(n,l);return d.push(...p.requests),await ne(`${we}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:Ze(t)})}case"gdocs_insert_image":{let t=tr(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:n,fileName:i,mimeType:s}=Wc(e.imagePath),{rawBody:o,contentType:a}=Zc({name:i,mimeType:s},n,s),d=(await ne(`${qc}/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 ne(`${Rn}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await ne(`${we}/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 ne(`${we}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:Ze(t)})}case"gdocs_get":{let t=tr(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=await ne(`${we}/documents/${t}`),i=Yc(n?.body);return JSON.stringify({ok:!0,documentId:t,title:n?.title||"",url:Ze(t),text:i,...i.length>=rr?{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(Gc),orderBy:"modifiedTime desc"}),n=await ne(`${Rn}/files?${t.toString()}`),i=(Array.isArray(n?.files)?n.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||Ze(s.id)}));return JSON.stringify({ok:!0,count:i.length,files:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). 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 Cn,statSync as Vc,readFileSync as Qc}from"fs";import{fileURLToPath as Xc}from"url";import{basename as el,dirname as tl,resolve as rl}from"path";import{resolveIntegrationToken as nl}from"@zibby/core/backend-client.js";function il(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=tl(Xc(import.meta.url)),e=rl(r,"..","bin","mcp-skill.mjs");return Cn(e)?e:null}var jn=2e4,$n=50,sl=50,ol=20,al=10*1024*1024,cl=6e3*1e3,Ve=null;async function Un(){let{appId:r,appSecret:e,host:t}=await nl("lark");if(Ve&&Ve.appId===r&&Ve.expiresAt>Date.now())return{token:Ve.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return Ve={token:i.tenant_access_token,expiresAt:Date.now()+cl,appId:r},{token:i.tenant_access_token,host:t}}async function H(r,e,t){let{token:n,host:i}=await Un(),s={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(s.body=JSON.stringify(t));let a=await(await fetch(`${i}${e}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:i}}function Qe(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function ll(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/wiki/${e}`:`https://www.larksuite.com/wiki/${e}`}function Se(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 Ue(r){let e=typeof r=="string"?Se(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 H("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),n=t?.node||{};if(n.obj_type!=="docx"||!n.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${n.obj_type||"unknown"})`);return n.obj_token}function nr(r){let e=String(r??"").replace(/\r\n/g,`
402
+ `}}),l=c+1);let p=An(n,l);return d.push(...p.requests),await ne(`${we}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:d}}),JSON.stringify({ok:!0,documentId:t,url:Ze(t)})}case"gdocs_insert_image":{let t=tr(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:n,fileName:i,mimeType:s}=Wc(e.imagePath),{rawBody:o,contentType:a}=Zc({name:i,mimeType:s},n,s),d=(await ne(`${Bc}/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 ne(`${Rn}/files/${d}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let l=await ne(`${we}/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 ne(`${we}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:d,url:Ze(t)})}case"gdocs_get":{let t=tr(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let n=await ne(`${we}/documents/${t}`),i=Yc(n?.body);return JSON.stringify({ok:!0,documentId:t,title:n?.title||"",url:Ze(t),text:i,...i.length>=rr?{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(Gc),orderBy:"modifiedTime desc"}),n=await ne(`${Rn}/files?${t.toString()}`),i=(Array.isArray(n?.files)?n.files:[]).map(s=>({documentId:s.id,title:s.name,modifiedTime:s.modifiedTime,url:s.webViewLink||Ze(s.id)}));return JSON.stringify({ok:!0,count:i.length,files:i})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). 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 Cn,statSync as Vc,readFileSync as Qc}from"fs";import{fileURLToPath as Xc}from"url";import{basename as el,dirname as tl,resolve as rl}from"path";import{resolveIntegrationToken as nl}from"@zibby/core/backend-client.js";function il(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=tl(Xc(import.meta.url)),e=rl(r,"..","bin","mcp-skill.mjs");return Cn(e)?e:null}var jn=2e4,$n=50,sl=50,ol=20,al=10*1024*1024,cl=6e3*1e3,Ve=null;async function Un(){let{appId:r,appSecret:e,host:t}=await nl("lark");if(Ve&&Ve.appId===r&&Ve.expiresAt>Date.now())return{token:Ve.token,host:t};let i=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return Ve={token:i.tenant_access_token,expiresAt:Date.now()+cl,appId:r},{token:i.tenant_access_token,host:t}}async function H(r,e,t){let{token:n,host:i}=await Un(),s={method:r,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&t!==void 0&&(s.body=JSON.stringify(t));let a=await(await fetch(`${i}${e}`,s)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:i}}function Qe(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function ll(r,e){return String(r||"").includes("feishu")?`https://feishu.cn/wiki/${e}`:`https://www.larksuite.com/wiki/${e}`}function Se(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 Ue(r){let e=typeof r=="string"?Se(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 H("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),n=t?.node||{};if(n.obj_type!=="docx"||!n.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${n.obj_type||"unknown"})`);return n.obj_token}function nr(r){let e=String(r??"").replace(/\r\n/g,`
403
403
  `),t=[];for(let n of e.split(`
404
- `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d,l;if(s){let p=s[1].length;c=`heading${p}`,d=2+p,l=s[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=i);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function Xe(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function ir(r,e){let t;for(let n=0;n<e.length;n+=$n){let i=e.slice(n,n+$n);t=(await H("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:i})).host}return t}function dl(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Cn(e)||!Vc(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=Qc(e);if(t.length>al)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function pl({fileName:r,parentNode:e,bytes:t}){let{token:n,host:i}=await Un(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",e),s.set("size",String(t.length)),s.set("file",new Blob([t]),r);let a=await(await fetch(`${i}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${n}`},body:s})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var ul="docx",ml=50;function Pn(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function fl(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function hl(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:fl(t?.content?.elements),createTime:t?.create_time||""}))}}function sr(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():ul}var Jn={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
404
+ `)){let i=n.replace(/\s+$/,"");if(!i.trim())continue;let s=/^(#{1,3})\s+(.*)$/.exec(i),o=/^\s*[-*]\s+(.*)$/.exec(i),a=/^\s*\d+[.)]\s+(.*)$/.exec(i),c,d,l;if(s){let p=s[1].length;c=`heading${p}`,d=2+p,l=s[2]}else o?(c="bullet",d=12,l=o[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=i);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function Xe(r){let e=typeof r?.markdown=="string"?r.markdown:null,t=typeof r?.text=="string"?r.text:null;return e??t}async function ir(r,e){let t;for(let n=0;n<e.length;n+=$n){let i=e.slice(n,n+$n);t=(await H("POST",`/open-apis/docx/v1/documents/${r}/blocks/${r}/children?document_revision_id=-1`,{children:i})).host}return t}function dl(r){let e=typeof r=="string"?r.trim():"";if(!e)throw new Error("imagePath is required");if(!Cn(e)||!Vc(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=Qc(e);if(t.length>al)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function pl({fileName:r,parentNode:e,bytes:t}){let{token:n,host:i}=await Un(),s=new FormData;s.set("file_name",r),s.set("parent_type","docx_image"),s.set("parent_node",e),s.set("size",String(t.length)),s.set("file",new Blob([t]),r);let a=await(await fetch(`${i}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${n}`},body:s})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var ul="docx",ml=50;function Pn(r){return[{type:"text_run",text_run:{text:String(r??"")}}]}function fl(r){return Array.isArray(r)?r.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function hl(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:fl(t?.content?.elements),createTime:t?.create_time||""}))}}function sr(r){return typeof r?.fileType=="string"&&r.fileType.trim()?r.fileType.trim():ul}var Jn={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:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],promptFragment:`## Lark Docs
405
405
  You can read, create, and append Lark/Feishu documents (docx). This reuses the same connected Lark app as messaging.
406
406
  - 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.
407
407
  - larkdoc_create: create a new doc from a title + markdown/text (#/##/### headings, - bullets, 1. ordered supported); returns { ok, documentId, url }. Share the url. To create the doc INSIDE a wiki space, first call larkwiki_list_spaces to find the space id, then pass wikiSpaceId (+ optional parentNodeToken to nest under a wiki node) \u2014 the doc is created as a wiki node and the returned url is the wiki link.
@@ -411,14 +411,14 @@ 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=il();return r?{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ue(n),s="";try{s=(await H("GET",`/open-apis/docx/v1/documents/${i}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await H("GET",`/open-apis/docx/v1/documents/${i}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>jn&&(c=c.slice(0,jn),d=!0),JSON.stringify({ok:!0,documentId:i,title:s,url:Qe(a,i),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let n=typeof e?.wikiSpaceId=="string"&&e.wikiSpaceId.trim()?e.wikiSpaceId.trim():null;if(n){let c=typeof e?.parentNodeToken=="string"&&e.parentNodeToken.trim()?e.parentNodeToken.trim():null,{data:d,host:l}=await H("POST",`/open-apis/wiki/v2/spaces/${encodeURIComponent(n)}/nodes`,{obj_type:"docx",node_type:"origin",title:t,...c?{parent_node_token:c}:{}}),p=d?.node||{},u=p.obj_token;if(!u)return JSON.stringify({ok:!1,error:"Lark wiki node create returned no obj_token"});let m=Xe(e);if(m&&m.trim()){let f=nr(m);f.length&&await ir(u,f)}return JSON.stringify({ok:!0,documentId:u,title:t,wikiSpaceId:n,wikiNodeToken:p.node_token||"",url:p.node_token?ll(l,p.node_token):Qe(l,u)})}let{data:i,host:s}=await H("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),o=i?.document?.document_id;if(!o)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let a=Xe(e);if(a&&a.trim()){let c=nr(a);c.length&&await ir(o,c)}return JSON.stringify({ok:!0,documentId:o,title:t,url:Qe(s,o)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=Xe(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Ue(n),o=nr(i);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await ir(s,o);return JSON.stringify({ok:!0,documentId:s,url:Qe(a,s)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let i=await Ue(n),s=e.imagePath.trim(),o=dl(s),a=el(s),d=(await H("POST",`/open-apis/docx/v1/documents/${i}/blocks/${i}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!d)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let l=await pl({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 H("PATCH",`/open-apis/docx/v1/documents/${i}/blocks/${d}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:i,blockId:d,fileToken:l,url:Qe(f,i)})}case"larkwiki_list_spaces":{let t=[],n=null;for(let i=0;i<ol;i++){let s=new URLSearchParams({page_size:String(sl)});n&&s.set("page_token",n);let{data:o}=await H("GET",`/open-apis/wiki/v2/spaces?${s.toString()}`),a=Array.isArray(o?.items)?o.items:[];for(let c of a)t.push({spaceId:String(c?.space_id||""),name:String(c?.name||"")});if(!o?.has_more||!o?.page_token)break;n=o.page_token}return JSON.stringify({ok:!0,count:t.length,spaces:t})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ue(n),s=sr(e),o=new URLSearchParams({file_type:s,page_size:String(ml)}),{data:a}=await H("GET",`/open-apis/drive/v1/files/${i}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(hl);return JSON.stringify({ok:!0,documentId:i,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=Xe({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Ue(n),o=sr(e),{data:a}=await H("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:Pn(i)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=e?.commentId||e?.comment_id;if(!i)return JSON.stringify({ok:!1,error:"commentId is required"});let s=Xe({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Ue(n),a=sr(e),{data:c}=await H("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(i)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:Pn(s)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(i),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Pass wikiSpaceId (from larkwiki_list_spaces) to create the doc INSIDE a wiki space instead of as a standalone doc \u2014 optionally nested under parentNodeToken. Returns { ok, documentId, url } (plus wikiNodeToken when created in a wiki) \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root. Ignored when wikiSpaceId is set."},wikiSpaceId:{type:"string",description:"Optional wiki space id (from larkwiki_list_spaces) \u2014 create the doc as a node inside this wiki space."},parentNodeToken:{type:"string",description:"Optional wiki node token to nest the new doc under (only with wikiSpaceId). Absent = the space root."}},required:["title"]}},{name:"larkwiki_list_spaces",description:"List the Lark/Feishu wiki spaces visible to the connected app. Returns { ok, count, spaces:[{ spaceId, name }] }. Use to discover the wikiSpaceId for larkdoc_create.",input_schema:{type:"object",properties:{}}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};var qn={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||[],...D.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return $.serverName;if(process.env.LARK_RECEIVE_ID)return D.serverName;if(process.env.SLACK_BOT_TOKEN)return $.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?$.allowedTools||[]:process.env.LARK_RECEIVE_ID?D.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=il();return r?{type:"stdio",command:"node",args:[r,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(r,e){try{switch(r){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ue(n),s="";try{s=(await H("GET",`/open-apis/docx/v1/documents/${i}`)).data?.document?.title||""}catch{}let{data:o,host:a}=await H("GET",`/open-apis/docx/v1/documents/${i}/raw_content?lang=0`),c=String(o?.content||""),d=!1;return c.length>jn&&(c=c.slice(0,jn),d=!0),JSON.stringify({ok:!0,documentId:i,title:s,url:Qe(a,i),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let n=typeof e?.wikiSpaceId=="string"&&e.wikiSpaceId.trim()?e.wikiSpaceId.trim():null;if(n){let c=typeof e?.parentNodeToken=="string"&&e.parentNodeToken.trim()?e.parentNodeToken.trim():null,{data:d,host:l}=await H("POST",`/open-apis/wiki/v2/spaces/${encodeURIComponent(n)}/nodes`,{obj_type:"docx",node_type:"origin",title:t,...c?{parent_node_token:c}:{}}),p=d?.node||{},u=p.obj_token;if(!u)return JSON.stringify({ok:!1,error:"Lark wiki node create returned no obj_token"});let m=Xe(e);if(m&&m.trim()){let f=nr(m);f.length&&await ir(u,f)}return JSON.stringify({ok:!0,documentId:u,title:t,wikiSpaceId:n,wikiNodeToken:p.node_token||"",url:p.node_token?ll(l,p.node_token):Qe(l,u)})}let{data:i,host:s}=await H("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),o=i?.document?.document_id;if(!o)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let a=Xe(e);if(a&&a.trim()){let c=nr(a);c.length&&await ir(o,c)}return JSON.stringify({ok:!0,documentId:o,title:t,url:Qe(s,o)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=Xe(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let s=await Ue(n),o=nr(i);if(!o.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await ir(s,o);return JSON.stringify({ok:!0,documentId:s,url:Qe(a,s)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let i=await Ue(n),s=e.imagePath.trim(),o=dl(s),a=el(s),d=(await H("POST",`/open-apis/docx/v1/documents/${i}/blocks/${i}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!d)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let l=await pl({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 H("PATCH",`/open-apis/docx/v1/documents/${i}/blocks/${d}?document_revision_id=-1`,{replace_image:p});return JSON.stringify({ok:!0,documentId:i,blockId:d,fileToken:l,url:Qe(f,i)})}case"larkwiki_list_spaces":{let t=[],n=null;for(let i=0;i<ol;i++){let s=new URLSearchParams({page_size:String(sl)});n&&s.set("page_token",n);let{data:o}=await H("GET",`/open-apis/wiki/v2/spaces?${s.toString()}`),a=Array.isArray(o?.items)?o.items:[];for(let c of a)t.push({spaceId:String(c?.space_id||""),name:String(c?.name||"")});if(!o?.has_more||!o?.page_token)break;n=o.page_token}return JSON.stringify({ok:!0,count:t.length,spaces:t})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=await Ue(n),s=sr(e),o=new URLSearchParams({file_type:s,page_size:String(ml)}),{data:a}=await H("GET",`/open-apis/drive/v1/files/${i}/comments?${o.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(hl);return JSON.stringify({ok:!0,documentId:i,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=Xe({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await Ue(n),o=sr(e),{data:a}=await H("POST",`/open-apis/drive/v1/files/${s}/comments?file_type=${encodeURIComponent(o)}`,{reply_list:{replies:[{content:{elements:Pn(i)}}]}});return JSON.stringify({ok:!0,documentId:s,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,n=Se(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let i=e?.commentId||e?.comment_id;if(!i)return JSON.stringify({ok:!1,error:"commentId is required"});let s=Xe({text:e?.text??e?.body});if(!s||!s.trim())return JSON.stringify({ok:!1,error:"text is required"});let o=await Ue(n),a=sr(e),{data:c}=await H("POST",`/open-apis/drive/v1/files/${o}/comments/${encodeURIComponent(i)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:Pn(s)}});return JSON.stringify({ok:!0,documentId:o,commentId:String(i),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Pass wikiSpaceId (from larkwiki_list_spaces) to create the doc INSIDE a wiki space instead of as a standalone doc \u2014 optionally nested under parentNodeToken. Returns { ok, documentId, url } (plus wikiNodeToken when created in a wiki) \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root. Ignored when wikiSpaceId is set."},wikiSpaceId:{type:"string",description:"Optional wiki space id (from larkwiki_list_spaces) \u2014 create the doc as a node inside this wiki space."},parentNodeToken:{type:"string",description:"Optional wiki node token to nest the new doc under (only with wikiSpaceId). Absent = the space root."}},required:["title"]}},{name:"larkwiki_list_spaces",description:"List the Lark/Feishu wiki spaces visible to the connected app. Returns { ok, count, spaces:[{ spaceId, name }] }. Use to discover the wikiSpaceId for larkdoc_create.",input_schema:{type:"object",properties:{}}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};var Bn={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||[],...D.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return $.serverName;if(process.env.LARK_RECEIVE_ID)return D.serverName;if(process.env.SLACK_BOT_TOKEN)return $.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?$.allowedTools||[]:process.env.LARK_RECEIVE_ID?D.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.
418
418
  Where to post:
419
419
  - If SLACK_CHANNEL / LARK_RECEIVE_ID is set, that is the default destination \u2014 use it.
420
420
  - If NO destination env var is set but your instructions name a channel (e.g. "post to #bla"), post to THAT channel \u2014 pass it as the \`channel\` arg (a "#name" or "C0123" id both work).
421
- - If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(r){return process.env.SLACK_CHANNEL&&typeof $.resolve=="function"?$.resolve(r):process.env.LARK_RECEIVE_ID&&typeof D.resolve=="function"?D.resolve(r):process.env.SLACK_BOT_TOKEN&&typeof $.resolve=="function"?$.resolve(r):null},async handleToolCall(r,e,t){return typeof r=="string"&&r.startsWith("slack_")?$.handleToolCall(r,e,t):typeof r=="string"&&r.startsWith("lark_")?D.handleToolCall(r,e,t):JSON.stringify({error:`chat_notify: unknown tool "${r}". Expected slack_* or lark_*.`})},get tools(){return[...$.tools||[],...D.tools||[]]}};import{createRequire as yl}from"module";import{execFileSync as gl}from"child_process";import{join as Bn}from"path";import{existsSync as _l}from"fs";var bl=yl(import.meta.url);function kl(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return bl.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var Dn={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:r}=await import("@zibby/ui-memory");return r()}catch{return null}},promptFragment:`BEFORE executing browser actions:
421
+ - If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(r){return process.env.SLACK_CHANNEL&&typeof $.resolve=="function"?$.resolve(r):process.env.LARK_RECEIVE_ID&&typeof D.resolve=="function"?D.resolve(r):process.env.SLACK_BOT_TOKEN&&typeof $.resolve=="function"?$.resolve(r):null},async handleToolCall(r,e,t){return typeof r=="string"&&r.startsWith("slack_")?$.handleToolCall(r,e,t):typeof r=="string"&&r.startsWith("lark_")?D.handleToolCall(r,e,t):JSON.stringify({error:`chat_notify: unknown tool "${r}". Expected slack_* or lark_*.`})},get tools(){return[...$.tools||[],...D.tools||[]]}};import{createRequire as yl}from"module";import{execFileSync as gl}from"child_process";import{join as qn}from"path";import{existsSync as _l}from"fs";var bl=yl(import.meta.url);function kl(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return bl.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var Dn={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:r}=await import("@zibby/ui-memory");return r()}catch{return null}},promptFragment:`BEFORE executing browser actions:
422
422
  - Review any test memory/history above. Prefer selectors proven to work.
423
423
  - If a previous run failed, avoid the same approach.
424
424
  - After setup/login completes, navigate directly to the target page instead of clicking through menus.
@@ -430,7 +430,7 @@ DURING execution \u2014 when a selector fails and you switch to a fallback:
430
430
  AFTER completing the test, you MUST call memory_save_insight at least once:
431
431
  - Save any useful finding: reliable selectors, timing quirks, navigation patterns, workarounds.
432
432
  - Category: selector_tip | timing | navigation | workaround | flaky | general
433
- - Be specific \u2014 future runs will read your insights.`,resolve(){let r=kl();if(!r)return console.warn("[memory] @zibby/ui-memory not found \u2014 memory tools disabled for this run"),null;let e=Bn(process.cwd(),".zibby","memory");if(!_l(Bn(e,".dolt")))return console.warn("[memory] DB/dolt unavailable \u2014 memory tools disabled for this run"),null;try{let t=gl("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:e,encoding:"utf-8",timeout:5e3}),n=JSON.parse(t.trim()).rows||[];if(!n[0]||n[0].cnt===0)return console.log("[memory] Database empty \u2014 memory tools activate after first completed run"),null}catch(t){return console.warn(`[memory] DB/dolt unavailable \u2014 memory tools disabled for this run (${t.message})`),null}return{command:"node",args:[r,"--db-path",e],description:this.description}},tools:[{name:"memory_get_test_history",description:"Query recent test runs with pass/fail results and timing",input_schema:{type:"object",properties:{specPath:{type:"string",description:"Filter by spec path (substring match)"},limit:{type:"number",description:"Max results (default 10)"}}}},{name:"memory_get_selectors",description:"Query known selectors for a page with stability metrics",input_schema:{type:"object",properties:{pageUrl:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_page_model",description:"Query page structure \u2014 elements, roles, selectors",input_schema:{type:"object",properties:{url:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_navigation",description:"Query known page-to-page transitions",input_schema:{type:"object",properties:{fromUrl:{type:"string",description:"Filter by source URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_save_insight",description:"Save a useful observation for future runs (selector tips, timing, workarounds)",input_schema:{type:"object",properties:{category:{type:"string",enum:["selector_tip","timing","navigation","workaround","flaky","general"],description:"Type of insight"},content:{type:"string",description:"The insight text \u2014 be specific and actionable"},specPath:{type:"string",description:"Related spec path"},sessionId:{type:"string",description:"Current session ID"}},required:["category","content"]}}]};import{existsSync as wl,readFileSync as Sl}from"fs";import{homedir as Il}from"os";import{join as vl}from"path";import{spawn as Nl}from"child_process";var Ie={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
433
+ - Be specific \u2014 future runs will read your insights.`,resolve(){let r=kl();if(!r)return console.warn("[memory] @zibby/ui-memory not found \u2014 memory tools disabled for this run"),null;let e=qn(process.cwd(),".zibby","memory");if(!_l(qn(e,".dolt")))return console.warn("[memory] DB/dolt unavailable \u2014 memory tools disabled for this run"),null;try{let t=gl("dolt",["sql","-q","SELECT COUNT(*) AS cnt FROM test_runs","-r","json"],{cwd:e,encoding:"utf-8",timeout:5e3}),n=JSON.parse(t.trim()).rows||[];if(!n[0]||n[0].cnt===0)return console.log("[memory] Database empty \u2014 memory tools activate after first completed run"),null}catch(t){return console.warn(`[memory] DB/dolt unavailable \u2014 memory tools disabled for this run (${t.message})`),null}return{command:"node",args:[r,"--db-path",e],description:this.description}},tools:[{name:"memory_get_test_history",description:"Query recent test runs with pass/fail results and timing",input_schema:{type:"object",properties:{specPath:{type:"string",description:"Filter by spec path (substring match)"},limit:{type:"number",description:"Max results (default 10)"}}}},{name:"memory_get_selectors",description:"Query known selectors for a page with stability metrics",input_schema:{type:"object",properties:{pageUrl:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_page_model",description:"Query page structure \u2014 elements, roles, selectors",input_schema:{type:"object",properties:{url:{type:"string",description:"Filter by page URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_get_navigation",description:"Query known page-to-page transitions",input_schema:{type:"object",properties:{fromUrl:{type:"string",description:"Filter by source URL (substring match)"},limit:{type:"number",description:"Max results (default 20)"}}}},{name:"memory_save_insight",description:"Save a useful observation for future runs (selector tips, timing, workarounds)",input_schema:{type:"object",properties:{category:{type:"string",enum:["selector_tip","timing","navigation","workaround","flaky","general"],description:"Type of insight"},content:{type:"string",description:"The insight text \u2014 be specific and actionable"},specPath:{type:"string",description:"Related spec path"},sessionId:{type:"string",description:"Current session ID"}},required:["category","content"]}}]};import{existsSync as wl,readFileSync as Sl}from"fs";import{homedir as Il}from"os";import{join as vl}from"path";import{spawn as Nl}from"child_process";var Ie={jira:{description:"Jira issue search, details, comments, transitions",integrationProvider:"jira",envKeys:[],setupInstructions:`To connect Jira:
434
434
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
435
435
  2. Click "Connect Jira" and authorize via Atlassian OAuth
436
436
  3. After OAuth completes, ask me to install Jira again`},github:{description:"GitHub issues, PRs, repository management",integrationProvider:"github",envKeys:[],setupInstructions:`To connect GitHub:
@@ -443,7 +443,7 @@ AFTER completing the test, you MUST call memory_save_insight at least once:
443
443
  1. Go to Settings \u2192 Integrations (https://studio.zibby.dev/integrations)
444
444
  2. Click "Connect Sentry" and authorize
445
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 Ol(){let r=["## Available Skills"];for(let[e,t]of Object.entries(Ie)){let n=t.integrationProvider?`integration: ${t.integrationProvider}`:"ready";r.push(`- ${e}: ${t.description} [${n}]`)}return r.push(""),r.push("Use the install_skill / uninstall_skill / list_available_skills tools to manage skills."),r.push(`Zibby third party Integration settings page: ${or()}`),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 Tl(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=vl(Il(),".zibby","config.json");return wl(r)&&JSON.parse(Sl(r,"utf-8")).sessionToken||null}catch{return null}}function Rl(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function or(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function Al(r){try{let e=process.platform;return Nl(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 El(){let r=Tl();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${Rl()}/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 Mn(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 Fn={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:Ie,promptFragment:Ol,tools:[{name:"install_skill",description:"Install a skill into the current chat session so its tools become available",input_schema:{type:"object",properties:{skillId:{type:"string",description:'Skill identifier to install (e.g. "jira", "github", "browser", "memory")'}},required:["skillId"]}},{name:"uninstall_skill",description:"Remove a skill from the current chat session",input_schema:{type:"object",properties:{skillId:{type:"string",description:"Skill identifier to remove"}},required:["skillId"]}},{name:"list_available_skills",description:"List all skills that can be installed, with their env-var readiness status",input_schema:{type:"object",properties:{}}}],async handleToolCall(r,e,t){let{activeSkills:n}=t,i=await El();if(r==="list_available_skills"){let s=Object.entries(Ie).map(([o,a])=>{let c=n.includes(o),d=Mn(i.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:d.connected,setupInstructions:d.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:s})}if(r==="install_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(n.includes(s)){let l=Ie[s],{getSkill:p}=await import("@zibby/agent-workflow"),m=(p(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?or():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!Ie[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(Ie).join(", ")}`});let o=Ie[s];if(o.integrationProvider){let l=Mn(i.statuses,o.integrationProvider),p=or();if(i.checked&&l.connected===!1){let u=Al(p);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:p,openedBrowser:u,setupInstructions:`Please connect ${o.integrationProvider} first at ${p}. After you finish OAuth, ask me to install ${s} again.`})}}n.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(s)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:d,hint:`${s} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(s==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=n.indexOf(s);return o===-1?JSON.stringify({ok:!1,error:`${s} is not installed`}):(n.splice(o,1),JSON.stringify({ok:!0,uninstalled:s}))}return JSON.stringify({error:`Unknown tool: ${r}`})},resolve(){return null}};import{readFileSync as xl,readdirSync as Ll,statSync as Gn,writeFileSync as jl,mkdirSync as $l}from"fs";import{join as Hn,resolve as Pl,relative as Cl}from"path";import{execSync as zn}from"child_process";var Kn=256*1024,Ul=64*1024,Yn={id:"core-tools",description:"File read/write, directory listing, shell commands, open URLs, wait for async operations",envKeys:[],tools:[{name:"read_file",description:"Read the contents of a file. Returns the text content.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"}},required:["path"]}},{name:"write_file",description:"Write content to a file. Creates parent directories if needed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"},content:{type:"string",description:"Content to write"}},required:["path","content"]}},{name:"list_directory",description:"List files and directories in a path. Returns names with type indicators (/ for dirs).",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory path (relative to cwd or absolute). Defaults to cwd."}}}},{name:"run_command",description:"Run a shell command and return its output. Use for grep, git, npm, etc.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},cwd:{type:"string",description:"Working directory (optional, defaults to project root)"}},required:["command"]}},{name:"open_url",description:"Open a URL in the user's default browser. Use for OAuth flows, documentation, integration setup pages.",input_schema:{type:"object",properties:{url:{type:"string",description:"URL to open"}},required:["url"]}},{name:"wait",description:"Wait for N seconds. Use this for async operations (tests, builds, deploys) \u2014 wait, then check status again.",input_schema:{type:"object",properties:{seconds:{type:"number",description:"Seconds to wait (default: 5, max: 300)"},reason:{type:"string",description:"Why waiting (for logging/clarity)"}}}}],async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"read_file":return Jl(e,n);case"write_file":return ql(e,n);case"list_directory":return Bl(e,n);case"run_command":return Dl(e,n);case"open_url":return Ml(e);case"wait":return await Fl(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function wt(r,e){return Pl(e,r)}function Jl(r,e){let t=wt(r.path,e),n=Gn(t);return n.size>Kn?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${Kn/1024}KB`}):xl(t,"utf-8")}function ql(r,e){let t=wt(r.path,e),n=Hn(t,"..");return $l(n,{recursive:!0}),jl(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:Cl(e,t)})}function Bl(r,e){let t=wt(r.path||".",e);return Ll(t).map(i=>{try{return Gn(Hn(t,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
446
+ `)}function Tl(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=vl(Il(),".zibby","config.json");return wl(r)&&JSON.parse(Sl(r,"utf-8")).sessionToken||null}catch{return null}}function Rl(){return(process.env.ZIBBY_API_URL||process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}function or(){return`${(process.env.ZIBBY_FRONTEND_URL||process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev").replace(/\/$/,"")}/integrations`}function Al(r){try{let e=process.platform;return Nl(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 El(){let r=Tl();if(!r)return{checked:!1,statuses:null,reason:"no-session-token"};try{let e=await fetch(`${Rl()}/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 Mn(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 Fn={id:"skill-installer",description:"Live skill installation for chat sessions",envKeys:[],catalog:Ie,promptFragment:Ol,tools:[{name:"install_skill",description:"Install a skill into the current chat session so its tools become available",input_schema:{type:"object",properties:{skillId:{type:"string",description:'Skill identifier to install (e.g. "jira", "github", "browser", "memory")'}},required:["skillId"]}},{name:"uninstall_skill",description:"Remove a skill from the current chat session",input_schema:{type:"object",properties:{skillId:{type:"string",description:"Skill identifier to remove"}},required:["skillId"]}},{name:"list_available_skills",description:"List all skills that can be installed, with their env-var readiness status",input_schema:{type:"object",properties:{}}}],async handleToolCall(r,e,t){let{activeSkills:n}=t,i=await El();if(r==="list_available_skills"){let s=Object.entries(Ie).map(([o,a])=>{let c=n.includes(o),d=Mn(i.statuses,a.integrationProvider);return{id:o,description:a.description,installed:c,integrationProvider:a.integrationProvider||void 0,integrationConnected:d.connected,setupInstructions:d.connected===!1?a.setupInstructions:void 0}});return JSON.stringify({skills:s})}if(r==="install_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(n.includes(s)){let l=Ie[s],{getSkill:p}=await import("@zibby/agent-workflow"),m=(p(s)?.tools||[]).map(f=>f.name);return JSON.stringify({ok:!0,alreadyInstalled:!0,skillId:s,description:l?.description,availableTools:m,integrationUrl:l?.integrationProvider?or():void 0,hint:`${s} is already active. Tools available: ${m.join(", ")}. Use them directly.`})}if(!Ie[s])return JSON.stringify({ok:!1,error:`Unknown skill "${s}". Available: ${Object.keys(Ie).join(", ")}`});let o=Ie[s];if(o.integrationProvider){let l=Mn(i.statuses,o.integrationProvider),p=or();if(i.checked&&l.connected===!1){let u=Al(p);return JSON.stringify({ok:!1,error:`${o.integrationProvider} is not connected for this Zibby account yet`,needsIntegration:!0,integrationUrl:p,openedBrowser:u,setupInstructions:`Please connect ${o.integrationProvider} first at ${p}. After you finish OAuth, ask me to install ${s} again.`})}}n.push(s);let{getSkill:a}=await import("@zibby/agent-workflow"),d=(a(s)?.tools||[]).map(l=>l.name);return JSON.stringify({ok:!0,installed:s,description:o.description,availableTools:d,hint:`${s} is now active. You now have these tools: ${d.join(", ")}. Use them immediately to help the user \u2014 don't just confirm installation.`})}if(r==="uninstall_skill"){let{skillId:s}=e;if(!s)return JSON.stringify({ok:!1,error:"skillId is required"});if(s==="skill-installer")return JSON.stringify({ok:!1,error:"Cannot uninstall the skill installer"});let o=n.indexOf(s);return o===-1?JSON.stringify({ok:!1,error:`${s} is not installed`}):(n.splice(o,1),JSON.stringify({ok:!0,uninstalled:s}))}return JSON.stringify({error:`Unknown tool: ${r}`})},resolve(){return null}};import{readFileSync as xl,readdirSync as Ll,statSync as Gn,writeFileSync as jl,mkdirSync as $l}from"fs";import{join as Hn,resolve as Pl,relative as Cl}from"path";import{execSync as zn}from"child_process";var Kn=256*1024,Ul=64*1024,Yn={id:"core-tools",description:"File read/write, directory listing, shell commands, open URLs, wait for async operations",envKeys:[],tools:[{name:"read_file",description:"Read the contents of a file. Returns the text content.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"}},required:["path"]}},{name:"write_file",description:"Write content to a file. Creates parent directories if needed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd or absolute)"},content:{type:"string",description:"Content to write"}},required:["path","content"]}},{name:"list_directory",description:"List files and directories in a path. Returns names with type indicators (/ for dirs).",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory path (relative to cwd or absolute). Defaults to cwd."}}}},{name:"run_command",description:"Run a shell command and return its output. Use for grep, git, npm, etc.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},cwd:{type:"string",description:"Working directory (optional, defaults to project root)"}},required:["command"]}},{name:"open_url",description:"Open a URL in the user's default browser. Use for OAuth flows, documentation, integration setup pages.",input_schema:{type:"object",properties:{url:{type:"string",description:"URL to open"}},required:["url"]}},{name:"wait",description:"Wait for N seconds. Use this for async operations (tests, builds, deploys) \u2014 wait, then check status again.",input_schema:{type:"object",properties:{seconds:{type:"number",description:"Seconds to wait (default: 5, max: 300)"},reason:{type:"string",description:"Why waiting (for logging/clarity)"}}}}],async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"read_file":return Jl(e,n);case"write_file":return Bl(e,n);case"list_directory":return ql(e,n);case"run_command":return Dl(e,n);case"open_url":return Ml(e);case"wait":return await Fl(e,t?.options?.signal);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};function wt(r,e){return Pl(e,r)}function Jl(r,e){let t=wt(r.path,e),n=Gn(t);return n.size>Kn?JSON.stringify({error:`File too large (${(n.size/1024).toFixed(0)}KB). Max: ${Kn/1024}KB`}):xl(t,"utf-8")}function Bl(r,e){let t=wt(r.path,e),n=Hn(t,"..");return $l(n,{recursive:!0}),jl(t,r.content,"utf-8"),JSON.stringify({ok:!0,path:Cl(e,t)})}function ql(r,e){let t=wt(r.path||".",e);return Ll(t).map(i=>{try{return Gn(Hn(t,i)).isDirectory()?`${i}/`:i}catch{return i}}).join(`
447
447
  `)}function Dl(r,e){let t=r.cwd?wt(r.cwd,e):e;return zn(r.command,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:Ul,stdio:["pipe","pipe","pipe"]})||"(no output)"}function Ml(r){let{url:e}=r;if(!e||!e.startsWith("http://")&&!e.startsWith("https://"))return JSON.stringify({error:"Invalid URL \u2014 must start with http:// or https://"});let t=process.platform,n=t==="darwin"?"open":t==="win32"?"start":"xdg-open";try{return zn(`${n} "${e}"`,{stdio:"ignore",timeout:5e3}),JSON.stringify({ok:!0,opened:e})}catch{return JSON.stringify({ok:!1,error:`Could not open browser. Please visit: ${e}`})}}async function Fl(r,e){let t=Math.min(Math.max(r.seconds||5,1),300),n=r.reason||"async operation",i=500,s=Date.now()+t*1e3;for(;Date.now()<s;){if(e?.aborted)return JSON.stringify({ok:!0,waited:Math.round((t*1e3-(s-Date.now()))/1e3),reason:n,interrupted:!0});await new Promise(o=>setTimeout(o,Math.min(i,s-Date.now())))}return JSON.stringify({ok:!0,waited:t,reason:n})}import{existsSync as Kl}from"fs";import{fileURLToPath as Gl}from"url";import{dirname as Hl,resolve as zl}from"path";import{resolveIntegrationToken as et}from"@zibby/core/backend-client.js";function Yl(){if(process.env.MCP_SENTRY_PATH)return process.env.MCP_SENTRY_PATH;let r=Hl(Gl(import.meta.url)),e=zl(r,"..","bin","mcp-sentry.mjs");return Kl(e)?e:null}function tt(r){return(r||process.env.SENTRY_URL||"https://sentry.io").trim().replace(/\/+$/,"")}function Wn(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 Zn(r,e={}){let{token:t,organizationSlug:n,baseUrl:i}=await et("sentry"),s=`${tt(i)}/api/0/organizations/${Wn(n)}${r}`,o={method:e.method||"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}};e.body!=null&&(o.body=typeof e.body=="string"?e.body:JSON.stringify(e.body));let a=await fetch(s,o);if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Sentry API ${a.status}: ${c.slice(0,300)}`)}return a.json()}async function Wl(){return Zn("/projects/?per_page=50")}async function Zl({query:r="is:unresolved",sort:e="date",project:t,limit:n=25}={}){let i=`/issues/?query=${encodeURIComponent(r)}&sort=${e}&per_page=${n}`;return t&&(i+=`&project=${encodeURIComponent(t)}`),Zn(i)}async function ar(r){let e=String(r??"").trim();if(!e)throw new Error("resolveSentryIssueId: issueRef is required");if(/^\d+$/.test(e))return e;let{token:t,organizationSlug:n,baseUrl:i}=await et("sentry"),s=await fetch(`${tt(i)}/api/0/organizations/${Wn(n)}/shortids/${encodeURIComponent(e)}/`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Sentry API ${s.status} resolving shortId "${e}": ${c.slice(0,200)}`)}let o=await s.json(),a=o.groupId||o.group&&o.group.id;if(!a)throw new Error(`Sentry shortId "${e}" did not resolve to a numeric issue id`);return String(a)}async function Vl(r){if(!r)throw new Error("sentryGetIssue: issueId is required");let e=await ar(r),{token:t,baseUrl:n}=await et("sentry"),i=await fetch(`${tt(n)}/api/0/issues/${e}/`,{headers:{Authorization:`Bearer ${t}`}});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`Sentry API ${i.status}: ${s.slice(0,300)}`)}return i.json()}async function Ql(r,e={}){if(!r)throw new Error("sentryUpdateIssue: issueId is required");let t={};for(let a of["status","statusDetails","assignedTo","isBookmarked","hasSeen"])e[a]!==void 0&&(t[a]=e[a]);if(Object.keys(t).length===0)throw new Error("sentryUpdateIssue: nothing to update (pass status / statusDetails / assignedTo / isBookmarked / hasSeen)");let n=await ar(r),{token:i,baseUrl:s}=await et("sentry"),o=await fetch(`${tt(s)}/api/0/issues/${n}/`,{method:"PUT",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===403?new Error(`Sentry API 403 updating issue ${r}: ${a.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access to let Zibby resolve/comment on issues.`):new Error(`Sentry API ${o.status} updating issue ${r}: ${a.slice(0,300)}`)}return o.json()}async function Xl(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 ar(r),{token:n,baseUrl:i}=await et("sentry"),s=await fetch(`${tt(i)}/api/0/issues/${t}/comments/`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({text:String(e)})});if(!s.ok){let o=await s.text().catch(()=>"");throw s.status===403?new Error(`Sentry API 403 commenting on issue ${r}: ${o.slice(0,200)}. The connected Sentry integration likely lacks the \`event:write\` scope \u2014 reconnect Sentry with write access.`):new Error(`Sentry API ${s.status} commenting on issue ${r}: ${o.slice(0,300)}`)}return s.json()}var St={id:"sentry",serverName:"sentry",allowedTools:["mcp__sentry__*"],requiresIntegration:N.SENTRY,description:"Sentry error tracking \u2014 projects, issues, events",envKeys:[],tools:[],promptFragment:`## Sentry
448
448
  You have access to the user's Sentry. Use these tools:
449
449
  - sentry_list_projects: List projects in the organization
@@ -614,8 +614,8 @@ ${i}
614
614
 
615
615
  `).trim();return l?(l.length>ti&&(l=`${l.slice(0,ti)}
616
616
 
617
- ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function ud(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function md(r,e,t){let n={...r},i=String(n.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let s=null;if(ri.test(i)&&!i.startsWith("inline:")){let l=await pd(i);l&&(i=l.inlineSpec,n.spec=i,String(n.ticketKey||"").trim()||(n.ticketKey=l.issueKey),s=l.issueKey)}let o=String(n.ticketKey||"").trim();if(o){for(let[l,p]of 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(!i.startsWith("inline:")){let l=ve(e,i);if(!ie(l))return ri.test(i)?JSON.stringify({error:`Invalid run_test spec: "${i}" is an issue id, not a spec.`,reason:"Jira auto-load was attempted but did not return usable text, or Jira is not configured.",doNext:["Confirm the jira skill is active and authenticated.",'Or call tracker tools yourself, then run_test with spec: "inline:" + steps.'],validExample:{spec:"inline:1. Open https://example.com \u2026 2. Verify \u2026",ticketKey:i},invalidExample:{spec:i,ticketKey:i}}):JSON.stringify({error:`Test spec not found: ${i}`,hint:'If this should be issue steps, load the issue with your tracker tools first, then run_test with spec: "inline:" + steps. Otherwise use a real file path.'})}let a=ai(t?.options?.config);if(lr()>=a){let l=li(),p=n.ticketKey||l,u={runId:l,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};M.set(l,u),ye.push({args:{...n,_queuedRunId:l},cwd:e,context:t}),J(p,"\u23F3",`Queued (${lr()}/${a} running, ${ye.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()-cr;c<Qn&&cr>0&&await new Promise(l=>setTimeout(l,Qn-c)),cr=Date.now();let d=ui(n,e,t);return s?ud(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function ui(r,e,t){let{spec:n,ticketKey:i,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||li(),l=n,p=!1;if(n.startsWith("inline:")){p=!0;let A=id(e);Vn(A,{recursive:!0}),l=V(A,`${d}.txt`),ed(l,n.slice(7).trim(),"utf-8")}let u=ve(e,".zibby","output","runs");Vn(u,{recursive:!0});let m=V(u,`${d}.log`),f=rd(m,{flags:"a"}),b=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,g=["test",l];b&&g.push("--agent",b),o&&g.push("--headless"),a&&g.push("--workflow",a),ci&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${g.map(A=>/\s/.test(A)?JSON.stringify(A):A).join(" ")} cwd=${e}`);let _=oi("zibby",g,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),y={runId:d,spec:i?`${i}: ${n}`:n,ticketKey:i||null,specPath:l,logPath:m,isInline:p,pid:_.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=i||d,O="";function z(A){let T=di(A).trim();if(!T)return;if(T.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let x=JSON.parse(T.slice(22));x.phase==="node_begin"?y.currentNode=x.node:x.phase==="node_end"&&(x.node&&!y.completedNodes.includes(x.node)&&y.completedNodes.push(x.node),y.currentNode===x.node&&(y.currentNode=null))}catch{}return}let B=T.match(/Session\s+(\S+)/);if(B&&!y.sessionId&&(y.sessionId=B[1],y.sessionPath=ve(e,pr,dr,y.sessionId)),T.startsWith("\u250C ")||T.startsWith("\u250C ")){let x=T.slice(2).trim();y.currentNode=x,It&&J(k,"\u25B6",`${x}`)}else if(T.startsWith("\u2514 ")||T.startsWith("\u2514 ")){let x=T.slice(2).trim();x.startsWith("done")?(y.currentNode&&!y.completedNodes.includes(y.currentNode)&&y.completedNodes.push(y.currentNode),It&&J(k,"\u2714",`${y.currentNode||"node"} done ${x.replace("done","").trim()}`),y.currentNode=null):x.startsWith("failed")&&(It&&J(k,"\u2718",`${y.currentNode||"node"} failed ${x.replace("failed","").trim()}`),y.currentNode=null)}else T.includes("Workflow completed")&&(y.currentNode=null,It&&J(k,"\u2714",`Workflow completed (${Xn(Date.now()-y.startTime)})`))}function Ee(A){let T=A.toString();y.output+=T,f.write(T),y.output.length>5e4&&(y.output=y.output.slice(-3e4)),O+=T;let B=O.split(`
618
- `);O=B.pop();for(let x of B)z(x)}return _.stdout.on("data",Ee),_.stderr.on("data",A=>{let T=A.toString();y.error+=T,f.write(T),y.error.length>2e4&&(y.error=y.error.slice(-1e4))}),_.on("close",A=>{y.status=A===0?"passed":"failed",y.exitCode=A,y.endTime=Date.now(),O&&z(O),f.end();let T=Xn(Date.now()-y.startTime);if(A===0?J(k,"\u2705",`Passed (${T})`):J(k,"\u274C",`Failed (${T})`),y.isInline)try{td(y.specPath)}catch{}ei()}),_.on("error",A=>{y.status="error",y.error+=`
617
+ ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:r}):null}catch{return null}}function ud(r,e){try{let t=JSON.parse(r);return JSON.stringify({...t,...e})}catch{return r}}async function md(r,e,t){let n={...r},i=String(n.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let s=null;if(ri.test(i)&&!i.startsWith("inline:")){let l=await pd(i);l&&(i=l.inlineSpec,n.spec=i,String(n.ticketKey||"").trim()||(n.ticketKey=l.issueKey),s=l.issueKey)}let o=String(n.ticketKey||"").trim();if(o){for(let[l,p]of 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(!i.startsWith("inline:")){let l=ve(e,i);if(!ie(l))return ri.test(i)?JSON.stringify({error:`Invalid run_test spec: "${i}" is an issue id, not a spec.`,reason:"Jira auto-load was attempted but did not return usable text, or Jira is not configured.",doNext:["Confirm the jira skill is active and authenticated.",'Or call tracker tools yourself, then run_test with spec: "inline:" + steps.'],validExample:{spec:"inline:1. Open https://example.com \u2026 2. Verify \u2026",ticketKey:i},invalidExample:{spec:i,ticketKey:i}}):JSON.stringify({error:`Test spec not found: ${i}`,hint:'If this should be issue steps, load the issue with your tracker tools first, then run_test with spec: "inline:" + steps. Otherwise use a real file path.'})}let a=ai(t?.options?.config);if(lr()>=a){let l=li(),p=n.ticketKey||l,u={runId:l,spec:n.ticketKey?`${n.ticketKey}: ${n.spec}`:n.spec,ticketKey:n.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};M.set(l,u),ye.push({args:{...n,_queuedRunId:l},cwd:e,context:t}),J(p,"\u23F3",`Queued (${lr()}/${a} running, ${ye.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()-cr;c<Qn&&cr>0&&await new Promise(l=>setTimeout(l,Qn-c)),cr=Date.now();let d=ui(n,e,t);return s?ud(d,{resolvedFromJiraIssue:s,message:`Spec was loaded from Jira issue ${s} (description + comments).`}):d}function ui(r,e,t){let{spec:n,ticketKey:i,agent:s,headless:o,workflow:a,_queuedRunId:c}=r,d=c||li(),l=n,p=!1;if(n.startsWith("inline:")){p=!0;let A=id(e);Vn(A,{recursive:!0}),l=V(A,`${d}.txt`),ed(l,n.slice(7).trim(),"utf-8")}let u=ve(e,".zibby","output","runs");Vn(u,{recursive:!0});let m=V(u,`${d}.log`),f=rd(m,{flags:"a"}),b=s&&["assistant","cursor","claude","codex","gemini"].includes(s)?s:null,g=["test",l];b&&g.push("--agent",b),o&&g.push("--headless"),a&&g.push("--workflow",a),ci&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${g.map(A=>/\s/.test(A)?JSON.stringify(A):A).join(" ")} cwd=${e}`);let _=oi("zibby",g,{cwd:e,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),y={runId:d,spec:i?`${i}: ${n}`:n,ticketKey:i||null,specPath:l,logPath:m,isInline:p,pid:_.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},k=i||d,O="";function z(A){let T=di(A).trim();if(!T)return;if(T.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let x=JSON.parse(T.slice(22));x.phase==="node_begin"?y.currentNode=x.node:x.phase==="node_end"&&(x.node&&!y.completedNodes.includes(x.node)&&y.completedNodes.push(x.node),y.currentNode===x.node&&(y.currentNode=null))}catch{}return}let q=T.match(/Session\s+(\S+)/);if(q&&!y.sessionId&&(y.sessionId=q[1],y.sessionPath=ve(e,pr,dr,y.sessionId)),T.startsWith("\u250C ")||T.startsWith("\u250C ")){let x=T.slice(2).trim();y.currentNode=x,It&&J(k,"\u25B6",`${x}`)}else if(T.startsWith("\u2514 ")||T.startsWith("\u2514 ")){let x=T.slice(2).trim();x.startsWith("done")?(y.currentNode&&!y.completedNodes.includes(y.currentNode)&&y.completedNodes.push(y.currentNode),It&&J(k,"\u2714",`${y.currentNode||"node"} done ${x.replace("done","").trim()}`),y.currentNode=null):x.startsWith("failed")&&(It&&J(k,"\u2718",`${y.currentNode||"node"} failed ${x.replace("failed","").trim()}`),y.currentNode=null)}else T.includes("Workflow completed")&&(y.currentNode=null,It&&J(k,"\u2714",`Workflow completed (${Xn(Date.now()-y.startTime)})`))}function Ee(A){let T=A.toString();y.output+=T,f.write(T),y.output.length>5e4&&(y.output=y.output.slice(-3e4)),O+=T;let q=O.split(`
618
+ `);O=q.pop();for(let x of q)z(x)}return _.stdout.on("data",Ee),_.stderr.on("data",A=>{let T=A.toString();y.error+=T,f.write(T),y.error.length>2e4&&(y.error=y.error.slice(-1e4))}),_.on("close",A=>{y.status=A===0?"passed":"failed",y.exitCode=A,y.endTime=Date.now(),O&&z(O),f.end();let T=Xn(Date.now()-y.startTime);if(A===0?J(k,"\u2705",`Passed (${T})`):J(k,"\u274C",`Failed (${T})`),y.isInline)try{td(y.specPath)}catch{}ei()}),_.on("error",A=>{y.status="error",y.error+=`
619
619
  Spawn error: ${A.message}`,J(k,"\u274C",`Spawn error: ${A.message}`),f.end(),ei()}),y._child=_,M.set(d,y),JSON.stringify({runId:d,spec:y.spec,ticketKey:y.ticketKey,status:"running",pid:_.pid,logFile:m})}function ni(r){let e=Math.round(((r.endTime||Date.now())-r.startTime)/1e3),t=r.completedNodes||[],n=r.currentNode||null;if(r.status!=="running")return{elapsed:e,stage:r.status,completedNodes:t,currentNode:null};let i;return n?(i=`Actively executing node "${n}"`,t.length&&(i+=` (completed: ${t.join(", ")})`)):t.length?i=`Between nodes (completed: ${t.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${e}s. This is normal progress \u2014 do not cancel.`,{elapsed:e,stage:"running",currentNode:n,completedNodes:t,progress:i}}function fd(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=ni(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 n=ni(t),i={runId:e,spec:t.spec,ticketKey:t.ticketKey,status:t.status,elapsed:n.elapsed,exitCode:t.exitCode,sessionId:t.sessionId||null};return t.status==="running"?(i.currentNode=n.currentNode,i.completedNodes=n.completedNodes,i.progress=n.progress):(i.outputTail=t.output.slice(-1e3),i.errorTail=t.error.slice(-500)),t.status==="running"&&(i._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(i)}function ii(r,e){if(e.status==="queued"){let t=ye.findIndex(n=>n.args._queuedRunId===r);return t>=0&&ye.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 hd(r){let{runId:e}=r;if(!e)return JSON.stringify({error:"runId is required"});if(e==="all"){let n=[];for(let[i,s]of M.entries())(s.status==="running"||s.status==="queued")&&n.push(ii(i,s));return n.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:n.length,results:n})}let t=M.get(e);return JSON.stringify(t?ii(e,t):{error:`Run not found: ${e}`})}function yd(r,e){let t=M.get(r);if(t?.sessionPath&&ie(t.sessionPath))return t.sessionPath;if(t?.sessionId){let n=ve(e,pr,dr,t.sessionId);if(ie(n))return n}return null}function mi(r,e=""){let t=[];if(!ie(r))return t;for(let n of Ot(r,{withFileTypes:!0})){let i=e?`${e}/${n.name}`:n.name;if(n.isDirectory())t.push(...mi(V(r,n.name),i));else{let s=nd(V(r,n.name));t.push({path:i,size:s.size})}}return t}function si(r){if(!ie(r))return null;try{return JSON.parse(Nt(r,"utf-8"))}catch{return null}}function fi(r,e=2e3){if(!r||!ie(r))return"";try{return Nt(r,"utf-8").slice(-Math.max(200,Number(e)||2e3))}catch{return""}}function gd({run:r,logTail:e,errorTail:t}){let i=`${e||""}
620
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.'}:i.includes("test spec not found")?{...s,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:i.includes("unknown command")&&i.includes("'run'")?{...s,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:i.includes("missing openai_api_key")||i.includes("didn't provide an api key")||i.includes("401")?{...s,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:i.includes("spawn error")||i.includes("enoent")?{...s,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:i.includes("security command failed")||i.includes("security process exited with code: 45")||i.includes("password not found for account")?{...s,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:s}function _d(r,e){let{runId:t,type:n,node:i="execute_live",query:s,tail:o=3e3}=r;if(n==="search"){if(!s)return JSON.stringify({error:'query is required for type="search"'});let c=ve(e,pr,dr);if(!ie(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=s.toLowerCase();for(let p of Ot(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=V(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=V(u,f);if(ie(b))try{let g=Nt(b,"utf-8");if(g.toLowerCase().includes(l)){let _=g.toLowerCase().indexOf(l),y=Math.max(0,_-100),k=Math.min(g.length,_+s.length+100);d.push({sessionId:p.name,artifact:h,snippet:g.slice(y,k)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:s,matches:d,total:d.length})}if(!t)return JSON.stringify({error:"runId is required for this type"});if(n==="log"){let c=M.get(t),d=fi(c?.logPath,o);if(d)return JSON.stringify({runId:t,source:"run-log",totalLength:d.length,tail:d})}let a=yd(t,e);if(!a)return JSON.stringify({error:`No session found for run ${t}. The run may still be starting.`});switch(n){case"list":{let c=mi(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=si(V(a,i,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:i,result:c}:{error:`No result.json found in ${i}`})}case"events":{let c=si(V(a,i,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${i}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=V(a,i,"raw_stream_output.txt");if(!ie(c))return JSON.stringify({error:`No log found in ${i}`});let d=Nt(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${n}. Use: list, result, events, log, search`})}}function bd(r,e){let t=String(r?.runId||"all"),n=Number(r?.tail||2e3),i=t==="all"?[...M.keys()]:[t];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let s=i.map(c=>{let d=M.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=fi(d.logPath,n),p=String(d.error||"").slice(-Math.max(200,n));return{...gd({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 kd(r,e){let t=r?.directory||"test-specs",n=ve(e,t);if(!ie(n))return JSON.stringify({specs:[],directory:t,message:`Directory not found: ${t}`});try{let s=function(o,a){for(let c of Ot(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?s(V(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&i.push(d)}},i=[];return s(n,""),JSON.stringify({specs:i.map(o=>`${t}/${o}`),total:i.length,directory:t})}catch(i){return JSON.stringify({error:i.message})}}function hi(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 yi={...me,id:"git-write",envKeys:[...me.envKeys||[],...je.envKeys||[],...$e.envKeys||[]].filter((r,e,t)=>t.indexOf(r)===e),promptFragment:`${me.promptFragment}
621
621
 
@@ -663,7 +663,7 @@ To MERGE an open PR/MR, use the provider-agnostic tool:
663
663
  )`],gi=new Set;function F(r,e){return wi(vi,e,{...Ni,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 At(r){if(gi.has(r))return!0;if(!_r(ce(r,".dolt"))){if(!Nd())return!1;Si(r,{recursive:!0}),F(r,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${vd.join(`;
664
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 gi.add(r),!0}function Nd(){try{return wi(vi,["version"],{...Ni,timeout:5e3}),!0}catch{return!1}}function S(r){return r==null?"NULL":`'${String(r).replace(/'/g,"''")}'`}function gr(r){return String(r||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function Je(r){return r==="long"?3:r==="mid"?2:r==="short"?1:0}function br(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 Oi(r){let e=new Map;for(let t of r||[]){let n=gr(t.content),i=t.memory_key?`key:${t.memory_key}`:n?`norm:${n}`:"";if(!i)continue;let s=e.get(i);if(!s){e.set(i,t);continue}let o=Je(s.tier),a=Je(t.tier);if(a>o){e.set(i,t);continue}a===o&&Number(t.relevance||0)>Number(s.relevance||0)&&e.set(i,t)}return[...e.values()]}function xt(r,e){let t=String(r??"");return t.length<=e?t:e<=1?t.slice(0,e):`${t.slice(0,e-1)}\u2026`}function rt(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||yr),error:r?.error||null};return t.backend==="mem0"?{...t,recentSessions:[],taskStats:[]}:t}function _i(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(`- ${xt(t.summary,150)}${t.tickets?` [${t.tickets}]`:""}`)}if(r.topMemories?.length>0){e.push("Known facts:");for(let t of r.topMemories.slice(0,10)){let n=t.tier==="long"?"\u2605":"\xB7";e.push(`${n} [${t.category}] ${xt(t.content,120)}`)}}return e.length===0?"":`## Memory Context
665
665
  ${e.join(`
666
- `)}`}function Et(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:xt(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:xt(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function Od(r,e){let t=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(t==="mem0"||t==="dolt")return t;let n=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(n==="mem0"||n==="dolt")return n;if(Tt.has(r))return Tt.get(r);try{let i=ce(r,".zibby.config.mjs");if(_r(i)){let s=await import(nt(i).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return Tt.set(r,o),o}}catch{}return Tt.set(r,yr),yr}function Ti(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${wd(r||process.cwd())}`}var Td="mem0";function Ri(r){let e=ce(r,hr,Td);return{dir:e,vectorDbPath:ce(e,"vectors.db"),historyDbPath:ce(e,"history.db")}}function Rd(r){let e=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!e)return null;let t=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),n=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),i=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),s=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=Ri(r||process.cwd());return{llm:{provider:"openai",config:{model:n,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:s,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function Ai(r){let e=r||process.cwd();if(mr.has(e))return mr.get(e);let t;try{let a=Ii(nt(ce(e,"package.json")).href).resolve("mem0ai/oss");t=await import(nt(a).href)}catch{try{let o=Id.resolve("mem0ai/oss");t=await import(nt(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let n=t?.Memory;if(!n)throw new Error("mem0ai/oss does not export Memory");let i=Rd(e);if(i)try{Si(Ri(e).dir,{recursive:!0})}catch{}let s=i?new n(i):new n;return mr.set(e,s),s}function bi(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||Lt(),memory_key:n?.metadata?.memoryKey||n?.metadata?.memory_key||null,category:n?.metadata?.category||"fact",content:n?.memory||n?.content||"",source:n?.metadata?.source||"mem0",ticket_key:n?.metadata?.ticketKey||n?.metadata?.ticket_key||null,tier:br(n?.metadata?.tier||e,n?.metadata?.category||"fact"),relevance:Number(n?.score??n?.metadata?.relevance??.8),created_at:n?.created_at||n?.metadata?.created_at||Ne()})).filter(n=>String(n.content||"").trim().length>0)}var qe={id:"dolt",store:(r,e)=>xi(r,e),recall:(r,e)=>$d(r,e),brief:(r,e)=>Pd(r,e),endSession:(r,e)=>ji(r,e),logTask:(r,e)=>$i(r,e),taskHistory:(r,e)=>Pi(r,e)},Ad={id:"mem0",store:(r,e,t)=>jd(r,e,t),recall:(r,e,t)=>Li(r,e,t),brief:(r,e,t)=>Cd(r,e,t),endSession:(r,e)=>ji(r,e),logTask:(r,e)=>$i(r,e),taskHistory:(r,e)=>Pi(r,e)},Ed={dolt:qe,mem0:Ad};async function ki(r,e){let t=await Od(r,e);return Ed[t]||qe}var Ei={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
666
+ `)}`}function Et(r){return{backend:r.backend,recentSessions:r.recentSessions.slice(0,3).map(e=>({summary:xt(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:xt(String(e?.content||""),140),source:e?.source||null})),taskStats:r.taskStats,error:r.error||null}}async function Od(r,e){let t=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(t==="mem0"||t==="dolt")return t;let n=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(n==="mem0"||n==="dolt")return n;if(Tt.has(r))return Tt.get(r);try{let i=ce(r,".zibby.config.mjs");if(_r(i)){let s=await import(nt(i).href),o=String(s?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return Tt.set(r,o),o}}catch{}return Tt.set(r,yr),yr}function Ti(r){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${wd(r||process.cwd())}`}var Td="mem0";function Ri(r){let e=ce(r,hr,Td);return{dir:e,vectorDbPath:ce(e,"vectors.db"),historyDbPath:ce(e,"history.db")}}function Rd(r){let e=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!e)return null;let t=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),n=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),i=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),s=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=Ri(r||process.cwd());return{llm:{provider:"openai",config:{model:n,baseURL:e,...t?{apiKey:t}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:s,baseURL:e,...t?{apiKey:t}:{}}},vectorStore:{provider:"memory",config:{dimension:s,dbPath:o}},historyDbPath:a}}async function Ai(r){let e=r||process.cwd();if(mr.has(e))return mr.get(e);let t;try{let a=Ii(nt(ce(e,"package.json")).href).resolve("mem0ai/oss");t=await import(nt(a).href)}catch{try{let o=Id.resolve("mem0ai/oss");t=await import(nt(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let n=t?.Memory;if(!n)throw new Error("mem0ai/oss does not export Memory");let i=Rd(e);if(i)try{Si(Ri(e).dir,{recursive:!0})}catch{}let s=i?new n(i):new n;return mr.set(e,s),s}function bi(r,e="mid"){return(Array.isArray(r)?r:Array.isArray(r?.results)?r.results:[]).map(n=>({id:n?.id||Lt(),memory_key:n?.metadata?.memoryKey||n?.metadata?.memory_key||null,category:n?.metadata?.category||"fact",content:n?.memory||n?.content||"",source:n?.metadata?.source||"mem0",ticket_key:n?.metadata?.ticketKey||n?.metadata?.ticket_key||null,tier:br(n?.metadata?.tier||e,n?.metadata?.category||"fact"),relevance:Number(n?.score??n?.metadata?.relevance??.8),created_at:n?.created_at||n?.metadata?.created_at||Ne()})).filter(n=>String(n.content||"").trim().length>0)}var Be={id:"dolt",store:(r,e)=>xi(r,e),recall:(r,e)=>$d(r,e),brief:(r,e)=>Pd(r,e),endSession:(r,e)=>ji(r,e),logTask:(r,e)=>$i(r,e),taskHistory:(r,e)=>Pi(r,e)},Ad={id:"mem0",store:(r,e,t)=>jd(r,e,t),recall:(r,e,t)=>Li(r,e,t),brief:(r,e,t)=>Cd(r,e,t),endSession:(r,e)=>ji(r,e),logTask:(r,e)=>$i(r,e),taskHistory:(r,e)=>Pi(r,e)},Ed={dolt:Be,mem0:Ad};async function ki(r,e){let t=await Od(r,e);return Ed[t]||Be}var Ei={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(),n=ce(t,hr),i=await ki(t,r),s=i.id;if(s==="dolt"&&!At(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:rt({backend:s,error:o},s),promptContext:"",debugPreview:Et(rt({backend:s,error:o},s)),error:o}}try{let o=await i.brief(e,n,t),a=JSON.parse(o||"{}"),c=rt({...a,backend:s},s);return{backend:s,brief:c,promptContext:_i(c),debugPreview:Et(c),error:c.error||null}}catch(o){if(s==="mem0"&&i!==qe&&At(n)){if(!Rt){Rt=!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 qe.brief(e,n,t),l=JSON.parse(d||"{}"),p=rt({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:_i(p),debugPreview:Et(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=rt({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:Et(c),error:a}}},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd(),i=ce(n,hr),s=await ki(n,t),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!At(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(r){case"memory_store":return d.store(e,i,n);case"memory_recall":return d.recall(e,i,n);case"memory_brief":return d.brief(e,i,n);case"memory_end_session":return d.endSession(e,i,n);case"task_log":return d.logTask(e,i,n);case"task_history":return d.taskHistory(e,i,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(d){if(o==="mem0"&&s!==qe){if(At(i)){if(!Rt){Rt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
684
- `)}catch{}}try{return await c(qe)}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 xi(r,e){let{content:t,category:n,source:i,ticketKey:s,tier:o,memoryKey:a}=r;if(!t||!n)return JSON.stringify({error:"content and category are required"});let c=gr(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=br(o,n),l=d==="long"?1:d==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let g=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(),n=ce(t,hr),i=await ki(t,r),s=i.id;if(s==="dolt"&&!At(n)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:s,brief:rt({backend:s,error:o},s),promptContext:"",debugPreview:Et(rt({backend:s,error:o},s)),error:o}}try{let o=await i.brief(e,n,t),a=JSON.parse(o||"{}"),c=rt({...a,backend:s},s);return{backend:s,brief:c,promptContext:_i(c),debugPreview:Et(c),error:c.error||null}}catch(o){if(s==="mem0"&&i!==Be&&At(n)){if(!Rt){Rt=!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 Be.brief(e,n,t),l=JSON.parse(d||"{}"),p=rt({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:_i(p),debugPreview:Et(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=rt({backend:s,error:a},s);return{backend:s,brief:c,promptContext:"",debugPreview:Et(c),error:a}}},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd(),i=ce(n,hr),s=await ki(n,t),o=s.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(r))&&!At(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(r){case"memory_store":return d.store(e,i,n);case"memory_recall":return d.recall(e,i,n);case"memory_brief":return d.brief(e,i,n);case"memory_end_session":return d.endSession(e,i,n);case"task_log":return d.logTask(e,i,n);case"task_history":return d.taskHistory(e,i,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}};try{return await c(s)}catch(d){if(o==="mem0"&&s!==Be){if(At(i)){if(!Rt){Rt=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
684
+ `)}catch{}}try{return await c(Be)}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 xi(r,e){let{content:t,category:n,source:i,ticketKey:s,tier:o,memoryKey:a}=r;if(!t||!n)return JSON.stringify({error:"content and category are required"});let c=gr(t);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=br(o,n),l=d==="long"?1:d==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let g=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
@@ -712,7 +712,7 @@ fact, decision, context, insight, credential, url, error, workaround`,resolve(){
712
712
  VALUES (${S(c)}, ${S(t)}, ${S(n)}, ${i}, ${s}, ${o}, ${S(a)}, ${S(Ne())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))xi({content:d,category:"fact",source:"session_summary",tier:"mid"},e);Ud(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 $i(r,e){let{title:t,type:n,status:i,ticketKey:s,specPath:o,resultSummary:a}=r;if(!t||!n||!i)return JSON.stringify({error:"title, type, and status are required"});let c=Lt(),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(n)}, ${S(t)}, ${S(i)}, ${S(o)}, ${S(d)}, ${S(a)}, ${S(Ne())}, ${S(Ne())})`);try{F(e,["add","."]),F(e,["commit","-m",`task: ${i} \u2014 ${t.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:t,type:n,status:i})}function Pi(r,e){let{ticketKey:t,type:n,status:i,limit:s=20}=r,o=[];t&&o.push(`ticket_key = ${S(t)}`),n&&o.push(`type = ${S(n)}`),i&&o.push(`status = ${S(i)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
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 Ud(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 Jd(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 Ci,readFileSync as qd}from"node:fs";import{homedir as Bd}from"node:os";import{join as Dd,dirname as Md,resolve as Fd}from"node:path";import{fileURLToPath as Kd}from"node:url";function Gd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Md(Kd(import.meta.url)),e=Fd(r,"..","bin","mcp-skill.mjs");return Ci(e)?e:null}function Hd(){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=Dd(Bd(),".zibby","config.json");return Ci(r)&&JSON.parse(qd(r,"utf-8")).sessionToken||null}catch{return null}}function zd(){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 Yd(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function kr(r){return`${Yd()}:${r}`}async function wr(r,e){let t=Hd();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${zd()}/credits/review-memory`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${i.status}): ${s.slice(0,300)}`)}return i.json()}var Ui={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 Ud(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 Jd(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 Ci,readFileSync as Bd}from"node:fs";import{homedir as qd}from"node:os";import{join as Dd,dirname as Md,resolve as Fd}from"node:path";import{fileURLToPath as Kd}from"node:url";function Gd(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Md(Kd(import.meta.url)),e=Fd(r,"..","bin","mcp-skill.mjs");return Ci(e)?e:null}function Hd(){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=Dd(qd(),".zibby","config.json");return Ci(r)&&JSON.parse(Bd(r,"utf-8")).sessionToken||null}catch{return null}}function zd(){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 Yd(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function kr(r){return`${Yd()}:${r}`}async function wr(r,e){let t=Hd();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${zd()}/credits/review-memory`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${i.status}): ${s.slice(0,300)}`)}return i.json()}var Ui={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=Gd();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/kvMemory.js","kvMemorySkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"kv_recall":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});let n=await wr("recall",{scope:kr(t)});return JSON.stringify(n)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let n=await wr("recall-prefix",{scopePrefix:kr(t)});return JSON.stringify(n)}case"kv_store":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});if(typeof e?.content!="string"||e.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let n={scope:kr(t),content:e.content};e.metadata!=null&&(n.metadata=e.metadata);let i=await wr("store",n);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"kv_recall",description:'Recall the value you stored under a plain key (exact match). Your per-agent namespace is added automatically \u2014 pass a plain key like "seen#owner/repo#42".',input_schema:{type:"object",properties:{key:{type:"string",description:'Plain storage key (no namespace prefix needed) \u2014 e.g. "seen#owner/repo#42" or "lastRun".'}},required:["key"]}},{name:"kv_recall_prefix",description:'List your entries whose plain key STARTS WITH a prefix (e.g. "seen#"). Your per-agent namespace is added automatically. Capped at 25.',input_schema:{type:"object",properties:{keyPrefix:{type:"string",description:'Plain key prefix to match (no namespace prefix needed) \u2014 e.g. "seen#".'}},required:["keyPrefix"]}},{name:"kv_store",description:"Store (overwrite) a value under a plain key so a later run of yours can recall it. Your per-agent namespace is added automatically.",input_schema:{type:"object",properties:{key:{type:"string",description:"Plain storage key (no namespace prefix needed). Same key you recall by."},content:{type:"string",description:"The value to persist. Free-form markdown/text."},metadata:{type:"object",description:"Optional structured metadata."}},required:["key","content"]}}]};import{existsSync as qi,readFileSync as Wd}from"node:fs";import{homedir as Zd}from"node:os";import{join as Vd,dirname as Qd,resolve as Xd}from"node:path";import{fileURLToPath as ep}from"node:url";function tp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Qd(ep(import.meta.url)),e=Xd(r,"..","bin","mcp-skill.mjs");return qi(e)?e:null}function Bi(){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=Vd(Zd(),".zibby","config.json");return qi(r)&&JSON.parse(Wd(r,"utf-8")).sessionToken||null}catch{return null}}function Di(){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 Ji(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function rp(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}var Mi={};function Oe(r){let e={...rp(),...Mi},t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function np(r){let e=Bi();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${Di()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let n=await t.text().catch(()=>"");throw new Error(`ensure_store failed (${t.status}): ${n.slice(0,300)}`)}return t.json()}async function le(r,e,t){let n=Bi();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${Di()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${e} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var ip=Math.floor(3.5*1024*1024);async function sp(r,e,t,n){let i=await le(r,"put-url",{path:e,contentType:n});if(!i?.url)throw new Error("put-url did not return an upload URL");let s=await fetch(i.url,{method:i.method||"PUT",headers:i.headers||{"Content-Type":n},body:t});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`direct upload failed (${s.status}): ${o.slice(0,200)}`)}return{ok:!0,path:i.path||e,size:t.length,contentType:i.contentType||n,via:"presign"}}async function op(r,e){let t=await le(r,"get-url",{path:e});if(!t?.url)throw new Error("get-url did not return a download URL");let n=await fetch(t.url,{method:t.method||"GET"});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`direct download failed (${n.status}): ${s.slice(0,200)}`)}let i=await n.arrayBuffer();return{buf:Buffer.from(i),contentType:n.headers.get("content-type")||"application/octet-stream"}}var Fi={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=Gd();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/kvMemory.js","kvMemorySkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"kv_recall":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});let n=await wr("recall",{scope:kr(t)});return JSON.stringify(n)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let n=await wr("recall-prefix",{scopePrefix:kr(t)});return JSON.stringify(n)}case"kv_store":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});if(typeof e?.content!="string"||e.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let n={scope:kr(t),content:e.content};e.metadata!=null&&(n.metadata=e.metadata);let i=await wr("store",n);return JSON.stringify(i)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"kv_recall",description:'Recall the value you stored under a plain key (exact match). Your per-agent namespace is added automatically \u2014 pass a plain key like "seen#owner/repo#42".',input_schema:{type:"object",properties:{key:{type:"string",description:'Plain storage key (no namespace prefix needed) \u2014 e.g. "seen#owner/repo#42" or "lastRun".'}},required:["key"]}},{name:"kv_recall_prefix",description:'List your entries whose plain key STARTS WITH a prefix (e.g. "seen#"). Your per-agent namespace is added automatically. Capped at 25.',input_schema:{type:"object",properties:{keyPrefix:{type:"string",description:'Plain key prefix to match (no namespace prefix needed) \u2014 e.g. "seen#".'}},required:["keyPrefix"]}},{name:"kv_store",description:"Store (overwrite) a value under a plain key so a later run of yours can recall it. Your per-agent namespace is added automatically.",input_schema:{type:"object",properties:{key:{type:"string",description:"Plain storage key (no namespace prefix needed). Same key you recall by."},content:{type:"string",description:"The value to persist. Free-form markdown/text."},metadata:{type:"object",description:"Optional structured metadata."}},required:["key","content"]}}]};import{existsSync as Bi,readFileSync as Wd}from"node:fs";import{homedir as Zd}from"node:os";import{join as Vd,dirname as Qd,resolve as Xd}from"node:path";import{fileURLToPath as ep}from"node:url";function tp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Qd(ep(import.meta.url)),e=Xd(r,"..","bin","mcp-skill.mjs");return Bi(e)?e:null}function qi(){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=Vd(Zd(),".zibby","config.json");return Bi(r)&&JSON.parse(Wd(r,"utf-8")).sessionToken||null}catch{return null}}function Di(){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 Ji(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function rp(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}var Mi={};function Oe(r){let e={...rp(),...Mi},t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function np(r){let e=qi();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let t=await fetch(`${Di()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let n=await t.text().catch(()=>"");throw new Error(`ensure_store failed (${t.status}): ${n.slice(0,300)}`)}return t.json()}async function le(r,e,t){let n=qi();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let i=`${Di()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Store ${e} failed (${s.status}): ${o.slice(0,300)}`)}return s.json()}var ip=Math.floor(3.5*1024*1024);async function sp(r,e,t,n){let i=await le(r,"put-url",{path:e,contentType:n});if(!i?.url)throw new Error("put-url did not return an upload URL");let s=await fetch(i.url,{method:i.method||"PUT",headers:i.headers||{"Content-Type":n},body:t});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`direct upload failed (${s.status}): ${o.slice(0,200)}`)}return{ok:!0,path:i.path||e,size:t.length,contentType:i.contentType||n,via:"presign"}}async function op(r,e){let t=await le(r,"get-url",{path:e});if(!t?.url)throw new Error("get-url did not return a download URL");let n=await fetch(t.url,{method:t.method||"GET"});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`direct download failed (${n.status}): ${s.slice(0,200)}`)}let i=await n.arrayBuffer();return{buf:Buffer.from(i),contentType:n.headers.get("content-type")||"application/octet-stream"}}var Fi={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.
@@ -795,13 +795,13 @@ Tools:
795
795
  To recall WHAT YOU HAVE ALREADY PUBLISHED, use your kv-memory tool
796
796
  kv_recall_prefix with keyPrefix "artifact:" \u2014 each entry is the index record
797
797
  { id, title, url, kind, createdAt, summary } for a page you made. (Publishing
798
- records this automatically; you don't store it yourself.)`,resolve(){let r=fp();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 n=Hi(e);if(!n)return JSON.stringify({error:"provide exactly one of html or markdown (non-empty string)"});let i={title:t,[n.format]:n.content};typeof e?.kind=="string"&&e.kind.trim()&&(i.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(i.favicon=e.favicon.trim());let s=await Ki(i),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:i.kind||null,createdAt:s.createdAt||new Date().toISOString(),summary:typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():t};try{await Gi(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 n=Hi(e),i=typeof e?.title=="string"?e.title.trim():"";if(!n&&!i)return JSON.stringify({error:"nothing to update \u2014 pass a new title and/or html|markdown"});let s={id:t};i&&(s.title=i),n&&(s[n.format]=n.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 Ki(s),a=o?.url;if(!a)return JSON.stringify({error:"artifact update returned no url",response:o});let c=await gp(t)||{},d={...c,id:t,url:a,title:i||c.title||"Untitled",kind:s.kind||c.kind||null,createdAt:c.createdAt||o.createdAt||new Date().toISOString(),updatedAt:o.updatedAt||new Date().toISOString()};typeof e?.summary=="string"&&e.summary.trim()?d.summary=e.summary.trim():d.summary||(d.summary=d.title);try{await Gi(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 n=await yp(t);return JSON.stringify(n)}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 _p}from"node:module";import{existsSync as Xi,mkdirSync as bp,writeFileSync as Zi}from"node:fs";import{dirname as es,join as Be,resolve as ts}from"node:path";import{fileURLToPath as rs}from"node:url";var ns=_p(import.meta.url),Sr=null;function kp(){return Sr||(Sr=ns("echarts")),Sr}var Ir=null;function wp(){return Ir||(Ir=ns("@resvg/resvg-js")),Ir}var Sp=800,Ip=600,vp=4096,Np=16,Vi=60,is="Noto Sans";function Op(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=es(rs(import.meta.url)),e=ts(r,"..","bin","mcp-skill.mjs");return Xi(e)?e:null}function Tp(){let r=es(rs(import.meta.url)),e=ts(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>Be(e,t)).filter(t=>Xi(t))}function Rp(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?Be(e,"chart-render"):Be(process.cwd(),".zibby","output","charts"));return bp(t,{recursive:!0}),t}function Te(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function Qi(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(Np,Math.min(vp,Math.round(t))):e}function vr(r){return typeof r!="string"||r.length<=Vi?r:`${r.slice(0,Vi-1)}\u2026`}function Pt(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=vr(t):Te(t)&&typeof t.name=="string"&&(t.name=vr(t.name))}}function Ap(r){for(let n of["xAxis","yAxis"]){let i=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let s of i)Te(s)&&Pt(s.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of e)Te(n)&&Pt(n.indicator);Te(r.legend)&&Pt(r.legend.data);let t=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of t)Te(n)&&(typeof n.name=="string"&&(n.name=vr(n.name)),Pt(n.data))}function Ep(r){let e=JSON.parse(JSON.stringify(r));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),Te(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=is),Ap(e),e}function xp(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Lp(r,e,t){let i=kp().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return i.setOption(r),i.renderToSVGString()}finally{i.dispose()}}function jp(r){let{Resvg:e}=wp();return new e(r,{font:{fontFiles:Tp(),loadSystemFonts:!0,defaultFontFamily:is}}).render().asPng()}var ss={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)
798
+ records this automatically; you don't store it yourself.)`,resolve(){let r=fp();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 n=Hi(e);if(!n)return JSON.stringify({error:"provide exactly one of html or markdown (non-empty string)"});let i={title:t,[n.format]:n.content};typeof e?.kind=="string"&&e.kind.trim()&&(i.kind=e.kind.trim()),typeof e?.favicon=="string"&&e.favicon.trim()&&(i.favicon=e.favicon.trim());let s=await Ki(i),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:i.kind||null,createdAt:s.createdAt||new Date().toISOString(),summary:typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():t};try{await Gi(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 n=Hi(e),i=typeof e?.title=="string"?e.title.trim():"";if(!n&&!i)return JSON.stringify({error:"nothing to update \u2014 pass a new title and/or html|markdown"});let s={id:t};i&&(s.title=i),n&&(s[n.format]=n.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 Ki(s),a=o?.url;if(!a)return JSON.stringify({error:"artifact update returned no url",response:o});let c=await gp(t)||{},d={...c,id:t,url:a,title:i||c.title||"Untitled",kind:s.kind||c.kind||null,createdAt:c.createdAt||o.createdAt||new Date().toISOString(),updatedAt:o.updatedAt||new Date().toISOString()};typeof e?.summary=="string"&&e.summary.trim()?d.summary=e.summary.trim():d.summary||(d.summary=d.title);try{await Gi(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 n=await yp(t);return JSON.stringify(n)}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 _p}from"node:module";import{existsSync as Xi,mkdirSync as bp,writeFileSync as Zi}from"node:fs";import{dirname as es,join as qe,resolve as ts}from"node:path";import{fileURLToPath as rs}from"node:url";var ns=_p(import.meta.url),Sr=null;function kp(){return Sr||(Sr=ns("echarts")),Sr}var Ir=null;function wp(){return Ir||(Ir=ns("@resvg/resvg-js")),Ir}var Sp=800,Ip=600,vp=4096,Np=16,Vi=60,is="Noto Sans";function Op(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=es(rs(import.meta.url)),e=ts(r,"..","bin","mcp-skill.mjs");return Xi(e)?e:null}function Tp(){let r=es(rs(import.meta.url)),e=ts(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>qe(e,t)).filter(t=>Xi(t))}function Rp(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?qe(e,"chart-render"):qe(process.cwd(),".zibby","output","charts"));return bp(t,{recursive:!0}),t}function Te(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}function Qi(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(Np,Math.min(vp,Math.round(t))):e}function vr(r){return typeof r!="string"||r.length<=Vi?r:`${r.slice(0,Vi-1)}\u2026`}function Pt(r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=r[e];typeof t=="string"?r[e]=vr(t):Te(t)&&typeof t.name=="string"&&(t.name=vr(t.name))}}function Ap(r){for(let n of["xAxis","yAxis"]){let i=Array.isArray(r[n])?r[n]:r[n]?[r[n]]:[];for(let s of i)Te(s)&&Pt(s.data)}let e=Array.isArray(r.radar)?r.radar:r.radar?[r.radar]:[];for(let n of e)Te(n)&&Pt(n.indicator);Te(r.legend)&&Pt(r.legend.data);let t=Array.isArray(r.series)?r.series:r.series?[r.series]:[];for(let n of t)Te(n)&&(typeof n.name=="string"&&(n.name=vr(n.name)),Pt(n.data))}function Ep(r){let e=JSON.parse(JSON.stringify(r));return e.animation=!1,e.backgroundColor==null&&(e.backgroundColor="#fff"),Te(e.textStyle)||(e.textStyle={}),e.textStyle.fontFamily==null&&(e.textStyle.fontFamily=is),Ap(e),e}function xp(r){return typeof r!="string"?null:r.trim().replace(/\.(svg|png)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function Lp(r,e,t){let i=kp().init(null,null,{renderer:"svg",ssr:!0,width:e,height:t});try{return i.setOption(r),i.renderToSVGString()}finally{i.dispose()}}function jp(r){let{Resvg:e}=wp();return new e(r,{font:{fontFiles:Tp(),loadSystemFonts:!0,defaultFontFamily:is}}).render().asPng()}var ss={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)
799
799
  You can render charts LOCALLY with the chart_render tool \u2014 pass a standard
800
800
  Apache ECharts option object as \`spec\` (any chart type: bar, line, pie,
801
801
  radar, scatter, heatmap, \u2026). It renders server-side to SVG/PNG files in the
802
802
  run's output folder (auto-attached to the run as artifacts) and returns the
803
803
  file paths. No browser, no external chart service \u2014 the data never leaves
804
- the machine. Don't set animation (it's forced off). Default 800\xD7600 PNG.`,resolve({sessionPath:r,nodeName:e}={}){let t=Op();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?Be(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/chartRender.js","chartRenderSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="chart_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.spec;if(!Te(t))return JSON.stringify({error:"spec must be a plain ECharts option OBJECT (e.g. { xAxis: {...}, yAxis: {...}, series: [...] }) \u2014 got "+(t===null?"null":Array.isArray(t)?"an array":typeof t)+". Pass the option object itself, not a string or an array."});let n=Qi(e?.width,Sp),i=Qi(e?.height,Ip),s=["svg","png","both"].includes(e?.output)?e.output:"png",o=xp(e?.filename)||`chart-${Date.now()}`,a;try{a=Lp(Ep(t),n,i)}catch(l){return JSON.stringify({error:`Chart render failed: ${l.message}. The spec must be a valid Apache ECharts option (check series[].type, and that xAxis/yAxis/radar match the series type). Fix the spec and retry.`})}if(typeof a!="string"||!a.includes("<svg"))return JSON.stringify({error:"Chart render produced no SVG \u2014 the spec likely describes an empty chart (no series?). Add at least one series and retry."});let c=Rp(),d=[];if(s==="svg"||s==="both"){let l=Be(c,`${o}.svg`);Zi(l,a,"utf-8"),d.push({path:l,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}if(s==="png"||s==="both"){let l;try{l=jp(a)}catch(u){return JSON.stringify({error:`PNG rasterization failed: ${u.message}. Retry with output:'svg' if you only need the vector.`})}let p=Be(c,`${o}.png`);Zi(p,l),d.push({path:p,format:"png",bytes:l.length})}return JSON.stringify({ok:!0,width:n,height:i,files:d})}catch(t){return JSON.stringify({error:`chart_render failed: ${t.message}`})}},tools:[{name:"chart_render",description:'Render a chart LOCALLY (no external service) from a standard Apache ECharts option and save it as SVG/PNG files in the run output folder. Pass the raw ECharts option as `spec` \u2014 every ECharts chart type works (bar, line, pie, radar, scatter, heatmap, \u2026). Returns the written file path(s). animation is forced off; background defaults to white. Bar example: {"xAxis":{"type":"category","data":["Q1","Q2"]},"yAxis":{},"series":[{"type":"bar","data":[12,30]}]}. Radar example: {"legend":{"data":["A","B"]},"radar":{"indicator":[{"name":"speed","max":10},{"name":"cost","max":10},{"name":"quality","max":10}]},"series":[{"type":"radar","data":[{"name":"A","value":[7,4,9]},{"name":"B","value":[5,8,6]}]}]}.',input_schema:{type:"object",properties:{spec:{type:"object",description:"The Apache ECharts option object, passed through as-is (series, xAxis/yAxis, radar, legend, title, \u2026)."},width:{type:"number",description:"Image width in px (default 800, max 4096)."},height:{type:"number",description:"Image height in px (default 600, max 4096)."},output:{type:"string",enum:["svg","png","both"],description:"Which file(s) to write (default 'png')."},filename:{type:"string",description:"Optional file basename (no extension); defaults to chart-<timestamp>."}},required:["spec"]}}]};import{existsSync as $p}from"fs";import{fileURLToPath as Pp}from"url";import{dirname as Cp,resolve as Up}from"path";function Jp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Cp(Pp(import.meta.url)),e=Up(r,"..","bin","mcp-skill.mjs");return $p(e)?e:null}var qp=[{name:"trivial",max:5},{name:"small",max:30},{name:"medium",max:150},{name:"large",max:600},{name:"huge",max:1/0}];function Bp(r,e){let t=(Number(r)||0)+(Number(e)||0);for(let n of qp)if(t<=n.max)return n.name;return"huge"}function Dp(r){let t=String(r||"").toLowerCase().split("/").pop()||"",n=t.match(/\.(test|spec)\.[a-z0-9]+$/);if(n)return`.${n[1]}`;let i=t.lastIndexOf(".");return i<=0?/^(dockerfile|makefile|jenkinsfile|procfile|gemfile|rakefile)$/i.test(t)?t.toLowerCase():"":t.slice(i)}var Mp={code:[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".rb",".php",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".scala",".m",".dart",".ex",".exs",".clj",".sh",".bash"],test:[".test",".spec"],docs:[".md",".mdx",".rst",".txt",".adoc"],config:[".json",".yml",".yaml",".toml",".ini",".env",".cfg",".conf",".lock",".xml",".properties","dockerfile","makefile","jenkinsfile","procfile",".tf",".gradle"],style:[".css",".scss",".sass",".less",".styl"],data:[".csv",".tsv",".sql",".parquet",".proto",".graphql",".gql"]},Fp=(()=>{let r={};for(let[e,t]of Object.entries(Mp))for(let n of t)r[n]=e;return r})();function Kp(r){return Fp[String(r||"").toLowerCase()]||"other"}function Gp(r,e={}){let t=Array.isArray(r)?r:[],n=[],i={},s={code:0,test:0,docs:0,config:0,style:0,data:0,other:0},o=0,a=0,c={path:"",changed:-1};for(let m of t){if(!m||typeof m!="object")continue;let f=String(m.path||m.newPath||m.filename||m.new_path||"").trim();if(!f)continue;n.push(f);let h=Number(m.additions??m.add??0)||0,b=Number(m.deletions??m.del??0)||0;o+=h,a+=b;let g=Dp(f);i[g||"(none)"]=(i[g||"(none)"]||0)+1,s[Kp(g)]+=1;let _=h+b;_>c.changed&&(c={path:f,changed:_})}let d=Number(e.additions),l=Number(e.deletions),p=Number.isFinite(d)?d:o,u=Number.isFinite(l)?l:a;return{filesChanged:n.length,filePaths:n,extCounts:i,kindCounts:s,additions:p,deletions:u,sizeBucket:Bp(p,u),largestFile:c.path||null,dirs:[...new Set(n.map(m=>m.includes("/")?m.split("/")[0]:"(root)"))].sort()}}function Hp(r){let e="",t=String(r||"");for(let n=0;n<t.length;n++){let i=t[n];i==="*"?t[n+1]==="*"?(e+=".*",n++,t[n+1]==="/"&&n++):e+="[^/]*":i==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(i)?e+=`\\${i}`:e+=i}return new RegExp(`^${e}$`)}function zp(r,e){let t=Array.isArray(r)?r.map(String):[],n=(Array.isArray(e)?e:[]).filter(Boolean).map(Hp);if(!n.length)return{total:t.length,hits:0,ratio:0,matched:[]};let i=t.filter(s=>n.some(o=>o.test(s)));return{total:t.length,hits:i.length,ratio:t.length?Number((i.length/t.length).toFixed(4)):0,matched:i}}function Yp(r,e){let t=(Array.isArray(r)?r:[]).map(Number).filter(s=>Number.isFinite(s)),n=Number(e);if(!t.length||!Number.isFinite(n))return null;let i=t.filter(s=>s<=n).length;return Number((i/t.length*100).toFixed(1))}var os={id:"code-stats",serverName:"code_stats",allowedTools:["mcp__code_stats__*"],description:"Deterministic code statistics \u2014 pure, reproducible facts from changed-file lists + numbers (extension/work-kind mix, size bucket, core-path glob coverage, percentile rank). Zero LLM, zero network.",promptFragment:`## Code Stats (DETERMINISTIC facts \u2014 pure, reproducible, zero-LLM)
804
+ the machine. Don't set animation (it's forced off). Default 800\xD7600 PNG.`,resolve({sessionPath:r,nodeName:e}={}){let t=Op();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?qe(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/chartRender.js","chartRenderSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="chart_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.spec;if(!Te(t))return JSON.stringify({error:"spec must be a plain ECharts option OBJECT (e.g. { xAxis: {...}, yAxis: {...}, series: [...] }) \u2014 got "+(t===null?"null":Array.isArray(t)?"an array":typeof t)+". Pass the option object itself, not a string or an array."});let n=Qi(e?.width,Sp),i=Qi(e?.height,Ip),s=["svg","png","both"].includes(e?.output)?e.output:"png",o=xp(e?.filename)||`chart-${Date.now()}`,a;try{a=Lp(Ep(t),n,i)}catch(l){return JSON.stringify({error:`Chart render failed: ${l.message}. The spec must be a valid Apache ECharts option (check series[].type, and that xAxis/yAxis/radar match the series type). Fix the spec and retry.`})}if(typeof a!="string"||!a.includes("<svg"))return JSON.stringify({error:"Chart render produced no SVG \u2014 the spec likely describes an empty chart (no series?). Add at least one series and retry."});let c=Rp(),d=[];if(s==="svg"||s==="both"){let l=qe(c,`${o}.svg`);Zi(l,a,"utf-8"),d.push({path:l,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}if(s==="png"||s==="both"){let l;try{l=jp(a)}catch(u){return JSON.stringify({error:`PNG rasterization failed: ${u.message}. Retry with output:'svg' if you only need the vector.`})}let p=qe(c,`${o}.png`);Zi(p,l),d.push({path:p,format:"png",bytes:l.length})}return JSON.stringify({ok:!0,width:n,height:i,files:d})}catch(t){return JSON.stringify({error:`chart_render failed: ${t.message}`})}},tools:[{name:"chart_render",description:'Render a chart LOCALLY (no external service) from a standard Apache ECharts option and save it as SVG/PNG files in the run output folder. Pass the raw ECharts option as `spec` \u2014 every ECharts chart type works (bar, line, pie, radar, scatter, heatmap, \u2026). Returns the written file path(s). animation is forced off; background defaults to white. Bar example: {"xAxis":{"type":"category","data":["Q1","Q2"]},"yAxis":{},"series":[{"type":"bar","data":[12,30]}]}. Radar example: {"legend":{"data":["A","B"]},"radar":{"indicator":[{"name":"speed","max":10},{"name":"cost","max":10},{"name":"quality","max":10}]},"series":[{"type":"radar","data":[{"name":"A","value":[7,4,9]},{"name":"B","value":[5,8,6]}]}]}.',input_schema:{type:"object",properties:{spec:{type:"object",description:"The Apache ECharts option object, passed through as-is (series, xAxis/yAxis, radar, legend, title, \u2026)."},width:{type:"number",description:"Image width in px (default 800, max 4096)."},height:{type:"number",description:"Image height in px (default 600, max 4096)."},output:{type:"string",enum:["svg","png","both"],description:"Which file(s) to write (default 'png')."},filename:{type:"string",description:"Optional file basename (no extension); defaults to chart-<timestamp>."}},required:["spec"]}}]};import{existsSync as $p}from"fs";import{fileURLToPath as Pp}from"url";import{dirname as Cp,resolve as Up}from"path";function Jp(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Cp(Pp(import.meta.url)),e=Up(r,"..","bin","mcp-skill.mjs");return $p(e)?e:null}var Bp=[{name:"trivial",max:5},{name:"small",max:30},{name:"medium",max:150},{name:"large",max:600},{name:"huge",max:1/0}];function qp(r,e){let t=(Number(r)||0)+(Number(e)||0);for(let n of Bp)if(t<=n.max)return n.name;return"huge"}function Dp(r){let t=String(r||"").toLowerCase().split("/").pop()||"",n=t.match(/\.(test|spec)\.[a-z0-9]+$/);if(n)return`.${n[1]}`;let i=t.lastIndexOf(".");return i<=0?/^(dockerfile|makefile|jenkinsfile|procfile|gemfile|rakefile)$/i.test(t)?t.toLowerCase():"":t.slice(i)}var Mp={code:[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".rb",".php",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".scala",".m",".dart",".ex",".exs",".clj",".sh",".bash"],test:[".test",".spec"],docs:[".md",".mdx",".rst",".txt",".adoc"],config:[".json",".yml",".yaml",".toml",".ini",".env",".cfg",".conf",".lock",".xml",".properties","dockerfile","makefile","jenkinsfile","procfile",".tf",".gradle"],style:[".css",".scss",".sass",".less",".styl"],data:[".csv",".tsv",".sql",".parquet",".proto",".graphql",".gql"]},Fp=(()=>{let r={};for(let[e,t]of Object.entries(Mp))for(let n of t)r[n]=e;return r})();function Kp(r){return Fp[String(r||"").toLowerCase()]||"other"}function Gp(r,e={}){let t=Array.isArray(r)?r:[],n=[],i={},s={code:0,test:0,docs:0,config:0,style:0,data:0,other:0},o=0,a=0,c={path:"",changed:-1};for(let m of t){if(!m||typeof m!="object")continue;let f=String(m.path||m.newPath||m.filename||m.new_path||"").trim();if(!f)continue;n.push(f);let h=Number(m.additions??m.add??0)||0,b=Number(m.deletions??m.del??0)||0;o+=h,a+=b;let g=Dp(f);i[g||"(none)"]=(i[g||"(none)"]||0)+1,s[Kp(g)]+=1;let _=h+b;_>c.changed&&(c={path:f,changed:_})}let d=Number(e.additions),l=Number(e.deletions),p=Number.isFinite(d)?d:o,u=Number.isFinite(l)?l:a;return{filesChanged:n.length,filePaths:n,extCounts:i,kindCounts:s,additions:p,deletions:u,sizeBucket:qp(p,u),largestFile:c.path||null,dirs:[...new Set(n.map(m=>m.includes("/")?m.split("/")[0]:"(root)"))].sort()}}function Hp(r){let e="",t=String(r||"");for(let n=0;n<t.length;n++){let i=t[n];i==="*"?t[n+1]==="*"?(e+=".*",n++,t[n+1]==="/"&&n++):e+="[^/]*":i==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(i)?e+=`\\${i}`:e+=i}return new RegExp(`^${e}$`)}function zp(r,e){let t=Array.isArray(r)?r.map(String):[],n=(Array.isArray(e)?e:[]).filter(Boolean).map(Hp);if(!n.length)return{total:t.length,hits:0,ratio:0,matched:[]};let i=t.filter(s=>n.some(o=>o.test(s)));return{total:t.length,hits:i.length,ratio:t.length?Number((i.length/t.length).toFixed(4)):0,matched:i}}function Yp(r,e){let t=(Array.isArray(r)?r:[]).map(Number).filter(s=>Number.isFinite(s)),n=Number(e);if(!t.length||!Number.isFinite(n))return null;let i=t.filter(s=>s<=n).length;return Number((i/t.length*100).toFixed(1))}var os={id:"code-stats",serverName:"code_stats",allowedTools:["mcp__code_stats__*"],description:"Deterministic code statistics \u2014 pure, reproducible facts from changed-file lists + numbers (extension/work-kind mix, size bucket, core-path glob coverage, percentile rank). Zero LLM, zero network.",promptFragment:`## Code Stats (DETERMINISTIC facts \u2014 pure, reproducible, zero-LLM)
805
805
  These tools COMPUTE reproducible facts from data you already have. Use them so
806
806
  your numbers are auditable and survive challenge (same input \u2192 same output).
807
807
 
@@ -830,7 +830,7 @@ notify. Post brief milestones so they know it's alive:
830
830
  you have it (provider + chatId); otherwise it resolves from the runtime.
831
831
  Fire-and-forget \u2014 if it can't post, just keep working; never treat a failed
832
832
  progress ping as an error.`,resolve(){let r=Xp();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","SLACK_BOT_TOKEN","SLACK_TEAM_ID","ZIBBY_PROGRESS_PROVIDER","ZIBBY_PROGRESS_CHAT_ID","ZIBBY_PROGRESS_MENTION","SLACK_CHANNEL","LARK_RECEIVE_ID"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/chatProgress.js","chatProgressSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="report_progress")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=String(e?.message||"").trim().slice(0,2e3);if(!t)return JSON.stringify({ok:!1,skipped:"empty message"});let{provider:n,chatId:i,mention:s}=eu(e);if(!n||!i)return JSON.stringify({ok:!1,skipped:"no chat target"});let o=s&&n==="slack"?`<@${s}> ${t}`:t,a;n==="lark"?a=await D.handleToolCall("lark_send_message",{receive_id:i,text:t}):a=await $.handleToolCall("slack_post_message",{channel:i,text:o});let c=null;try{c=JSON.parse(a)}catch{}return c&&c.error?JSON.stringify({ok:!1,skipped:`post failed: ${c.error}`}):JSON.stringify({ok:!0,provider:n,posted:!0})}catch(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 tu}from"node:module";import{existsSync as ps,mkdirSync as ru,writeFileSync as cs}from"node:fs";import{dirname as us,join as Me,resolve as ms}from"node:path";import{fileURLToPath as fs}from"node:url";var nu=tu(import.meta.url),Nr=null;function iu(){return Nr||(Nr=nu("@resvg/resvg-js")),Nr}var hs=1200,su=627,ou=4096,au=320,cu="#3b82f6",Re="Noto Sans",lu=3;function du(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=us(fs(import.meta.url)),e=ms(r,"..","bin","mcp-skill.mjs");return ps(e)?e:null}function pu(){let r=us(fs(import.meta.url)),e=ms(r,"..","assets","fonts");return["NotoSans-Regular.ttf","NotoSans-Bold.ttf"].map(t=>Me(e,t)).filter(t=>ps(t))}function uu(){let r=process.env.ZIBBY_NODE_SESSION_PATH,e=process.env.ZIBBY_SESSION_PATH,t=r||(e?Me(e,"social-card"):Me(process.cwd(),".zibby","output","social-cards"));return ru(t,{recursive:!0}),t}function ls(r,e){let t=Number(r);return Number.isFinite(t)?Math.max(au,Math.min(ou,Math.round(t))):e}function De(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function mu(r){return typeof r!="string"?null:r.trim().replace(/\.(png|svg)$/i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||null}function fu(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 ys(r,e,t){return String(r).length*e*t}function Or(r,e,t,n){let i=String(r).trim().split(/\s+/).filter(Boolean),s=[],o="";for(let a of i){let c=o?`${o} ${a}`:a;o&&ys(c,t,n)>e?(s.push(o),o=a):o=c}return o&&s.push(o),s.length?s:[""]}function hu(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 ds(r,e,t,n,i){let s=(Array.isArray(r)?r:[]).map(b=>String(b??"").trim()).filter(Boolean).slice(0,lu);if(s.length<2)return null;let o=24,a=54,c=26,d=90,l=17,p=s.map(b=>Math.max(96,ys(b,o,.58)+c*2)),u=p.reduce((b,g)=>b+g,0)+d*(s.length-1),m=e-u/2,f=t+a/2,h=[];for(let b=0;b<s.length;b++){let g=p[b];if(h.push(`<rect x="${m.toFixed(1)}" y="${t}" width="${g.toFixed(1)}" height="${a}" rx="${a/2}" fill="${i}" fill-opacity="0.12" stroke="${i}" stroke-opacity="0.55" stroke-width="1.5"/>`,`<text x="${(m+g/2).toFixed(1)}" y="${(f+o*.35).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${o}" font-weight="700" fill="${n.pillText}">${De(s[b])}</text>`),m+=g,b<s.length-1){let _=m,y=m+d,k=(_+y)/2;h.push(`<line x1="${_.toFixed(1)}" y1="${f}" x2="${y.toFixed(1)}" y2="${f}" stroke="${i}" stroke-opacity="0.55" stroke-width="2"/>`,`<circle cx="${k.toFixed(1)}" cy="${f}" r="${l}" fill="${i}"/>`,`<path d="M ${(k-8).toFixed(1)} ${f.toFixed(1)} l 5 5 l 9 -11" fill="none" stroke="${n.checkFg}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`),m=y}}return{svg:h.join(`
833
- `),height:a}}function yu(r){let{width:e,height:t,theme:n,accent:i}=r,s=hu(n),o=e/2,a=Math.round(e*.07),c=e-a*2,d=String(r.headline).trim(),l=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",p=r.subhead?String(r.subhead).trim():"",u=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=e/hs,h=Math.round(22*f),b=Math.round(29*f),g=p?Or(p,c,b,.52):[],_=Math.round(b*1.28),y=4,k=Math.round(26*f),O=Math.round(20*f),z=Math.round(24*f),Ee=Math.round(30*f),A=!!(u||m),T=a,B=A?Math.round(110*f):a,x=t-T-B,_e=ds(r.diagram,o,0,s,i),Mr=(P,pe)=>{let Ke=y+k;return l&&(Ke+=h+O),Ke+=pe.length*Math.round(P*1.16),g.length&&(Ke+=z+g.length*_),_e&&(Ke+=Ee+_e.height),Ke},Kt=[76,66,58,50,44,38].map(P=>Math.round(P*f)),Xs=4,xe=Kt[Kt.length-1],Gt=Or(d,c,xe,.6);for(let P of Kt){let pe=Or(d,c,P,.6);if(pe.length<=Xs&&Mr(P,pe)<=x){xe=P,Gt=pe;break}}let eo=Math.round(xe*1.16),to=Mr(xe,Gt),Y=T+Math.max(0,(x-to)/2),se=[];se.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${s.bg}"/>`);let Fr=Math.round(60*f);se.push(`<rect x="${(o-Fr/2).toFixed(1)}" y="${Y}" width="${Fr}" height="${y}" rx="2" fill="${i}"/>`),Y+=y+k,l&&(se.push(`<text x="${o}" y="${(Y+h*.82).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${i}">${De(l)}</text>`),Y+=h+O);for(let P of Gt)se.push(`<text x="${o}" y="${(Y+xe*.82).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${xe}" font-weight="700" fill="${s.fg}">${De(P)}</text>`),Y+=eo;if(g.length){Y+=z;for(let P of g)se.push(`<text x="${o}" y="${(Y+b*.82).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${b}" font-weight="400" fill="${s.muted}">${De(P)}</text>`),Y+=_}if(_e){Y+=Ee;let P=ds(r.diagram,o,Y,s,i);P&&se.push(P.svg)}if(A){let P=Math.round(24*f),pe=t-Math.round(46*f);m&&se.push(`<text x="${a}" y="${pe}" text-anchor="start" font-family="${Re}" font-size="${P}" font-weight="400" fill="${s.muted}">${De(m)}</text>`),u&&se.push(`<text x="${e-a}" y="${pe}" text-anchor="end" font-family="${Re}" font-size="${P}" font-weight="700" fill="${i}">${De(u)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
833
+ `),height:a}}function yu(r){let{width:e,height:t,theme:n,accent:i}=r,s=hu(n),o=e/2,a=Math.round(e*.07),c=e-a*2,d=String(r.headline).trim(),l=r.eyebrow?String(r.eyebrow).trim().toUpperCase():"",p=r.subhead?String(r.subhead).trim():"",u=r.stat?String(r.stat).trim():"",m=r.footer?String(r.footer).trim():"",f=e/hs,h=Math.round(22*f),b=Math.round(29*f),g=p?Or(p,c,b,.52):[],_=Math.round(b*1.28),y=4,k=Math.round(26*f),O=Math.round(20*f),z=Math.round(24*f),Ee=Math.round(30*f),A=!!(u||m),T=a,q=A?Math.round(110*f):a,x=t-T-q,_e=ds(r.diagram,o,0,s,i),Mr=(P,pe)=>{let Ke=y+k;return l&&(Ke+=h+O),Ke+=pe.length*Math.round(P*1.16),g.length&&(Ke+=z+g.length*_),_e&&(Ke+=Ee+_e.height),Ke},Kt=[76,66,58,50,44,38].map(P=>Math.round(P*f)),Xs=4,xe=Kt[Kt.length-1],Gt=Or(d,c,xe,.6);for(let P of Kt){let pe=Or(d,c,P,.6);if(pe.length<=Xs&&Mr(P,pe)<=x){xe=P,Gt=pe;break}}let eo=Math.round(xe*1.16),to=Mr(xe,Gt),Y=T+Math.max(0,(x-to)/2),se=[];se.push(`<rect x="0" y="0" width="${e}" height="${t}" fill="${s.bg}"/>`);let Fr=Math.round(60*f);se.push(`<rect x="${(o-Fr/2).toFixed(1)}" y="${Y}" width="${Fr}" height="${y}" rx="2" fill="${i}"/>`),Y+=y+k,l&&(se.push(`<text x="${o}" y="${(Y+h*.82).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${h}" font-weight="700" letter-spacing="3" fill="${i}">${De(l)}</text>`),Y+=h+O);for(let P of Gt)se.push(`<text x="${o}" y="${(Y+xe*.82).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${xe}" font-weight="700" fill="${s.fg}">${De(P)}</text>`),Y+=eo;if(g.length){Y+=z;for(let P of g)se.push(`<text x="${o}" y="${(Y+b*.82).toFixed(1)}" text-anchor="middle" font-family="${Re}" font-size="${b}" font-weight="400" fill="${s.muted}">${De(P)}</text>`),Y+=_}if(_e){Y+=Ee;let P=ds(r.diagram,o,Y,s,i);P&&se.push(P.svg)}if(A){let P=Math.round(24*f),pe=t-Math.round(46*f);m&&se.push(`<text x="${a}" y="${pe}" text-anchor="start" font-family="${Re}" font-size="${P}" font-weight="400" fill="${s.muted}">${De(m)}</text>`),u&&se.push(`<text x="${e-a}" y="${pe}" text-anchor="end" font-family="${Re}" font-size="${P}" font-weight="700" fill="${i}">${De(u)}</text>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">
834
834
  ${se.join(`
835
835
  `)}
836
836
  </svg>`}function gu(r){let{Resvg:e}=iu();return new e(r,{font:{fontFiles:pu(),loadSystemFonts:!0,defaultFontFamily:Re}}).render().asPng()}var gs={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)
@@ -847,15 +847,15 @@ fields that capture the ONE key idea of your post:
847
847
  It renders server-side to a PNG in the run's output folder and returns
848
848
  { ok:true, files:[{ path, format:'png', bytes }] }. Pass the returned \`path\` as
849
849
  \`imagePath\` when you draft/publish a LinkedIn post to ATTACH the card as the
850
- post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=du();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?Me(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/socialCard.js","socialCardSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="social_card_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.headline;if(typeof t!="string"||!t.trim())return JSON.stringify({error:"headline (the big bold line) is required and must be a non-empty string."});let n=ls(e?.width,hs),i=ls(e?.height,su),s=e?.theme==="light"?"light":"dark",o=fu(e?.accent,cu),a;try{a=yu({width:n,height:i,theme:s,accent:o,headline:t,eyebrow:e?.eyebrow,subhead:e?.subhead,stat:e?.stat,footer:e?.footer,diagram:e?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=gu(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=uu(),l=mu(e?.filename)||`social-card-${Date.now()}`,p=Me(d,`${l}.png`);cs(p,c);let u=[{path:p,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=Me(d,`${l}.svg`);cs(m,a,"utf-8"),u.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:i,theme:s,files:u})}catch(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 _u}from"node:child_process";import{existsSync as q,readdirSync as ks,statSync as ws,writeFileSync as Rr,mkdirSync as Ar}from"node:fs";import{dirname as Tr,extname as qt,join as C,relative as bu,resolve as Jt}from"node:path";import{tmpdir as Er}from"node:os";import{fileURLToPath as ku}from"node:url";import{SKILL_META as wu}from"@zibby/skill-ids";import{binPath as Su}from"@zibby/bin-oxlint";import{binPath as Iu}from"@zibby/bin-semgrep";function vu(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=Su();if(r&&q(r))return r}catch{}return"oxlint"}function Nu(){if(process.env.SEMGREP_CORE_BIN)return process.env.SEMGREP_CORE_BIN;try{let r=Iu();if(r&&q(r))return r}catch{}return"semgrep-core"}function Ou(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Tr(ku(import.meta.url)),e=Jt(r,"..","bin","mcp-skill.mjs");return q(e)?e:null}var Ss=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),Tu=400,Ru={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"}},Au=[".oxlintrc.json",".oxlintrc","oxlint.json"],Ct=null;function Eu(){if(Ct&&q(Ct))return Ct;try{let r=C(Er(),"zibby-code-scan");Ar(r,{recursive:!0});let e=C(r,"oxlintrc.curated.json");return Rr(e,JSON.stringify(Ru),"utf-8"),Ct=e,e}catch{return null}}var Is={".java":"java",".py":"python",".go":"go",".rb":"ruby",".php":"php"},_s=Object.keys(Is),vs={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(...);"}]}]}]},xu=[".semgrep.yml",".semgrep.yaml","semgrep.yml","semgrep.yaml"],Ut=null;function Lu(){if(Ut&&q(Ut))return Ut;try{let r=C(Er(),"zibby-code-scan");Ar(r,{recursive:!0});let e=C(r,"semgrep.curated.rules.json");return Rr(e,JSON.stringify(vs),"utf-8"),Ut=e,e}catch{return null}}function ju(r){return xu.map(t=>C(r,t)).find(t=>q(t))||Lu()}function $u(r){let e=[];for(let t of Array.isArray(r)?r:[]){if(typeof t!="string"||!t)continue;let n=Is[qt(t).toLowerCase()];if(!n)continue;let i=t.replace(/\\/g,"/");e.push(["CodeTarget",{path:{fpath:i,ppath:`/${i.replace(/^\/+/,"")}`},analyzer:n,products:["sast"]}])}return["Targets",e]}var Pu=0;function Cu(r){let e=$u(r),t=e[1].length,n=C(Er(),"zibby-code-scan");Ar(n,{recursive:!0});let i=C(n,`semgrep.targets.${process.pid}.${Pu++}.json`);return Rr(i,JSON.stringify(e),"utf-8"),{path:i,count:t}}function bs(r){let e=typeof r=="string"?r.toUpperCase():"";return e==="ERROR"?"error":e==="INFO"||e==="INVENTORY"||e==="EXPERIMENT"?"info":"warning"}var Uu=Object.fromEntries(vs.rules.map(r=>[r.id,r.severity]));function Ju(r,e){if(e)return bs(e);let t=Uu[r];return t?bs(t):"warning"}function qu(r){let e=String(r||""),t=e.indexOf("{");if(t<0)return[];let n;try{n=JSON.parse(e.slice(t))}catch{return[]}return(n&&Array.isArray(n.results)?n.results:[]).map(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:Ju(s.check_id,a.severity),rule:s.check_id||"",message:(a.message||"").trim()}}).filter(s=>s&&(s.file||s.message))}function Bu(r,e,t=4e3){let n=new Set(e.map(o=>o.toLowerCase())),i=[r],s=0;for(;i.length;){let o=i.pop(),a;try{a=ks(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(++s>t)return!1;if(c.isDirectory())!Ss.has(c.name)&&!c.name.startsWith(".")&&i.push(C(o,c.name));else if(c.isFile()&&n.has(qt(c.name).toLowerCase()))return!0}}return!1}function Du(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return(Array.isArray(t)?t:t&&Array.isArray(t.diagnostics)?t.diagnostics:[]).map(i=>{if(!i||typeof i!="object")return null;let s=Array.isArray(i.labels)&&i.labels.length?i.labels[0]:null,o=s&&s.span?s.span:null;return{file:i.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:i.severity||"warning",rule:i.code||"",message:i.message||""}}).filter(i=>i&&(i.file||i.message))}function Mu(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.map(n=>n&&typeof n=="object"?{file:n.filename||"",line:n.location&&Number.isFinite(n.location.row)?n.location.row:"",severity:"warning",rule:n.code||"",message:n.message||""}:null).filter(n=>n&&(n.file||n.message)):[]}function Fu(r){let e=String(r||"").trim();if(!e)return[];let t=[];for(let n of e.split(`
851
- `)){let i=n.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{continue}if(!s||typeof s!="object")continue;let o=s.location||{};t.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""})}return t.filter(n=>n.file||n.message)}var Ku=[{id:"oxlint",detect:r=>q(C(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>vu(),args:(r,e={})=>{let t=e.baseDir||".",i=Au.some(o=>q(C(t,o)))?null:Eu();return["--format","json",...i?["--config",i]:[],...r]},parse:Du},{id:"semgrep",detect:r=>Bu(r,_s),langs:_s,bin:()=>Nu(),args:(r,e={})=>{let t=e.baseDir||".",n=ju(t),{path:i}=Cu(r);return[...n?["-rules",n]:[],"-targets",i,"-json"]},parse:qu},{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:Mu},{id:"staticcheck",detect:r=>q(C(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:Fu}];function Gu(r,e,t){let n=[],i=new Set(e.map(o=>o.toLowerCase())),s=[r];for(;s.length&&n.length<t;){let o=s.pop(),a;try{a=ks(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(n.length>=t)break;c.isDirectory()?!Ss.has(c.name)&&!c.name.startsWith(".")&&s.push(C(o,c.name)):c.isFile()&&i.has(qt(c.name).toLowerCase())&&n.push(C(o,c.name))}}return n}function Hu(r,e,t){let n=t.map(a=>bu(e,a)).filter(Boolean);if(!n.length)return{scanner:r.id,skipped:"no matching files"};let i=r.bin(),s=_u(i,r.args(n,{baseDir:e}),{cwd:e,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(s.error){let a=s.error.code==="ENOENT"?`binary not installed (${i})`:String(s.error.message||s.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(s.stdout,s.stderr,s.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:n.length,findings:o}}var Ns={id:"code-scan",serverName:"code_scan",meta:wu["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)
850
+ post image. No browser, no external service \u2014 the data never leaves the machine.`,resolve({sessionPath:r,nodeName:e}={}){let t=du();if(!t)return{command:null,args:[],env:{},description:this.description};let n={},i=r&&e?Me(r,e):null;i&&(n.ZIBBY_NODE_SESSION_PATH=i),r&&(n.ZIBBY_SESSION_PATH=r);for(let s of["ZIBBY_NODE_SESSION_PATH","ZIBBY_SESSION_PATH"])!n[s]&&process.env[s]&&(n[s]=process.env[s]);return{type:"stdio",command:"node",args:[t,"../dist/socialCard.js","socialCardSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){if(r!=="social_card_render")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=e?.headline;if(typeof t!="string"||!t.trim())return JSON.stringify({error:"headline (the big bold line) is required and must be a non-empty string."});let n=ls(e?.width,hs),i=ls(e?.height,su),s=e?.theme==="light"?"light":"dark",o=fu(e?.accent,cu),a;try{a=yu({width:n,height:i,theme:s,accent:o,headline:t,eyebrow:e?.eyebrow,subhead:e?.subhead,stat:e?.stat,footer:e?.footer,diagram:e?.diagram})}catch(m){return JSON.stringify({error:`Card layout failed: ${m.message}`})}let c;try{c=gu(a)}catch(m){return JSON.stringify({error:`PNG rasterization failed: ${m.message}`})}let d=uu(),l=mu(e?.filename)||`social-card-${Date.now()}`,p=Me(d,`${l}.png`);cs(p,c);let u=[{path:p,format:"png",bytes:c.length}];if(e?.output==="both"||e?.output==="svg"){let m=Me(d,`${l}.svg`);cs(m,a,"utf-8"),u.push({path:m,format:"svg",bytes:Buffer.byteLength(a,"utf-8")})}return JSON.stringify({ok:!0,width:n,height:i,theme:s,files:u})}catch(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 _u}from"node:child_process";import{existsSync as B,readdirSync as ks,statSync as ws,writeFileSync as Rr,mkdirSync as Ar}from"node:fs";import{dirname as Tr,extname as Bt,join as C,relative as bu,resolve as Jt}from"node:path";import{tmpdir as Er}from"node:os";import{fileURLToPath as ku}from"node:url";import{SKILL_META as wu}from"@zibby/skill-ids";import{binPath as Su}from"@zibby/bin-oxlint";import{binPath as Iu}from"@zibby/bin-semgrep";function vu(){if(process.env.OXLINT_BIN)return process.env.OXLINT_BIN;try{let r=Su();if(r&&B(r))return r}catch{}return"oxlint"}function Nu(){if(process.env.SEMGREP_CORE_BIN)return process.env.SEMGREP_CORE_BIN;try{let r=Iu();if(r&&B(r))return r}catch{}return"semgrep-core"}function Ou(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Tr(ku(import.meta.url)),e=Jt(r,"..","bin","mcp-skill.mjs");return B(e)?e:null}var Ss=new Set(["node_modules",".git","dist","build","out","vendor","target",".venv","venv","__pycache__",".next",".turbo","coverage",".zibby"]),Tu=400,Ru={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"}},Au=[".oxlintrc.json",".oxlintrc","oxlint.json"],Ct=null;function Eu(){if(Ct&&B(Ct))return Ct;try{let r=C(Er(),"zibby-code-scan");Ar(r,{recursive:!0});let e=C(r,"oxlintrc.curated.json");return Rr(e,JSON.stringify(Ru),"utf-8"),Ct=e,e}catch{return null}}var Is={".java":"java",".py":"python",".go":"go",".rb":"ruby",".php":"php"},_s=Object.keys(Is),vs={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(...);"}]}]}]},xu=[".semgrep.yml",".semgrep.yaml","semgrep.yml","semgrep.yaml"],Ut=null;function Lu(){if(Ut&&B(Ut))return Ut;try{let r=C(Er(),"zibby-code-scan");Ar(r,{recursive:!0});let e=C(r,"semgrep.curated.rules.json");return Rr(e,JSON.stringify(vs),"utf-8"),Ut=e,e}catch{return null}}function ju(r){return xu.map(t=>C(r,t)).find(t=>B(t))||Lu()}function $u(r){let e=[];for(let t of Array.isArray(r)?r:[]){if(typeof t!="string"||!t)continue;let n=Is[Bt(t).toLowerCase()];if(!n)continue;let i=t.replace(/\\/g,"/");e.push(["CodeTarget",{path:{fpath:i,ppath:`/${i.replace(/^\/+/,"")}`},analyzer:n,products:["sast"]}])}return["Targets",e]}var Pu=0;function Cu(r){let e=$u(r),t=e[1].length,n=C(Er(),"zibby-code-scan");Ar(n,{recursive:!0});let i=C(n,`semgrep.targets.${process.pid}.${Pu++}.json`);return Rr(i,JSON.stringify(e),"utf-8"),{path:i,count:t}}function bs(r){let e=typeof r=="string"?r.toUpperCase():"";return e==="ERROR"?"error":e==="INFO"||e==="INVENTORY"||e==="EXPERIMENT"?"info":"warning"}var Uu=Object.fromEntries(vs.rules.map(r=>[r.id,r.severity]));function Ju(r,e){if(e)return bs(e);let t=Uu[r];return t?bs(t):"warning"}function Bu(r){let e=String(r||""),t=e.indexOf("{");if(t<0)return[];let n;try{n=JSON.parse(e.slice(t))}catch{return[]}return(n&&Array.isArray(n.results)?n.results:[]).map(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:Ju(s.check_id,a.severity),rule:s.check_id||"",message:(a.message||"").trim()}}).filter(s=>s&&(s.file||s.message))}function qu(r,e,t=4e3){let n=new Set(e.map(o=>o.toLowerCase())),i=[r],s=0;for(;i.length;){let o=i.pop(),a;try{a=ks(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(++s>t)return!1;if(c.isDirectory())!Ss.has(c.name)&&!c.name.startsWith(".")&&i.push(C(o,c.name));else if(c.isFile()&&n.has(Bt(c.name).toLowerCase()))return!0}}return!1}function Du(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return(Array.isArray(t)?t:t&&Array.isArray(t.diagnostics)?t.diagnostics:[]).map(i=>{if(!i||typeof i!="object")return null;let s=Array.isArray(i.labels)&&i.labels.length?i.labels[0]:null,o=s&&s.span?s.span:null;return{file:i.filename||o&&o.filename||"",line:o&&Number.isFinite(o.line)?o.line:"",severity:i.severity||"warning",rule:i.code||"",message:i.message||""}}).filter(i=>i&&(i.file||i.message))}function Mu(r){let e=String(r||"").trim();if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.map(n=>n&&typeof n=="object"?{file:n.filename||"",line:n.location&&Number.isFinite(n.location.row)?n.location.row:"",severity:"warning",rule:n.code||"",message:n.message||""}:null).filter(n=>n&&(n.file||n.message)):[]}function Fu(r){let e=String(r||"").trim();if(!e)return[];let t=[];for(let n of e.split(`
851
+ `)){let i=n.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{continue}if(!s||typeof s!="object")continue;let o=s.location||{};t.push({file:o.file||"",line:Number.isFinite(o.line)?o.line:"",severity:s.severity||"warning",rule:s.code||"",message:s.message||""})}return t.filter(n=>n.file||n.message)}var Ku=[{id:"oxlint",detect:r=>B(C(r,"package.json")),langs:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bin:()=>vu(),args:(r,e={})=>{let t=e.baseDir||".",i=Au.some(o=>B(C(t,o)))?null:Eu();return["--format","json",...i?["--config",i]:[],...r]},parse:Du},{id:"semgrep",detect:r=>qu(r,_s),langs:_s,bin:()=>Nu(),args:(r,e={})=>{let t=e.baseDir||".",n=ju(t),{path:i}=Cu(r);return[...n?["-rules",n]:[],"-targets",i,"-json"]},parse:Bu},{id:"ruff",detect:r=>B(C(r,"pyproject.toml"))||B(C(r,"requirements.txt"))||B(C(r,"setup.py")),langs:[".py"],bin:()=>process.env.RUFF_BIN||"ruff",args:r=>["check","--output-format","json",...r],parse:Mu},{id:"staticcheck",detect:r=>B(C(r,"go.mod")),langs:[".go"],bin:()=>process.env.STATICCHECK_BIN||"staticcheck",args:r=>["-f","json",...r],parse:Fu}];function Gu(r,e,t){let n=[],i=new Set(e.map(o=>o.toLowerCase())),s=[r];for(;s.length&&n.length<t;){let o=s.pop(),a;try{a=ks(o,{withFileTypes:!0})}catch{continue}for(let c of a){if(n.length>=t)break;c.isDirectory()?!Ss.has(c.name)&&!c.name.startsWith(".")&&s.push(C(o,c.name)):c.isFile()&&i.has(Bt(c.name).toLowerCase())&&n.push(C(o,c.name))}}return n}function Hu(r,e,t){let n=t.map(a=>bu(e,a)).filter(Boolean);if(!n.length)return{scanner:r.id,skipped:"no matching files"};let i=r.bin(),s=_u(i,r.args(n,{baseDir:e}),{cwd:e,encoding:"utf-8",timeout:180*1e3,maxBuffer:32*1024*1024});if(s.error){let a=s.error.code==="ENOENT"?`binary not installed (${i})`:String(s.error.message||s.error);return{scanner:r.id,skipped:a}}let o=[];try{let a=r.parse(s.stdout,s.stderr,s.status);o=Array.isArray(a)?a.filter(Boolean):[]}catch{o=[]}return{scanner:r.id,filesScanned:n.length,findings:o}}var Ns={id:"code-scan",serverName:"code_scan",meta:wu["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)
852
852
  After you've cloned the repo, call \`scan_code\` to get DETERMINISTIC linter
853
853
  findings for WHATEVER stack this repo is \u2014 it auto-detects (JS/TS\u2192oxlint;
854
854
  Java/Python/Go/Ruby/PHP\u2192semgrep) and runs the matching tool. Pass \`files\` (the changed files, ideal for
855
855
  a review) or \`dir\` (a directory to scan). Findings are GROUND-TRUTH CANDIDATES:
856
856
  triage them for THIS change, verify each in context (false positives exist \u2014
857
857
  trace before asserting), fold noise, and turn the real ones into inline
858
- suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=Ou();return r?{type:"stdio",command:"node",args:[r,"../dist/code-scan.js","codeScanSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,e){if(r!=="scan_code")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=Array.isArray(e?.files)?e.files.filter(a=>typeof a=="string"&&a.trim()):null,n;if(e?.dir&&typeof e.dir=="string"?n=Jt(e.dir):t&&t.length?n=zu(t.map(a=>Jt(a))):n=process.cwd(),!q(n)||!ws(n).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${n}`});let i=t?t.map(a=>Jt(n,a)):null,s=[],o=0;for(let a of Ku){let c=!1;try{c=!!a.detect(n)}catch{c=!1}if(!c)continue;let d=new Set(a.langs.map(u=>u.toLowerCase())),l=i?i.filter(u=>d.has(qt(u).toLowerCase())):Gu(n,a.langs,Tu),p=Hu(a,n,l);Array.isArray(p.findings)&&(o+=p.findings.length),s.push(p)}return s.length?JSON.stringify({ok:!0,baseDir:n,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:n,scanners:[],totalFindings:0,note:"No known stack detected (no package.json / pyproject / go.mod \u2026). Review by hand."})}catch(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 zu(r){if(!r.length)return process.cwd();if(r.length===1)return Tr(r[0]);let e=r.map(s=>s.split("/")),t=e[0],n=[];for(let s=0;s<t.length;s++){let o=t[s];if(e.every(a=>a[s]===o))n.push(o);else break}let i=n.join("/");return i&&q(i)&&ws(i).isDirectory()?i:Tr(r[0])}import{dirname as Yu,resolve as Wu}from"path";import{fileURLToPath as Zu}from"url";import{existsSync as Vu}from"fs";function Qu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Yu(Zu(import.meta.url)),e=Wu(r,"..","bin","mcp-skill.mjs");return Vu(e)?e:null}function Xu(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function em(){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 tm={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:[]}},Os={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=Qu();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","PROJECT_ID","WORKFLOW_TYPE","PROGRESS_API_URL","ZIBBY_ACCOUNT_API_URL","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_USER_TOKEN"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/triggerAgent.js","triggerAgentSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e={}){if(r!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${r}`});try{let t=process.env.PROJECT_ID,n=Xu(),i=typeof e.workflowType=="string"&&e.workflowType.trim()?e.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!t)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!n)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!i)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let s=`${em()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(i)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(s,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({input:e.input&&typeof e.input=="object"?e.input:{}}),signal:o.signal})}finally{clearTimeout(a)}let d=await c.text().catch(()=>""),l;try{l=d?JSON.parse(d):{}}catch{l={raw:d}}if(!c.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${c.status})`,detail:l&&(l.error||l.message)||d.slice(0,300)});let p=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:p,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[tm]};import{spawnSync as rm}from"node:child_process";import{existsSync as xr,mkdirSync as Ts,readdirSync as nm,writeFileSync as im}from"node:fs";import{createHash as sm}from"node:crypto";import{join as Bt}from"node:path";import{SKILL_META as om}from"@zibby/skill-ids";function Rs(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function As(){if(process.env.CBM_CACHE_DIR)return process.env.CBM_CACHE_DIR;let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE;return r?Bt(r,".zibby","cbm-cache"):"/tmp/zibby-cbm-cache"}function am(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=Bt(r,".zibby","repos");try{if(xr(e)){let t=nm(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>Bt(e,n.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return null}function cm(r){return sm("sha256").update(r).digest("hex").slice(0,16)}var Es={id:"codebase-memory",serverName:"codebase_memory",meta:om["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)
858
+ suggestions. Don't hand-lint what the tool already covers, and don't re-run it.`,resolve(){let r=Ou();return r?{type:"stdio",command:"node",args:[r,"../dist/code-scan.js","codeScanSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(r,e){if(r!=="scan_code")return JSON.stringify({error:`Unknown tool: ${r}`});try{let t=Array.isArray(e?.files)?e.files.filter(a=>typeof a=="string"&&a.trim()):null,n;if(e?.dir&&typeof e.dir=="string"?n=Jt(e.dir):t&&t.length?n=zu(t.map(a=>Jt(a))):n=process.cwd(),!B(n)||!ws(n).isDirectory())return JSON.stringify({error:`dir does not exist or is not a directory: ${n}`});let i=t?t.map(a=>Jt(n,a)):null,s=[],o=0;for(let a of Ku){let c=!1;try{c=!!a.detect(n)}catch{c=!1}if(!c)continue;let d=new Set(a.langs.map(u=>u.toLowerCase())),l=i?i.filter(u=>d.has(Bt(u).toLowerCase())):Gu(n,a.langs,Tu),p=Hu(a,n,l);Array.isArray(p.findings)&&(o+=p.findings.length),s.push(p)}return s.length?JSON.stringify({ok:!0,baseDir:n,totalFindings:o,scanners:s}):JSON.stringify({ok:!0,baseDir:n,scanners:[],totalFindings:0,note:"No known stack detected (no package.json / pyproject / go.mod \u2026). Review by hand."})}catch(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 zu(r){if(!r.length)return process.cwd();if(r.length===1)return Tr(r[0]);let e=r.map(s=>s.split("/")),t=e[0],n=[];for(let s=0;s<t.length;s++){let o=t[s];if(e.every(a=>a[s]===o))n.push(o);else break}let i=n.join("/");return i&&B(i)&&ws(i).isDirectory()?i:Tr(r[0])}import{dirname as Yu,resolve as Wu}from"path";import{fileURLToPath as Zu}from"url";import{existsSync as Vu}from"fs";function Qu(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Yu(Zu(import.meta.url)),e=Wu(r,"..","bin","mcp-skill.mjs");return Vu(e)?e:null}function Xu(){return process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN||null}function em(){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 tm={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:[]}},Os={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=Qu();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","PROJECT_ID","WORKFLOW_TYPE","PROGRESS_API_URL","ZIBBY_ACCOUNT_API_URL","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_USER_TOKEN"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/triggerAgent.js","triggerAgentSkill"],env:e,description:this.description,alwaysLoad:!1}},async handleToolCall(r,e={}){if(r!=="trigger_agent")return JSON.stringify({ok:!1,error:`unknown tool: ${r}`});try{let t=process.env.PROJECT_ID,n=Xu(),i=typeof e.workflowType=="string"&&e.workflowType.trim()?e.workflowType.trim():(process.env.WORKFLOW_TYPE||"").trim();if(!t)return JSON.stringify({ok:!1,error:"PROJECT_ID not set \u2014 cannot resolve the target project."});if(!n)return JSON.stringify({ok:!1,error:"PROJECT_API_TOKEN not set \u2014 cannot authenticate the trigger."});if(!i)return JSON.stringify({ok:!1,error:"No workflowType given and WORKFLOW_TYPE is unset \u2014 nothing to trigger."});let s=`${em()}/projects/${encodeURIComponent(t)}/workflows/${encodeURIComponent(i)}/trigger`,o=new AbortController,a=setTimeout(()=>o.abort(),2e4),c;try{c=await fetch(s,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({input:e.input&&typeof e.input=="object"?e.input:{}}),signal:o.signal})}finally{clearTimeout(a)}let d=await c.text().catch(()=>""),l;try{l=d?JSON.parse(d):{}}catch{l={raw:d}}if(!c.ok)return JSON.stringify({ok:!1,error:`trigger failed (HTTP ${c.status})`,detail:l&&(l.error||l.message)||d.slice(0,300)});let p=l.executionId||l.execution?.id||l.id||null;return JSON.stringify({ok:!0,workflowType:i,executionId:p,note:"run started (fire-and-forget)"})}catch(t){return JSON.stringify({ok:!1,error:`trigger_agent failed: ${t?.message||String(t)}`})}},tools:[tm]};import{spawnSync as rm}from"node:child_process";import{existsSync as xr,mkdirSync as Ts,readdirSync as nm,writeFileSync as im}from"node:fs";import{createHash as sm}from"node:crypto";import{join as qt}from"node:path";import{SKILL_META as om}from"@zibby/skill-ids";function Rs(){return process.env.CBM_BIN||"/usr/local/bin/codebase-memory-mcp"}function As(){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 am(){let r=process.env.WORKSPACE||process.env.ZIBBY_WORKSPACE||"/workspace",e=qt(r,".zibby","repos");try{if(xr(e)){let t=nm(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>qt(e,n.name));if(t.length===1)return t[0];if(t.length>1)return e}}catch{}return null}function cm(r){return sm("sha256").update(r).digest("hex").slice(0,16)}var Es={id:"codebase-memory",serverName:"codebase_memory",meta:om["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)
859
859
  The checked-out repository is indexed into a queryable code graph + semantic
860
860
  index. Reach for these instead of blindly grepping when you need structure,
861
861
  relationships, or "where does X live / what depends on Y":
@@ -867,7 +867,7 @@ relationships, or "where does X live / what depends on Y":
867
867
  - get_code_snippet / search_code: pull the exact code for a node / text match.
868
868
  - index_status / list_projects: confirm the index is present before querying.
869
869
  The repo is indexed for you at the start of the run; if a query comes back
870
- empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=As();try{Ts(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:Rs(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=am();if(!r)return{};let e=As();try{Ts(e,{recursive:!0})}catch{}let t=Bt(e,`.cbm-indexed-${cm(r)}`);if(xr(t))return{};let n=Rs();if(!xr(n)&&!process.env.CBM_BIN)return{};let i=rm(n,["cli","index_repository",JSON.stringify({repo_path:r})],{env:{...process.env,CBM_CACHE_DIR:e},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{im(t,`${new Date().toISOString()} status=${i.status}
870
+ empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let r=As();try{Ts(r,{recursive:!0})}catch{}let e={CBM_CACHE_DIR:r};return process.env.WORKSPACE&&(e.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:Rs(),args:[],env:e,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let r=am();if(!r)return{};let e=As();try{Ts(e,{recursive:!0})}catch{}let t=qt(e,`.cbm-indexed-${cm(r)}`);if(xr(t))return{};let n=Rs();if(!xr(n)&&!process.env.CBM_BIN)return{};let i=rm(n,["cli","index_repository",JSON.stringify({repo_path:r})],{env:{...process.env,CBM_CACHE_DIR:e},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{im(t,`${new Date().toISOString()} status=${i.status}
871
871
  `)}catch{}}catch{}return{}}};import{existsSync as xs,readFileSync as lm}from"node:fs";import{homedir as dm}from"node:os";import{join as pm,dirname as um,resolve as mm}from"node:path";import{fileURLToPath as fm}from"node:url";import{SKILL_META as hm}from"@zibby/skill-ids";var ym=3e4,Lr=1;function gm(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=um(fm(import.meta.url)),e=mm(r,"..","bin","mcp-skill.mjs");return xs(e)?e:null}function _m(){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=pm(dm(),".zibby","config.json");return xs(r)&&JSON.parse(lm(r,"utf-8")).sessionToken||null}catch{return null}}function bm(){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 km(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}function jr(r){let e=km(),t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no knowledge-base store is bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function $r(r,e,t){let n=_m();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). The knowledge base is only available inside a Zibby run.");let i=`${bm()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s={Authorization:`Bearer ${n}`,"Content-Type":"application/json"},o=JSON.stringify(t),a;for(let c=0;c<=Lr;c++){let d=new AbortController,l=setTimeout(()=>d.abort(),ym);try{let p=await fetch(i,{method:"POST",headers:s,body:o,signal:d.signal}),u=await p.text().catch(()=>"");if(p.status>=500&&c<Lr){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<Lr))break}finally{clearTimeout(l)}}throw a||new Error(`gbrain ${e} request failed`)}var Ls={id:"gbrain",serverName:"gbrain",allowedTools:["mcp__gbrain__*"],meta:hm.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)
872
872
  You have a per-tenant KNOWLEDGE BASE (a Postgres + pgvector "brain"), bound as a
873
873
  \`postgres\`-type store in the "AVAILABLE STORES" block below. Ingested documents
@@ -989,7 +989,7 @@ Call with no arguments to see all available topics.
989
989
  - Workflow names must be kebab-case (e.g., ticket-triage, pr-review).
990
990
  - State flows through: each node's validated output is stored under its name in state (e.g., state.classify_ticket).
991
991
  - Downstream nodes reference upstream outputs in their prompt function (e.g., \\\`\\\${JSON.stringify(state.classify_ticket, null, 2)}\\\`).
992
- - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,Js=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function qs(r){return`${r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function it(r){return`${r.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}Node`}function Om(r){let e=r?.agent;return e?e.provider?e.provider:e.gemini?"gemini":e.codex?"codex":e.claude?"claude":e.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function Tm(r){let e=Cr(r,".zibby.config.mjs");if(!de(e))return{};try{return(await import(e)).default||{}}catch{return{}}}function Rm(){try{let r=Us(vm.resolve("@zibby/core/package.json")),e=E(r,"templates","browser-test-automation"),t=st(E(e,"nodes","preflight.mjs"),"utf-8"),n=st(E(e,"graph.mjs"),"utf-8");return{preflight:t,graph:n}}catch{return null}}var js=Us(Sm(import.meta.url));function Bs(){let r=Cr(js,"..","..","..","docsite","docs");if(de(r))return r;let e=Cr(js,"..","docs");return de(e)?e:null}function $s(){let r=Bs();if(!r)return[];try{let e=(t,n="")=>{let i=[];for(let s of Pr(t)){let o=E(t,s);try{if(Ps(o).isDirectory())i=i.concat(e(o,`${n}${s}/`));else if(s.endsWith(".md")){let a=`${n}${s.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return e(r)}catch{return[]}}function Ds(r){let e=Bs();if(!e)return null;let t=E(e,`${r}.md`);if(!de(t))return null;try{return st(t,"utf-8")}catch{return null}}function Am(r){let e=r.nodes.map(o=>{let a=o.inputFields?.length?`Input fields: ${o.inputFields.join(", ")}`:"Input: receives full state",c=o.outputFields?.length?`Output fields: ${o.outputFields.join(", ")}`:"Output: determined by task",d=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${a}. ${c}.${d?` ${d}`:""}`}).join(`
992
+ - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,Js=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function Bs(r){return`${r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function it(r){return`${r.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}Node`}function Om(r){let e=r?.agent;return e?e.provider?e.provider:e.gemini?"gemini":e.codex?"codex":e.claude?"claude":e.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function Tm(r){let e=Cr(r,".zibby.config.mjs");if(!de(e))return{};try{return(await import(e)).default||{}}catch{return{}}}function Rm(){try{let r=Us(vm.resolve("@zibby/core/package.json")),e=E(r,"templates","browser-test-automation"),t=st(E(e,"nodes","preflight.mjs"),"utf-8"),n=st(E(e,"graph.mjs"),"utf-8");return{preflight:t,graph:n}}catch{return null}}var js=Us(Sm(import.meta.url));function qs(){let r=Cr(js,"..","..","..","docsite","docs");if(de(r))return r;let e=Cr(js,"..","docs");return de(e)?e:null}function $s(){let r=qs();if(!r)return[];try{let e=(t,n="")=>{let i=[];for(let s of Pr(t)){let o=E(t,s);try{if(Ps(o).isDirectory())i=i.concat(e(o,`${n}${s}/`));else if(s.endsWith(".md")){let a=`${n}${s.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return e(r)}catch{return[]}}function Ds(r){let e=qs();if(!e)return null;let t=E(e,`${r}.md`);if(!de(t))return null;try{return st(t,"utf-8")}catch{return null}}function Am(r){let e=r.nodes.map(o=>{let a=o.inputFields?.length?`Input fields: ${o.inputFields.join(", ")}`:"Input: receives full state",c=o.outputFields?.length?`Output fields: ${o.outputFields.join(", ")}`:"Output: determined by task",d=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${a}. ${c}.${d?` ${d}`:""}`}).join(`
993
993
  `),t=r.edges.map(o=>o.condition?`- ${o.from} \u2192 ${o.to} (conditional: ${o.condition})`:`- ${o.from} \u2192 ${o.to}`).join(`
994
994
  `),n=Rm(),i=Ds("custom-workflows"),s="";return n&&(s+=`
995
995
  ## Real working examples from the Zibby framework
@@ -1090,7 +1090,7 @@ export const ${n} = {
1090
1090
  prompt: (state) => \`${a}\`,
1091
1091
  outputSchema: ${i},
1092
1092
  };
1093
- `}}return{nodes:e}}function xm(r,e,t,n){let i=e.toLowerCase(),s=qs(i),o=E(r,".zibby","workflows",i),a=E(o,"nodes");wm(a,{recursive:!0});let c=t.nodes.map(g=>g.name);for(let g of t.nodes){let _=n.nodes?.[g.name]?.code;_&&Fe(E(a,`${g.name.replace(/_/g,"-")}.mjs`),_,"utf-8")}let d=c.map(g=>{let _=it(g),y=g.replace(/_/g,"-");return`export { ${_} } from './${y}.mjs';`});Fe(E(a,"index.mjs"),`${d.join(`
1093
+ `}}return{nodes:e}}function xm(r,e,t,n){let i=e.toLowerCase(),s=Bs(i),o=E(r,".zibby","workflows",i),a=E(o,"nodes");wm(a,{recursive:!0});let c=t.nodes.map(g=>g.name);for(let g of t.nodes){let _=n.nodes?.[g.name]?.code;_&&Fe(E(a,`${g.name.replace(/_/g,"-")}.mjs`),_,"utf-8")}let d=c.map(g=>{let _=it(g),y=g.replace(/_/g,"-");return`export { ${_} } from './${y}.mjs';`});Fe(E(a,"index.mjs"),`${d.join(`
1094
1094
  `)}
1095
1095
  `,"utf-8");let l=c[0],p=c.map(g=>it(g)).join(", "),u=c.map(g=>` graph.addNode('${g}', ${it(g)});`).join(`
1096
1096
  `),m=t.edges.map(g=>g.condition?` graph.addConditionalEdges('${g.from}', (state) => {
@@ -1116,8 +1116,8 @@ ${m}
1116
1116
  }
1117
1117
  }
1118
1118
  `;Fe(E(o,"graph.mjs"),f,"utf-8");let h={name:i,description:t.description||`${s} workflow`,entryClass:s,triggers:{api:!0}};Fe(E(o,"workflow.json"),`${JSON.stringify(h,null,2)}
1119
- `,"utf-8");let b=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(g=>`nodes/${g.replace(/_/g,"-")}.mjs`)];return{workflowDir:Cs(r,o),files:b,className:s,slug:i}}async function Lm(r){let{name:e,description:t,nodes:n,edges:i}=r;if(!e||!Js.test(e.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${e}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!n||n.length===0)return JSON.stringify({error:"At least one node is required."});let s={name:e.toLowerCase(),description:t||`${qs(e.toLowerCase())} workflow`,nodes:n.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:i||[]};if(s.edges.length===0&&s.nodes.length>0){for(let o=0;o<s.nodes.length-1;o++)s.edges.push({from:s.nodes[o].name,to:s.nodes[o+1].name});s.edges.push({from:s.nodes[s.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:s,message:`Workflow "${s.name}" designed with ${s.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:s.nodes.map(o=>o.name),flow:s.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function jm(r,e){let{name:t,spec:n}=r,i=(t||n?.name||"").toLowerCase();if(!i||!Js.test(i))return JSON.stringify({error:`Invalid workflow name "${i}".`});if(!n||!n.nodes||n.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let s=E(e,".zibby","workflows",i);if(de(s))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await Ms(n,e),a=xm(e,i,n,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${i}" created at ${a.workflowDir}/`,nextSteps:[`Test locally: zibby start ${i}`,`Deploy to cloud: zibby deploy ${i} --project <project-id>`,`Tail logs: zibby logs --workflow ${i} --project <project-id>`]})}async function $m(r,e){let{workflowName:t,nodeName:n,description:i,inputFields:s,outputFields:o}=r,a=(t||"").toLowerCase(),c=(n||"").replace(/-/g,"_"),d=E(e,".zibby","workflows",a);if(!de(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:i||`Process ${c}`,inputFields:s||[],outputFields:o||[]}],edges:[]},u=(await Ms(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`;Fe(E(m,f),u,"utf-8");let h=E(m,"index.mjs"),b=it(c),g=`export { ${b} } from './${c.replace(/_/g,"-")}.mjs';
1120
- `,_=de(h)?st(h,"utf-8"):"";return _.includes(b)||Fe(h,_+g,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:b,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Pm(r,e){let{name:t,projectId:n}=r,i=(t||"").toLowerCase();if(!i)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let s=E(e,".zibby","workflows",i);if(!de(s))return JSON.stringify({error:`Workflow "${i}" not found at .zibby/workflows/${i}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${E(e,"packages/cli/bin/zibby.js")}" deploy ${i} --project ${n}`,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:a.trim()})}catch{try{let{execSync:a}=await import("child_process"),c=a(`npx zibby deploy ${i} --project ${n}`,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:c.trim()})}catch(a){return JSON.stringify({error:`Deploy failed: ${a.message}`})}}}function Cm(r){let e=E(r,".zibby","workflows");if(!de(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=Pr(e).filter(i=>{try{return Ps(E(e,i)).isDirectory()}catch{return!1}}).map(i=>{let s=E(e,i,"workflow.json"),o={};try{o=JSON.parse(st(s,"utf-8"))}catch{}let a=E(e,i,"nodes"),c=0;try{c=Pr(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:c,path:Cs(r,E(e,i))}});return JSON.stringify({workflows:n})}var Fs={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:Nm,tools:[{name:"design_workflow",description:"Design a workflow spec (nodes, edges, descriptions) for the user to review before building. Call this after understanding requirements.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name in kebab-case (e.g., ticket-triage)"},description:{type:"string",description:"What the workflow does"},nodes:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Node name in snake_case (e.g., classify_ticket)"},description:{type:"string",description:"What this node does \u2014 be specific about input/output"},inputFields:{type:"array",items:{type:"string"},description:"Key fields this node reads from state"},outputFields:{type:"array",items:{type:"string"},description:"Key fields this node produces"}},required:["name","description"]},description:"Workflow nodes (processing steps)"},edges:{type:"array",items:{type:"object",properties:{from:{type:"string",description:"Source node name"},to:{type:"string",description:'Target node name (or "END")'},condition:{type:"string",description:"JS expression for conditional routing (optional)"}},required:["from","to"]},description:"Edges connecting nodes. If omitted, nodes are wired linearly."}},required:["name","description","nodes"]}},{name:"build_workflow",description:"Generate real workflow code on disk from a design spec. Uses the configured AI agent for high-quality code generation.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name (from design_workflow)"},spec:{type:"object",description:"The full spec object returned by design_workflow",properties:{name:{type:"string"},description:{type:"string"},nodes:{type:"array",items:{type:"object"}},edges:{type:"array",items:{type:"object"}}}}},required:["name","spec"]}},{name:"add_node",description:"Add a new node to an existing workflow. Generates the node file and updates the barrel export.",input_schema:{type:"object",properties:{workflowName:{type:"string",description:"Existing workflow name (kebab-case)"},nodeName:{type:"string",description:"New node name (snake_case)"},description:{type:"string",description:"What this node does"},inputFields:{type:"array",items:{type:"string"},description:"Fields read from state"},outputFields:{type:"array",items:{type:"string"},description:"Fields produced"}},required:["workflowName","nodeName","description"]}},{name:"deploy_workflow",description:"Deploy a workflow to Zibby Cloud. Returns the trigger URL.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name to deploy"},projectId:{type:"string",description:"Target project ID"}},required:["name","projectId"]}},{name:"list_workflows",description:"List all local workflows in .zibby/workflows/.",input_schema:{type:"object",properties:{}}},{name:"explore_framework_docs",description:"Read Zibby framework documentation on demand. Call this before building complex workflows or when you need details on advanced patterns (middleware, conditional routing, skills, deployment, CLI commands).",input_schema:{type:"object",properties:{topic:{type:"string",description:'Doc topic to read (e.g., "workflow", "custom-workflows", "cli-reference", "packages/core", "packages/skills", "integrations/jira"). Call with no topic to list all available docs.'}}}}],async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Lm(e);case"build_workflow":return await jm(e,n);case"add_node":return await $m(e,n);case"deploy_workflow":return await Pm(e,n);case"list_workflows":return Cm(n);case"explore_framework_docs":{let i=(e.topic||"").trim();if(!i){let o=$s();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=Ds(i);if(!s){let o=$s();return JSON.stringify({error:`Doc "${i}" not found.`,available:o})}return JSON.stringify({topic:i,content:s})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};import{resolveIntegrationToken as Um}from"@zibby/core/backend-client.js";var Jr=Object.freeze({id:"openai_billing",requiresIntegration:N.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),qr=Object.freeze({id:"anthropic_billing",requiresIntegration:N.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),Br=Object.freeze({id:"cursor_admin",requiresIntegration:N.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Ks(r){return Math.floor(r/1e3)}function Ur(r){return new Date(r).toISOString().slice(0,10)}function Gs(r){return new Date(r).toISOString()}async function ot(r){let e=await Um(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function Hs({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let n=await ot("openai_billing"),i=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.openai.com/v1/organization/costs?${[`start_time=${Ks(r)}`,`end_time=${Ks(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=Ur((m.start_time||0)*1e3);for(let h of m.results||[])i.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Jm(){let r=await ot("openai_billing"),t=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function zs({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let n=await ot("anthropic_billing"),i=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(Gs(r))}`,`ending_at=${encodeURIComponent(Gs(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])i.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function qm(){let r=await ot("anthropic_billing"),t=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function Ys({startMs:r,endMs:e}){let t=await ot("cursor_admin"),n=Ur(r),i=Ur(e),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${i}`,o=await fetch(s,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${l.slice(0,200)}`)}let a=await o.json(),c=[],d=0;for(let l of a.data||[]){d+=1;let 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 Bm({startMs:r,endMs:e}){let[t,n,i]=await Promise.allSettled([Hs({startMs:r,endMs:e}),zs({startMs:r,endMs:e}),Ys({startMs:r,endMs:e})]),s=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=s(t),a=s(n),c=s(i),d=[{provider:"openai",totalUsd:o.items.reduce((l,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 Dm(r,e){let t=new Map;for(let n of r){let i=e(n);if(!i)continue;let s=t.get(i)||{key:i,totalUsd:0,count:0};s.totalUsd+=n.costUsd||0,s.count+=1,t.set(i,s)}return[...t.values()].sort((n,i)=>i.totalUsd-n.totalUsd)}function Mm(r){if(!r.length)return{mean:0,stddev:0};let e=r.reduce((n,i)=>n+i,0)/r.length,t=r.reduce((n,i)=>n+(i-e)**2,0)/r.length;return{mean:e,stddev:Math.sqrt(t)}}import{SKILL_IDS as Q_}from"@zibby/skill-ids";import{z as w}from"zod";var at=["ok","info","warn","critical"],Fm=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(at).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.')}),Km=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(at).optional()}),Gm=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.")}),Hm=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(at).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.")}),zm=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(at).optional()})).min(1).max(20)}),Ym=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),Wm=w.discriminatedUnion("kind",[Km,Gm,Hm,zm,Ym]),ct=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:Fm,sections:w.array(Wm).max(20).default([]).superRefine((r,e)=>{r.forEach((t,n)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:w.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(i=>i.length===t.headers.length)&&e.addIssue({code:w.ZodIssueCode.custom,path:[n,"rows"],message:"every row must have headers.length entries"})})}),footer:w.object({viewUrl:w.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:w.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),U=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),Dt=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),Zm=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Mt(r,e,t=12){if(!Number.isFinite(r)||!Number.isFinite(e)||e<=0)return"";let n=Math.max(0,Math.min(1,r/e)),i=Math.round(n*t);return"\u2593".repeat(i)+"\u2591".repeat(t-i)}function lt(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function Ft(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function Vs({headers:r,rows:e}){let t=r.map((o,a)=>{let c=Math.max(String(o).length,...e.map(d=>String(d[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>lt(a,t[c])).join(" "),i=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),i,...e.map(o=>n(o))].join(`
1119
+ `,"utf-8");let b=["graph.mjs","workflow.json","nodes/index.mjs",...c.map(g=>`nodes/${g.replace(/_/g,"-")}.mjs`)];return{workflowDir:Cs(r,o),files:b,className:s,slug:i}}async function Lm(r){let{name:e,description:t,nodes:n,edges:i}=r;if(!e||!Js.test(e.toLowerCase()))return JSON.stringify({error:`Invalid workflow name "${e}". Must be kebab-case, 2-64 chars, lowercase letters/numbers/hyphens.`});if(!n||n.length===0)return JSON.stringify({error:"At least one node is required."});let s={name:e.toLowerCase(),description:t||`${Bs(e.toLowerCase())} workflow`,nodes:n.map(o=>({name:o.name.replace(/-/g,"_"),description:o.description||`Process ${o.name}`,inputFields:o.inputFields||[],outputFields:o.outputFields||[]})),edges:i||[]};if(s.edges.length===0&&s.nodes.length>0){for(let o=0;o<s.nodes.length-1;o++)s.edges.push({from:s.nodes[o].name,to:s.nodes[o+1].name});s.edges.push({from:s.nodes[s.nodes.length-1].name,to:"END"})}return JSON.stringify({ok:!0,spec:s,message:`Workflow "${s.name}" designed with ${s.nodes.length} node(s). Call build_workflow to generate the code.`,preview:{nodes:s.nodes.map(o=>o.name),flow:s.edges.map(o=>o.condition?`${o.from} \u2192(if ${o.condition})\u2192 ${o.to}`:`${o.from} \u2192 ${o.to}`)}})}async function jm(r,e){let{name:t,spec:n}=r,i=(t||n?.name||"").toLowerCase();if(!i||!Js.test(i))return JSON.stringify({error:`Invalid workflow name "${i}".`});if(!n||!n.nodes||n.nodes.length===0)return JSON.stringify({error:"spec with nodes is required. Call design_workflow first."});let s=E(e,".zibby","workflows",i);if(de(s))return JSON.stringify({error:`Workflow "${i}" already exists at .zibby/workflows/${i}/. Delete it first or choose a different name.`});let o=await Ms(n,e),a=xm(e,i,n,o);return JSON.stringify({ok:!0,...a,message:`Workflow "${i}" created at ${a.workflowDir}/`,nextSteps:[`Test locally: zibby start ${i}`,`Deploy to cloud: zibby deploy ${i} --project <project-id>`,`Tail logs: zibby logs --workflow ${i} --project <project-id>`]})}async function $m(r,e){let{workflowName:t,nodeName:n,description:i,inputFields:s,outputFields:o}=r,a=(t||"").toLowerCase(),c=(n||"").replace(/-/g,"_"),d=E(e,".zibby","workflows",a);if(!de(d))return JSON.stringify({error:`Workflow "${a}" not found. Create it first with build_workflow.`});let l={name:a,description:"",nodes:[{name:c,description:i||`Process ${c}`,inputFields:s||[],outputFields:o||[]}],edges:[]},u=(await Ms(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`;Fe(E(m,f),u,"utf-8");let h=E(m,"index.mjs"),b=it(c),g=`export { ${b} } from './${c.replace(/_/g,"-")}.mjs';
1120
+ `,_=de(h)?st(h,"utf-8"):"";return _.includes(b)||Fe(h,_+g,"utf-8"),JSON.stringify({ok:!0,file:`nodes/${f}`,exportName:b,message:`Node "${c}" added. Update graph.mjs to wire it into the graph.`})}async function Pm(r,e){let{name:t,projectId:n}=r,i=(t||"").toLowerCase();if(!i)return JSON.stringify({error:"Workflow name is required."});if(!n)return JSON.stringify({error:"projectId is required."});let s=E(e,".zibby","workflows",i);if(!de(s))return JSON.stringify({error:`Workflow "${i}" not found at .zibby/workflows/${i}/`});try{let{execSync:o}=await import("child_process"),a=o(`node "${E(e,"packages/cli/bin/zibby.js")}" deploy ${i} --project ${n}`,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:a.trim()})}catch{try{let{execSync:a}=await import("child_process"),c=a(`npx zibby deploy ${i} --project ${n}`,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]});return JSON.stringify({ok:!0,output:c.trim()})}catch(a){return JSON.stringify({error:`Deploy failed: ${a.message}`})}}}function Cm(r){let e=E(r,".zibby","workflows");if(!de(e))return JSON.stringify({workflows:[],message:"No workflows found. Use build_workflow to create one."});let n=Pr(e).filter(i=>{try{return Ps(E(e,i)).isDirectory()}catch{return!1}}).map(i=>{let s=E(e,i,"workflow.json"),o={};try{o=JSON.parse(st(s,"utf-8"))}catch{}let a=E(e,i,"nodes"),c=0;try{c=Pr(a).filter(d=>d.endsWith(".mjs")&&d!=="index.mjs").length}catch{}return{name:i,description:o.description||"",nodeCount:c,path:Cs(r,E(e,i))}});return JSON.stringify({workflows:n})}var Fs={id:"workflow-builder",description:"Build, scaffold, and deploy custom AI workflows via conversation",envKeys:[],promptFragment:Nm,tools:[{name:"design_workflow",description:"Design a workflow spec (nodes, edges, descriptions) for the user to review before building. Call this after understanding requirements.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name in kebab-case (e.g., ticket-triage)"},description:{type:"string",description:"What the workflow does"},nodes:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Node name in snake_case (e.g., classify_ticket)"},description:{type:"string",description:"What this node does \u2014 be specific about input/output"},inputFields:{type:"array",items:{type:"string"},description:"Key fields this node reads from state"},outputFields:{type:"array",items:{type:"string"},description:"Key fields this node produces"}},required:["name","description"]},description:"Workflow nodes (processing steps)"},edges:{type:"array",items:{type:"object",properties:{from:{type:"string",description:"Source node name"},to:{type:"string",description:'Target node name (or "END")'},condition:{type:"string",description:"JS expression for conditional routing (optional)"}},required:["from","to"]},description:"Edges connecting nodes. If omitted, nodes are wired linearly."}},required:["name","description","nodes"]}},{name:"build_workflow",description:"Generate real workflow code on disk from a design spec. Uses the configured AI agent for high-quality code generation.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name (from design_workflow)"},spec:{type:"object",description:"The full spec object returned by design_workflow",properties:{name:{type:"string"},description:{type:"string"},nodes:{type:"array",items:{type:"object"}},edges:{type:"array",items:{type:"object"}}}}},required:["name","spec"]}},{name:"add_node",description:"Add a new node to an existing workflow. Generates the node file and updates the barrel export.",input_schema:{type:"object",properties:{workflowName:{type:"string",description:"Existing workflow name (kebab-case)"},nodeName:{type:"string",description:"New node name (snake_case)"},description:{type:"string",description:"What this node does"},inputFields:{type:"array",items:{type:"string"},description:"Fields read from state"},outputFields:{type:"array",items:{type:"string"},description:"Fields produced"}},required:["workflowName","nodeName","description"]}},{name:"deploy_workflow",description:"Deploy a workflow to Zibby Cloud. Returns the trigger URL.",input_schema:{type:"object",properties:{name:{type:"string",description:"Workflow name to deploy"},projectId:{type:"string",description:"Target project ID"}},required:["name","projectId"]}},{name:"list_workflows",description:"List all local workflows in .zibby/workflows/.",input_schema:{type:"object",properties:{}}},{name:"explore_framework_docs",description:"Read Zibby framework documentation on demand. Call this before building complex workflows or when you need details on advanced patterns (middleware, conditional routing, skills, deployment, CLI commands).",input_schema:{type:"object",properties:{topic:{type:"string",description:'Doc topic to read (e.g., "workflow", "custom-workflows", "cli-reference", "packages/core", "packages/skills", "integrations/jira"). Call with no topic to list all available docs.'}}}}],async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"design_workflow":return await Lm(e);case"build_workflow":return await jm(e,n);case"add_node":return await $m(e,n);case"deploy_workflow":return await Pm(e,n);case"list_workflows":return Cm(n);case"explore_framework_docs":{let i=(e.topic||"").trim();if(!i){let o=$s();return JSON.stringify({available:o,hint:"Call again with a topic to read its content."})}let s=Ds(i);if(!s){let o=$s();return JSON.stringify({error:`Doc "${i}" not found.`,available:o})}return JSON.stringify({topic:i,content:s})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:i.message})}},resolve(){return null}};import{resolveIntegrationToken as Um}from"@zibby/core/backend-client.js";var Jr=Object.freeze({id:"openai_billing",requiresIntegration:N.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),Br=Object.freeze({id:"anthropic_billing",requiresIntegration:N.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),qr=Object.freeze({id:"cursor_admin",requiresIntegration:N.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function Ks(r){return Math.floor(r/1e3)}function Ur(r){return new Date(r).toISOString().slice(0,10)}function Gs(r){return new Date(r).toISOString()}async function ot(r){let e=await Um(r);if(!e?.token)throw new Error(`${r} token resolver returned no token`);return e.token}async function Hs({startMs:r,endMs:e,groupBy:t=["project_id","line_item"]}){let n=await ot("openai_billing"),i=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.openai.com/v1/organization/costs?${[`start_time=${Ks(r)}`,`end_time=${Ks(e)}`,"bucket_width=1d","limit=180",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`OpenAI costs API ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=Ur((m.start_time||0)*1e3);for(let h of m.results||[])i.push({provider:"openai",day:f,costUsd:Number(h.amount?.value??0),projectId:h.project_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.line_item||void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Jm(){let r=await ot("openai_billing"),t=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`OpenAI projects API ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function zs({startMs:r,endMs:e,groupBy:t=["workspace_id"]}){let n=await ot("anthropic_billing"),i=[],s=0,o=t.map(c=>`group_by[]=${encodeURIComponent(c)}`).join("&"),a=null;for(let c=0;c<50;c++){let l=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(Gs(r))}`,`ending_at=${encodeURIComponent(Gs(e))}`,"bucket=1d","limit=100",o,a?`page=${encodeURIComponent(a)}`:""].filter(Boolean).join("&")}`,p=await fetch(l,{headers:{"x-api-key":n,"anthropic-version":"2023-06-01"}});if(!p.ok){let m=await p.text().catch(()=>"");throw new Error(`Anthropic cost_report ${p.status}: ${m.slice(0,200)}`)}let u=await p.json();for(let m of u.data||[]){s+=1;let f=(m.starting_at||"").slice(0,10);for(let h of m.results||[])i.push({provider:"anthropic",day:f,costUsd:Number(h.amount??h.cost??0),workspaceId:h.workspace_id||void 0,apiKeyId:h.api_key_id||void 0,model:h.model||void 0,tokensIn:h.uncached_input_tokens!=null?Number(h.uncached_input_tokens):void 0,tokensOut:h.output_tokens!=null?Number(h.output_tokens):void 0,cachedTokens:h.cached_input_tokens!=null?Number(h.cached_input_tokens):void 0})}if(!u.has_more||!u.next_page)break;a=u.next_page}return{ok:!0,items:i,rawBuckets:s}}async function Bm(){let r=await ot("anthropic_billing"),t=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":r,"anthropic-version":"2023-06-01"}});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Anthropic workspaces ${t.status}: ${s.slice(0,200)}`)}let n=await t.json(),i=new Map;for(let s of n.data||[])i.set(s.id,s.name);return i}async function Ys({startMs:r,endMs:e}){let t=await ot("cursor_admin"),n=Ur(r),i=Ur(e),s=`https://api.cursor.com/teams/daily-usage-data?startDate=${n}&endDate=${i}`,o=await fetch(s,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Cursor daily-usage ${o.status}: ${l.slice(0,200)}`)}let a=await o.json(),c=[],d=0;for(let l of a.data||[]){d+=1;let 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 qm({startMs:r,endMs:e}){let[t,n,i]=await Promise.allSettled([Hs({startMs:r,endMs:e}),zs({startMs:r,endMs:e}),Ys({startMs:r,endMs:e})]),s=l=>l.status==="fulfilled"?l.value:{ok:!1,error:l.reason?.message||String(l.reason),items:[]},o=s(t),a=s(n),c=s(i),d=[{provider:"openai",totalUsd:o.items.reduce((l,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 Dm(r,e){let t=new Map;for(let n of r){let i=e(n);if(!i)continue;let s=t.get(i)||{key:i,totalUsd:0,count:0};s.totalUsd+=n.costUsd||0,s.count+=1,t.set(i,s)}return[...t.values()].sort((n,i)=>i.totalUsd-n.totalUsd)}function Mm(r){if(!r.length)return{mean:0,stddev:0};let e=r.reduce((n,i)=>n+i,0)/r.length,t=r.reduce((n,i)=>n+(i-e)**2,0)/r.length;return{mean:e,stddev:Math.sqrt(t)}}import{SKILL_IDS as Q_}from"@zibby/skill-ids";import{z as w}from"zod";var at=["ok","info","warn","critical"],Fm=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(at).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.')}),Km=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(at).optional()}),Gm=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.")}),Hm=w.object({kind:w.literal("callouts"),title:w.string().max(120).optional(),tone:w.enum(at).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.")}),zm=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(at).optional()})).min(1).max(20)}),Ym=w.object({kind:w.literal("paragraph"),title:w.string().max(120).optional(),text:w.string().min(1).max(3e3)}),Wm=w.discriminatedUnion("kind",[Km,Gm,Hm,zm,Ym]),ct=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:Fm,sections:w.array(Wm).max(20).default([]).superRefine((r,e)=>{r.forEach((t,n)=>{t.kind==="trend"&&t.labels.length!==t.values.length&&e.addIssue({code:w.ZodIssueCode.custom,path:[n,"values"],message:"labels.length must equal values.length"}),t.kind==="table"&&!t.rows.every(i=>i.length===t.headers.length)&&e.addIssue({code:w.ZodIssueCode.custom,path:[n,"rows"],message:"every row must have headers.length entries"})})}),footer:w.object({viewUrl:w.string().url().optional().describe('Optional "View in Zibby" button URL.'),rerunUrl:w.string().url().optional().describe('Optional "Run again" button URL.')}).optional()}),U=Object.freeze({ok:"\u{1F7E2}",info:"\u{1F535}",warn:"\u{1F7E0}",critical:"\u{1F534}"}),Dt=Object.freeze({up:"\u2191",down:"\u2193",flat:"\u2192"}),Zm=Object.freeze({ok:"green",info:"blue",warn:"orange",critical:"red"});function Mt(r,e,t=12){if(!Number.isFinite(r)||!Number.isFinite(e)||e<=0)return"";let n=Math.max(0,Math.min(1,r/e)),i=Math.round(n*t);return"\u2593".repeat(i)+"\u2591".repeat(t-i)}function lt(r,e){let t=String(r);return t.length>=e?t:t+" ".repeat(e-t.length)}function Ft(r,e){let t=String(r);return t.length>=e?t:" ".repeat(e-t.length)+t}function Vs({headers:r,rows:e}){let t=r.map((o,a)=>{let c=Math.max(String(o).length,...e.map(d=>String(d[a]??"").length));return Math.min(c,32)}),n=o=>o.map((a,c)=>lt(a,t[c])).join(" "),i=t.map(o=>"\u2500".repeat(o)).join(" ");return"```\n"+[n(r),i,...e.map(o=>n(o))].join(`
1121
1121
  `)+"\n```"}function Vm(r){let e=ct.parse(r),t=[];t.push({type:"header",text:{type:"plain_text",text:e.title.slice(0,150),emoji:!0}}),e.subtitle&&t.push({type:"context",elements:[{type:"mrkdwn",text:e.subtitle}]});let n=[`*${e.headline.primary}*`];if(e.headline.delta){let s=Dt[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"";n.push(`${s} ${e.headline.delta.value} ${o}`.trim())}let i=n.join(" ");e.headline.summary&&(i+=`
1122
1122
  `+e.headline.summary),t.push({type:"section",text:{type:"mrkdwn",text:i}});for(let s of e.sections)switch(t.push({type:"divider"}),s.title&&t.push({type:"section",text:{type:"mrkdwn",text:`*${s.title}*`}}),s.kind){case"trend":{let o=Math.max(...s.values),a=s.labels.map((c,d)=>{let l=s.values[d],p=Mt(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`${lt(c,10)} ${Ft(l.toLocaleString(),8)} ${p}${m}`});t.push({type:"section",text:{type:"mrkdwn",text:"```\n"+a.join(`
1123
1123
  `)+"\n```"}});break}case"table":{t.push({type:"section",text:{type:"mrkdwn",text:Vs(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(`
@@ -1129,4 +1129,4 @@ _${a.sub}_`:""}${a.severity?` ${U[a.severity]}`:""}`}));for(let a=0;a<o.length;a
1129
1129
  `)}});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(`
1130
1130
  `)}});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=Zm[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 Xm=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),Ws=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});function Ae(r,e={}){let t={type:"text",text:{content:String(r).slice(0,2e3)}};return e.annotations&&(t.annotations=e.annotations),[t]}function Dr(r,e){let t={object:"block",type:"paragraph",paragraph:{rich_text:Ae(r)}};return e&&(t.paragraph.color=e),t}function ef(r){return{object:"block",type:"code",code:{rich_text:Ae(r),language:"plain text"}}}function tf(r){let e=ct.parse(r),t=[];t.push({object:"block",type:"heading_1",heading_1:{rich_text:Ae(e.title.slice(0,200))}}),e.subtitle&&t.push(Dr(e.subtitle,"gray_background"));let n=[{type:"text",text:{content:e.headline.primary.slice(0,200)},annotations:{bold:!0}}];if(e.headline.delta){let s=Dt[e.headline.delta.direction]||"",o=e.headline.delta.severity?U[e.headline.delta.severity]:"",a=` ${s} ${e.headline.delta.value} ${o}`.trimEnd();n.push({type:"text",text:{content:a}})}t.push({object:"block",type:"paragraph",paragraph:{rich_text:n}}),e.headline.summary&&t.push(Dr(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:Ae(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=Mt(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`${lt(d,10)} ${Ft(p.toLocaleString(),8)} ${u}${f}`});t.push(ef(c.join(`
1131
1131
  `)));break}case"table":{let o={object:"block",type:"table_row",table_row:{cells:s.headers.map(c=>Ae(c))}},a=s.rows.map(c=>({object:"block",type:"table_row",table_row:{cells:c.map(d=>Ae(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=Ws[o],c=Xm[o];for(let d of s.items)t.push({object:"block",type:"callout",callout:{rich_text:Ae(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(Dr(s.text));break}}e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)&&(t.push({object:"block",type:"divider",divider:{}}),e.footer.viewUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.viewUrl}}),e.footer.rerunUrl&&t.push({object:"block",type:"embed",embed:{url:e.footer.rerunUrl}}));let i=e.headline.delta?.severity?Ws[e.headline.delta.severity]:void 0;return{blocks:t,title:e.title.slice(0,200),icon:i}}function Zs(r){return String(r??"").replace(/\|/g,"\\|")}function rf(r){let e=ct.parse(r),t=[];t.push(`# ${e.title}`),e.subtitle&&t.push("",e.subtitle);let n=[`**${e.headline.primary}**`];if(e.headline.delta){let i=Dt[e.headline.delta.direction]||"",s=e.headline.delta.severity?U[e.headline.delta.severity]:"";n.push(`${i} ${e.headline.delta.value} ${s}`.trim())}t.push("",n.join(" ")),e.headline.summary&&t.push("",e.headline.summary);for(let i of e.sections)switch(t.push("","---",""),i.title&&t.push(`## ${i.title}`,""),i.kind){case"trend":{let s=Math.max(...i.values),o=Math.min(...i.values),a=i.labels.map((c,d)=>{let l=i.values[d],p=Mt(l,s),m=(i.highlight==="last"&&d===i.labels.length-1||i.highlight==="max"&&l===s||i.highlight==="min"&&l===o)&&i.severity?` ${U[i.severity]}`:"";return`${lt(c,10)} ${Ft(l.toLocaleString(),8)} ${p}${m}`});t.push("```",...a,"```");break}case"table":{t.push(`| ${i.headers.map(Zs).join(" | ")} |`),t.push(`| ${i.headers.map(()=>"---").join(" | ")} |`);for(let s of i.rows)t.push(`| ${s.map(Zs).join(" | ")} |`);break}case"callouts":{let s=U[i.tone||"info"];for(let o of i.items)t.push(`- ${s} ${o}`);break}case"breakdown":{for(let s of i.rows){let o=s.sub?` _${s.sub}_`:"",a=s.severity?` ${U[s.severity]}`:"";t.push(`- **${s.label}**: ${s.value}${o}${a}`)}break}case"paragraph":{t.push(i.text);break}}if(e.footer&&(e.footer.viewUrl||e.footer.rerunUrl)){let i=[];e.footer.viewUrl&&i.push(`[View in Zibby](${e.footer.viewUrl})`),e.footer.rerunUrl&&i.push(`[Run again](${e.footer.rerunUrl})`),t.push("","---","",i.join(" \xB7 "))}return t.join(`
1132
- `)}import{createRequire as nf}from"module";import{fileURLToPath as sf}from"url";import{registerHandlers as of}from"@zibby/core/function-skill-registry.js";import{registerSkill as af}from"@zibby/agent-workflow";var cf=nf(import.meta.url);function lf(){try{return cf.resolve("@zibby/core/function-bridge.js")}catch{return null}}var df=import.meta.url;function pf(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let t=new Error().stack;for(let n=2;n<t.length;n++){let i=t[n].getFileName();if(i&&i!==df&&!i.startsWith("node:"))return i.startsWith("file://")?sf(i):i}return null}finally{Error.prepareStackTrace=r}}function uf(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let e={},t=[];for(let[n,i]of Object.entries(r))if(typeof i=="string")e[n]={type:i},t.push(n);else{let{required:s,...o}=i;e[n]=o,s!==!1&&t.push(n)}return{type:"object",properties:e,required:t}}function mf(r,e,t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n={[r]:t.handler},i=[{name:r,description:t.description||"",input_schema:uf(t.input)}];return of(r,n,i),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:t.description||`Function skill: ${r}`,envKeys:[],tools:i,resolve(){let s=lf();return s?{command:"node",args:[s,e,r]}:null}}}function ff(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 Qs(r,e){let t;if("handler"in e){if(typeof e.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n=pf();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);t=mf(r,n,e)}else if(typeof e.resolve=="function")t=ff(r,e);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return af(t),t}var hf=Qs;import{registerSkill as nb,getSkill as ib,hasSkill as sb,getAllSkills as ob,listSkillIds as ab}from"@zibby/agent-workflow";I(Kr);I(zr);I(je);I($e);I(nn);I(on);I(cn);I(ln);I(un);I($);I(D);I(hn);I(In);I(Tn);I(Ln);I(Jn);I(qn);I(St);I(Dn);I(pi);I(me);I(yi);I(Fn);I(Yn);I(Ei);I(Ui);I(Fi);I(Wi);I(ss);I(os);I(as);I(gs);I(Ns);I(Os);I(Es);I(Ls);I(Fs);I(Jr);I(qr);I(Br);I({...$,id:"slack_notify"});export{N as INTEGRATIONS,po as INTEGRATION_REGISTRY,at as REPORT_SEVERITIES,Q_ as SKILLS,qr as anthropicBillingSkill,Wi as artifactSkill,Kr as browserSkill,ss as chartRenderSkill,Ei as chatMemorySkill,qn as chatNotifySkill,as as chatProgressSkill,Ns as codeScanSkill,os as codeStatsSkill,Es as codebaseMemorySkill,Yn as coreToolsSkill,Br as cursorAdminSkill,Fi as datasetStoreSkill,hn as discordSkill,Bm as fetchAllProviders,zs as fetchAnthropicCosts,qm as fetchAnthropicWorkspaces,Ys as fetchCursorSpend,Hs as fetchOpenAICosts,Jm as fetchOpenAIProjects,nn as figmaSkill,hf as functionSkill,Ls as gbrainSkill,ob as getAllSkills,ib as getSkill,me as gitSkill,yi as gitWriteSkill,je as githubSkill,$e as gitlabSkill,Ln as googleDocsSkill,Dm as groupByKey,sb as hasSkill,on as hubspotSkill,zr as jiraSkill,Ui as kvMemorySkill,Jn as larkDocsSkill,D as larkSkill,cn as linearSkill,Tn as linkedinSkill,ab as listSkillIds,Mm as meanStddev,Dn as memorySkill,In as notionSkill,Jr as openaiBillingSkill,un as opendesignSkill,ln as planeSkill,nb as registerSkill,ct as reportObjectSchema,Vm as reportToBlockKit,Qm as reportToLarkCard,rf as reportToMarkdown,tf as reportToNotionBlocks,pi as runnerSkill,St as sentrySkill,Qs as skill,Fn as skillInstallerSkill,$ as slackSkill,gs as socialCardSkill,pi as testRunnerSkill,Fs as workflowBuilderSkill};
1132
+ `)}import{createRequire as nf}from"module";import{fileURLToPath as sf}from"url";import{registerHandlers as of}from"@zibby/core/function-skill-registry.js";import{registerSkill as af}from"@zibby/agent-workflow";var cf=nf(import.meta.url);function lf(){try{return cf.resolve("@zibby/core/function-bridge.js")}catch{return null}}var df=import.meta.url;function pf(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let t=new Error().stack;for(let n=2;n<t.length;n++){let i=t[n].getFileName();if(i&&i!==df&&!i.startsWith("node:"))return i.startsWith("file://")?sf(i):i}return null}finally{Error.prepareStackTrace=r}}function uf(r){if(!r||typeof r!="object")return{type:"object",properties:{},required:[]};let e={},t=[];for(let[n,i]of Object.entries(r))if(typeof i=="string")e[n]={type:i},t.push(n);else{let{required:s,...o}=i;e[n]=o,s!==!1&&t.push(n)}return{type:"object",properties:e,required:t}}function mf(r,e,t){if(typeof t.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n={[r]:t.handler},i=[{name:r,description:t.description||"",input_schema:uf(t.input)}];return of(r,n,i),{id:r,type:"function",serverName:r,allowedTools:[`mcp__${r}__*`],description:t.description||`Function skill: ${r}`,envKeys:[],tools:i,resolve(){let s=lf();return s?{command:"node",args:[s,e,r]}:null}}}function ff(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 Qs(r,e){let t;if("handler"in e){if(typeof e.handler!="function")throw new Error(`Skill "${r}" must have a handler function`);let n=pf();if(!n)throw new Error(`Could not resolve caller file for skill "${r}".`);t=mf(r,n,e)}else if(typeof e.resolve=="function")t=ff(r,e);else throw new Error(`Skill "${r}" must have either a handler (function skill) or resolve (MCP skill).`);return af(t),t}var hf=Qs;import{registerSkill as nb,getSkill as ib,hasSkill as sb,getAllSkills as ob,listSkillIds as ab}from"@zibby/agent-workflow";I(Kr);I(zr);I(je);I($e);I(nn);I(on);I(cn);I(ln);I(un);I($);I(D);I(hn);I(In);I(Tn);I(Ln);I(Jn);I(Bn);I(St);I(Dn);I(pi);I(me);I(yi);I(Fn);I(Yn);I(Ei);I(Ui);I(Fi);I(Wi);I(ss);I(os);I(as);I(gs);I(Ns);I(Os);I(Es);I(Ls);I(Fs);I(Jr);I(Br);I(qr);I({...$,id:"slack_notify"});export{N as INTEGRATIONS,po as INTEGRATION_REGISTRY,at as REPORT_SEVERITIES,Q_ as SKILLS,Br as anthropicBillingSkill,Wi as artifactSkill,Kr as browserSkill,ss as chartRenderSkill,Ei as chatMemorySkill,Bn as chatNotifySkill,as as chatProgressSkill,Ns as codeScanSkill,os as codeStatsSkill,Es as codebaseMemorySkill,Yn as coreToolsSkill,qr as cursorAdminSkill,Fi as datasetStoreSkill,hn as discordSkill,qm as fetchAllProviders,zs as fetchAnthropicCosts,Bm as fetchAnthropicWorkspaces,Ys as fetchCursorSpend,Hs as fetchOpenAICosts,Jm as fetchOpenAIProjects,nn as figmaSkill,hf as functionSkill,Ls as gbrainSkill,ob as getAllSkills,ib as getSkill,me as gitSkill,yi as gitWriteSkill,je as githubSkill,$e as gitlabSkill,Ln as googleDocsSkill,Dm as groupByKey,sb as hasSkill,on as hubspotSkill,zr as jiraSkill,Ui as kvMemorySkill,Jn as larkDocsSkill,D as larkSkill,cn as linearSkill,Tn as linkedinSkill,ab as listSkillIds,Mm as meanStddev,Dn as memorySkill,In as notionSkill,Jr as openaiBillingSkill,un as opendesignSkill,ln as planeSkill,nb as registerSkill,ct as reportObjectSchema,Vm as reportToBlockKit,Qm as reportToLarkCard,rf as reportToMarkdown,tf as reportToNotionBlocks,pi as runnerSkill,St as sentrySkill,Qs as skill,Fn as skillInstallerSkill,$ as slackSkill,gs as socialCardSkill,pi as testRunnerSkill,Fs as workflowBuilderSkill};