@zibby/skills 0.1.29 → 0.1.31

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/bin/mcp-slack.mjs CHANGED
@@ -118,16 +118,21 @@ server.registerTool(
118
118
  'slack_post_message',
119
119
  {
120
120
  title: 'Post Slack Message',
121
- description: 'Post a text message to a Slack channel OR direct-message a user. `channel` accepts a channel id (C…), a channel name with `#` prefix, OR a user id (U…) for DMs.',
121
+ description: 'Post a message to a Slack channel OR direct-message a user. `channel` accepts a channel id (C…), a channel name with `#` prefix, OR a user id (U…) for DMs. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.',
122
122
  inputSchema: z.object({
123
123
  channel: z.string().describe('Channel id, channel name (#…), or user id (U…) for DMs'),
124
- text: z.string().describe('Message text'),
124
+ text: z.string().describe('Notification/fallback text (required even when blocks are sent)'),
125
+ blocks: z.array(z.any()).optional().describe('Block Kit blocks for a rich card (optional). header / section / divider / context; a section may carry a button accessory with a url.'),
125
126
  }),
126
127
  },
127
128
  async (args = {}) => {
128
129
  try {
129
130
  if (!args.channel || !args.text) return err('channel and text are required');
130
- const data = await slackApi('chat.postMessage', { channel: args.channel, text: args.text });
131
+ const data = await slackApi('chat.postMessage', {
132
+ channel: args.channel,
133
+ text: args.text,
134
+ ...(args.blocks ? { blocks: args.blocks } : {}),
135
+ });
131
136
  return ok({ ok: true, ts: data.ts, channel: data.channel });
132
137
  } catch (e) { return err(e.message); }
133
138
  },
@@ -1,4 +1,4 @@
1
- import{execFileSync as V}from"child_process";import{existsSync as J,mkdirSync as re}from"fs";import{join as T,basename as se}from"path";import{randomBytes as ne}from"crypto";import{pathToFileURL as M}from"url";import{createRequire as W}from"module";var U=".zibby/memory",j="dolt",z={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},L="dolt",O=new Map,A=new Map,oe=W(import.meta.url),C=()=>ne(8).toString("hex"),S=()=>new Date().toISOString(),ie=[`CREATE TABLE IF NOT EXISTS chat_memory (
1
+ import{execFileSync as J}from"child_process";import{existsSync as H,mkdirSync as j}from"fs";import{join as g,basename as me}from"path";import{randomBytes as le}from"crypto";import{pathToFileURL as T}from"url";import{createRequire as W}from"module";var b=".zibby/memory",Z="dolt",z={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},L="dolt",N=new Map,M=new Map,ue=W(import.meta.url),C=()=>le(8).toString("hex"),S=()=>new Date().toISOString(),ye=[`CREATE TABLE IF NOT EXISTS chat_memory (
2
2
  id VARCHAR(64) PRIMARY KEY,
3
3
  memory_key VARCHAR(160),
4
4
  category VARCHAR(32) NOT NULL,
@@ -29,10 +29,10 @@ import{execFileSync as V}from"child_process";import{existsSync as J,mkdirSync as
29
29
  tasks_failed INT DEFAULT 0,
30
30
  key_facts TEXT,
31
31
  created_at VARCHAR(32) NOT NULL
32
- )`],D=new Set;function d(t,e){return V(j,e,{...z,cwd:t})}function g(t,e){try{let r=d(t,["sql","-q",e,"-r","json"]);return JSON.parse(r.trim()).rows||[]}catch{return[]}}function p(t,e){d(t,["sql","-q",e])}function H(t){if(D.has(t))return!0;if(!J(T(t,".dolt"))){if(!ce())return!1;re(t,{recursive:!0}),d(t,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${ie.join(`;
33
- `)};`;p(t,e);try{p(t,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{p(t,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return D.add(t),!0}function Te(){D.clear()}function ce(){try{return V(j,["version"],{...z,timeout:5e3}),!0}catch{return!1}}function c(t){return t==null?"NULL":`'${String(t).replace(/'/g,"''")}'`}function B(t){return String(t||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function R(t){return t==="long"?3:t==="mid"?2:t==="short"?1:0}function b(t,e){let r=["short","mid","long"].includes(t)?t:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(e||"").toLowerCase())&&r==="short"?"mid":r}function Z(t){let e=new Map;for(let r of t||[]){let s=B(r.content),n=r.memory_key?`key:${r.memory_key}`:s?`norm:${s}`:"";if(!n)continue;let o=e.get(n);if(!o){e.set(n,r);continue}let i=R(o.tier),a=R(r.tier);if(a>i){e.set(n,r);continue}a===i&&Number(r.relevance||0)>Number(o.relevance||0)&&e.set(n,r)}return[...e.values()]}function $(t,e){let r=String(t??"");return r.length<=e?r:e<=1?r.slice(0,e):`${r.slice(0,e-1)}\u2026`}function v(t,e){let r={recentSessions:Array.isArray(t?.recentSessions)?t.recentSessions:[],topMemories:Array.isArray(t?.topMemories)?t.topMemories:[],taskStats:Array.isArray(t?.taskStats)?t.taskStats:[],ticketFilter:t?.ticketFilter||null,backend:e||String(t?.backend||L),error:t?.error||null};return r.backend==="mem0"?{...r,recentSessions:[],taskStats:[]}:r}function ae(t){let e=[];if(t.recentSessions?.length>0){e.push("Recent sessions:");for(let r of t.recentSessions.slice(0,3))r?.summary?.trim()&&e.push(`- ${$(r.summary,150)}${r.tickets?` [${r.tickets}]`:""}`)}if(t.topMemories?.length>0){e.push("Known facts:");for(let r of t.topMemories.slice(0,10)){let s=r.tier==="long"?"\u2605":"\xB7";e.push(`${s} [${r.category}] ${$(r.content,120)}`)}}return e.length===0?"":`## Memory Context
32
+ )`],B=new Set;function f(t,e){return J(Z,e,{...z,cwd:t})}function h(t,e){try{let r=f(t,["sql","-q",e,"-r","json"]);return JSON.parse(r.trim()).rows||[]}catch{return[]}}function _(t,e){f(t,["sql","-q",e])}function q(t){if(B.has(t))return!0;if(!H(g(t,".dolt"))){if(!de())return!1;j(t,{recursive:!0}),f(t,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${ye.join(`;
33
+ `)};`;_(t,e);try{_(t,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{_(t,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return B.add(t),!0}function Oe(){B.clear()}function De(t){return x(t)}function be(t){return G(t)}function Le(t,e){return U(t,e)}function Be(t,e){return re(t,e)}function de(){try{return J(Z,["version"],{...z,timeout:5e3}),!0}catch{return!1}}function c(t){return t==null?"NULL":`'${String(t).replace(/'/g,"''")}'`}function F(t){return String(t||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function A(t){return t==="long"?3:t==="mid"?2:t==="short"?1:0}function K(t,e){let r=["short","mid","long"].includes(t)?t:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(e||"").toLowerCase())&&r==="short"?"mid":r}function P(t){let e=new Map;for(let r of t||[]){let s=F(r.content),n=r.memory_key?`key:${r.memory_key}`:s?`norm:${s}`:"";if(!n)continue;let o=e.get(n);if(!o){e.set(n,r);continue}let i=A(o.tier),a=A(r.tier);if(a>i){e.set(n,r);continue}a===i&&Number(r.relevance||0)>Number(o.relevance||0)&&e.set(n,r)}return[...e.values()]}function w(t,e){let r=String(t??"");return r.length<=e?r:e<=1?r.slice(0,e):`${r.slice(0,e-1)}\u2026`}function v(t,e){let r={recentSessions:Array.isArray(t?.recentSessions)?t.recentSessions:[],topMemories:Array.isArray(t?.topMemories)?t.topMemories:[],taskStats:Array.isArray(t?.taskStats)?t.taskStats:[],ticketFilter:t?.ticketFilter||null,backend:e||String(t?.backend||L),error:t?.error||null};return r.backend==="mem0"?{...r,recentSessions:[],taskStats:[]}:r}function pe(t){let e=[];if(t.recentSessions?.length>0){e.push("Recent sessions:");for(let r of t.recentSessions.slice(0,3))r?.summary?.trim()&&e.push(`- ${w(r.summary,150)}${r.tickets?` [${r.tickets}]`:""}`)}if(t.topMemories?.length>0){e.push("Known facts:");for(let r of t.topMemories.slice(0,10)){let s=r.tier==="long"?"\u2605":"\xB7";e.push(`${s} [${r.category}] ${w(r.content,120)}`)}}return e.length===0?"":`## Memory Context
34
34
  ${e.join(`
35
- `)}`}function I(t){return{backend:t.backend,recentSessions:t.recentSessions.slice(0,3).map(e=>({summary:$(String(e?.summary||""),160),tickets:e?.tickets||null,created_at:e?.created_at||null})),topMemories:t.topMemories.slice(0,8).map(e=>({category:e?.category||null,tier:e?.tier||null,content:$(String(e?.content||""),140),source:e?.source||null})),taskStats:t.taskStats,error:t.error||null}}async function K(t,e){let r=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(r==="mem0"||r==="dolt")return r;let s=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(s==="mem0"||s==="dolt")return s;if(A.has(t))return A.get(t);try{let n=T(t,".zibby.config.mjs");if(J(n)){let o=await import(M(n).href),i=String(o?.default?.memory?.backend||"").trim().toLowerCase();if(i==="mem0"||i==="dolt")return A.set(t,i),i}}catch{}return A.set(t,L),L}function X(t){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${se(t||process.cwd())}`}function me(){let t=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!t)return null;let e=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),r=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),s=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),n=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536);return{llm:{provider:"openai",config:{model:r,baseURL:t,...e?{apiKey:e}:{}}},embedder:{provider:"openai",config:{model:s,embeddingDims:n,baseURL:t,...e?{apiKey:e}:{}}},vectorStore:{provider:"memory",config:{dimension:n}}}}async function G(t){let e=t||process.cwd();if(O.has(e))return O.get(e);let r;try{let a=W(M(T(e,"package.json")).href).resolve("mem0ai/oss");r=await import(M(a).href)}catch{try{let i=oe.resolve("mem0ai/oss");r=await import(M(i).href)}catch(i){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${i.message})`,{cause:i})}}let s=r?.Memory;if(!s)throw new Error("mem0ai/oss does not export Memory");let n=me(),o=n?new s(n):new s;return O.set(e,o),o}function x(t,e="mid"){return(Array.isArray(t)?t:Array.isArray(t?.results)?t.results:[]).map(s=>({id:s?.id||C(),memory_key:s?.metadata?.memoryKey||s?.metadata?.memory_key||null,category:s?.metadata?.category||"fact",content:s?.memory||s?.content||"",source:s?.metadata?.source||"mem0",ticket_key:s?.metadata?.ticketKey||s?.metadata?.ticket_key||null,tier:b(s?.metadata?.tier||e,s?.metadata?.category||"fact"),relevance:Number(s?.score??s?.metadata?.relevance??.8),created_at:s?.created_at||s?.metadata?.created_at||S()})).filter(s=>String(s.content||"").trim().length>0)}var Ae={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
35
+ `)}`}function O(t){return{backend:t.backend,recentSessions:t.recentSessions.slice(0,3).map(e=>({summary:w(String(e?.summary||""),160),tickets:e?.tickets||null,created_at:e?.created_at||null})),topMemories:t.topMemories.slice(0,8).map(e=>({category:e?.category||null,tier:e?.tier||null,content:w(String(e?.content||""),140),source:e?.source||null})),taskStats:t.taskStats,error:t.error||null}}async function fe(t,e){let r=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(r==="mem0"||r==="dolt")return r;let s=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(s==="mem0"||s==="dolt")return s;if(M.has(t))return M.get(t);try{let n=g(t,".zibby.config.mjs");if(H(n)){let o=await import(T(n).href),i=String(o?.default?.memory?.backend||"").trim().toLowerCase();if(i==="mem0"||i==="dolt")return M.set(t,i),i}}catch{}return M.set(t,L),L}function X(t){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${me(t||process.cwd())}`}var _e="mem0";function x(t){let e=g(t,b,_e);return{dir:e,vectorDbPath:g(e,"vectors.db"),historyDbPath:g(e,"history.db")}}function G(t){let e=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!e)return null;let r=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),s=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),n=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),o=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:i,historyDbPath:a}=x(t||process.cwd());return{llm:{provider:"openai",config:{model:s,baseURL:e,...r?{apiKey:r}:{}}},embedder:{provider:"openai",config:{model:n,embeddingDims:o,baseURL:e,...r?{apiKey:r}:{}}},vectorStore:{provider:"memory",config:{dimension:o,dbPath:i}},historyDbPath:a}}async function Q(t){let e=t||process.cwd();if(N.has(e))return N.get(e);let r;try{let a=W(T(g(e,"package.json")).href).resolve("mem0ai/oss");r=await import(T(a).href)}catch{try{let i=ue.resolve("mem0ai/oss");r=await import(T(i).href)}catch(i){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${i.message})`,{cause:i})}}let s=r?.Memory;if(!s)throw new Error("mem0ai/oss does not export Memory");let n=G(e);if(n)try{j(x(e).dir,{recursive:!0})}catch{}let o=n?new s(n):new s;return N.set(e,o),o}function V(t,e="mid"){return(Array.isArray(t)?t:Array.isArray(t?.results)?t.results:[]).map(s=>({id:s?.id||C(),memory_key:s?.metadata?.memoryKey||s?.metadata?.memory_key||null,category:s?.metadata?.category||"fact",content:s?.memory||s?.content||"",source:s?.metadata?.source||"mem0",ticket_key:s?.metadata?.ticketKey||s?.metadata?.ticket_key||null,tier:K(s?.metadata?.tier||e,s?.metadata?.category||"fact"),relevance:Number(s?.score??s?.metadata?.relevance??.8),created_at:s?.created_at||s?.metadata?.created_at||S()})).filter(s=>String(s.content||"").trim().length>0)}var ee={id:"dolt",store:(t,e)=>te(t,e),recall:(t,e)=>Se(t,e),brief:(t,e)=>Re(t,e),endSession:(t,e)=>ne(t,e),logTask:(t,e)=>oe(t,e),taskHistory:(t,e)=>ie(t,e)},ge={id:"mem0",store:(t,e,r)=>Ee(t,e,r),recall:(t,e,r)=>se(t,e,r),brief:(t,e,r)=>Ae(t,e,r),endSession:(t,e)=>ne(t,e),logTask:(t,e)=>oe(t,e),taskHistory:(t,e)=>ie(t,e)},ke={dolt:ee,mem0:ge};async function U(t,e){let r=await fe(t,e);return ke[r]||ee}var Fe={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
36
36
  You have persistent memory across sessions. Use it to avoid losing context:
37
37
  - **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
38
38
  - **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
@@ -48,35 +48,35 @@ You have persistent memory across sessions. Use it to avoid losing context:
48
48
  - When the user's request is complete: call memory_end_session
49
49
 
50
50
  ### Categories for memory_store
51
- fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(t,e={}){let r=t?.options?.workspace||process.cwd(),s=T(r,U),n=await K(r,t);if(n==="dolt"&&!H(s)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:n,brief:v({backend:n,error:o},n),promptContext:"",debugPreview:I(v({backend:n,error:o},n)),error:o}}try{let o=n==="mem0"?await q(e,s,r):Y(e,s),i=JSON.parse(o||"{}"),a=v({...i,backend:n},n);return{backend:n,brief:a,promptContext:ae(a),debugPreview:I(a),error:a.error||null}}catch(o){let i=String(o?.message||o),a=v({backend:n,error:i},n);return{backend:n,brief:a,promptContext:"",debugPreview:I(a),error:i}}},async handleToolCall(t,e,r){let s=r?.options?.workspace||process.cwd(),n=T(s,U),o=await K(s,r);if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(t))&&!H(n))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});try{switch(t){case"memory_store":return o==="mem0"?await le(e,n,s):P(e,n);case"memory_recall":return o==="mem0"?await Q(e,n,s):ye(e,n);case"memory_brief":return o==="mem0"?await q(e,n,s):Y(e,n);case"memory_end_session":return ue(e,n);case"task_log":return de(e,n);case"task_history":return pe(e,n);default:return JSON.stringify({error:`Unknown tool: ${t}`})}}catch(a){if(o==="mem0")throw new Error(`mem0 throw: ${a.message}`,{cause:a});return JSON.stringify({error:a.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)"}},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 P(t,e){let{content:r,category:s,source:n,ticketKey:o,tier:i,memoryKey:a}=t;if(!r||!s)return JSON.stringify({error:"content and category are required"});let y=B(r);if(!y)return JSON.stringify({error:"content is empty after normalization"});let m=b(i,s),l=m==="long"?1:m==="mid"?.8:.5,u=String(a||"").trim().slice(0,160);if(u){let k=g(e,`SELECT id, tier, relevance
51
+ fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(t,e={}){let r=t?.options?.workspace||process.cwd(),s=g(r,b),n=await U(r,t),o=n.id;if(o==="dolt"&&!q(s)){let i="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:o,brief:v({backend:o,error:i},o),promptContext:"",debugPreview:O(v({backend:o,error:i},o)),error:i}}try{let i=await n.brief(e,s,r),a=JSON.parse(i||"{}"),m=v({...a,backend:o},o);return{backend:o,brief:m,promptContext:pe(m),debugPreview:O(m),error:m.error||null}}catch(i){let a=String(i?.message||i),m=v({backend:o,error:a},o);return{backend:o,brief:m,promptContext:"",debugPreview:O(m),error:a}}},async handleToolCall(t,e,r){let s=r?.options?.workspace||process.cwd(),n=g(s,b),o=await U(s,r),i=o.id;if((i==="dolt"||["memory_end_session","task_log","task_history"].includes(t))&&!q(n))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});try{switch(t){case"memory_store":return await o.store(e,n,s);case"memory_recall":return await o.recall(e,n,s);case"memory_brief":return await o.brief(e,n,s);case"memory_end_session":return await o.endSession(e,n,s);case"task_log":return await o.logTask(e,n,s);case"task_history":return await o.taskHistory(e,n,s);default:return JSON.stringify({error:`Unknown tool: ${t}`})}}catch(m){if(i==="mem0")throw new Error(`mem0 throw: ${m.message}`,{cause:m});return JSON.stringify({error:m.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 te(t,e){let{content:r,category:s,source:n,ticketKey:o,tier:i,memoryKey:a}=t;if(!r||!s)return JSON.stringify({error:"content and category are required"});let m=F(r);if(!m)return JSON.stringify({error:"content is empty after normalization"});let u=K(i,s),l=u==="long"?1:u==="mid"?.8:.5,y=String(a||"").trim().slice(0,160);if(y){let k=h(e,`SELECT id, tier, relevance
52
52
  FROM chat_memory
53
- WHERE memory_key = ${c(u)}
53
+ WHERE memory_key = ${c(y)}
54
54
  ORDER BY created_at DESC
55
- LIMIT 1`)[0];if(k){let E=String(k.tier||"mid"),N=Number(k.relevance||0),F=R(m)>R(E)?m:E,te=Math.max(l,N);p(e,`UPDATE chat_memory
55
+ LIMIT 1`)[0];if(k){let R=String(k.tier||"mid"),I=Number(k.relevance||0),Y=A(u)>A(R)?u:R,ae=Math.max(l,I);_(e,`UPDATE chat_memory
56
56
  SET content = ${c(r)},
57
57
  category = ${c(s)},
58
58
  source = ${c(n)},
59
59
  ticket_key = ${c(o)},
60
- tier = ${c(F)},
61
- relevance = ${te},
60
+ tier = ${c(Y)},
61
+ relevance = ${ae},
62
62
  created_at = ${c(S())}
63
- WHERE id = ${c(k.id)}`);try{d(e,["add","."]),d(e,["commit","-m",`memory upsert: ${s} \u2014 ${String(r).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:k.id,category:s,tier:F,memoryKey:u,upserted:!0})}}let _=g(e,`SELECT id, content, tier, relevance
63
+ WHERE id = ${c(k.id)}`);try{f(e,["add","."]),f(e,["commit","-m",`memory upsert: ${s} \u2014 ${String(r).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:k.id,category:s,tier:Y,memoryKey:y,upserted:!0})}}let p=h(e,`SELECT id, content, tier, relevance
64
64
  FROM chat_memory
65
65
  WHERE category = ${c(s)}
66
66
  ORDER BY created_at DESC
67
- LIMIT 200`).find(h=>B(h.content)===y);if(_){let h=String(_.tier||"mid"),k=Number(_.relevance||0),E=R(m)>R(h),N=l>k;if(E||N){p(e,`UPDATE chat_memory
68
- SET tier = ${c(E?m:h)},
67
+ LIMIT 200`).find(E=>F(E.content)===m);if(p){let E=String(p.tier||"mid"),k=Number(p.relevance||0),R=A(u)>A(E),I=l>k;if(R||I){_(e,`UPDATE chat_memory
68
+ SET tier = ${c(R?u:E)},
69
69
  relevance = ${Math.max(l,k)}
70
- WHERE id = ${c(_.id)}`);try{d(e,["add","."]),d(e,["commit","-m",`memory promote: ${s} \u2014 ${String(r).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:_.id,category:s,tier:E?m:h,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:_.id,category:s,tier:h,deduped:!0,promoted:!1})}let w=C(),ee=process.env.ZIBBY_CHAT_SESSION_ID||null;p(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
71
- VALUES (${c(w)}, ${c(u||null)}, ${c(s)}, ${c(r)}, ${c(n)}, ${c(o)}, ${c(ee)}, ${c(m)}, ${l}, ${c(S())})`);try{d(e,["add","."]),d(e,["commit","-m",`memory: ${s} \u2014 ${r.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:w,category:s,tier:m,memoryKey:u||null,stored:r.slice(0,100)})}async function le(t,e,r){let{content:s,category:n,source:o,ticketKey:i,tier:a,memoryKey:y}=t;if(!s||!n)return JSON.stringify({error:"content and category are required"});try{let m=await G(r),l=X(r),u=b(a,n);return await m.add([{role:"user",content:String(s)}],{userId:l,metadata:{memoryKey:y||null,category:n,tier:u,source:o||"zibby-chat",ticketKey:i||null,created_at:S()}}),JSON.stringify({ok:!0,backend:"mem0",userId:l,category:n,tier:u,memoryKey:y||null,stored:String(s).slice(0,100)})}catch(m){throw new Error(`mem0 store failed: ${m.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:m})}}function ye(t,e){let{query:r,category:s,ticketKey:n,tier:o,limit:i=20}=t,a=[];r&&a.push(`content LIKE ${c(`%${r}%`)}`),s&&a.push(`category = ${c(s)}`),n&&a.push(`ticket_key = ${c(n)}`),o&&a.push(`tier = ${c(o)}`);let m=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
70
+ WHERE id = ${c(p.id)}`);try{f(e,["add","."]),f(e,["commit","-m",`memory promote: ${s} \u2014 ${String(r).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:p.id,category:s,tier:R?u:E,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:p.id,category:s,tier:E,deduped:!0,promoted:!1})}let $=C(),ce=process.env.ZIBBY_CHAT_SESSION_ID||null;_(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
71
+ VALUES (${c($)}, ${c(y||null)}, ${c(s)}, ${c(r)}, ${c(n)}, ${c(o)}, ${c(ce)}, ${c(u)}, ${l}, ${c(S())})`);try{f(e,["add","."]),f(e,["commit","-m",`memory: ${s} \u2014 ${r.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:$,category:s,tier:u,memoryKey:y||null,stored:r.slice(0,100)})}function he(t){let e=String(t||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var D=new Map;async function re(t,e){if(typeof t=="boolean")return t;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return he(process.env.ZIBBY_MEM0_INFER);let r=e||process.cwd();if(D.has(r))return D.get(r);let s=!1;try{let n=g(r,".zibby.config.mjs");H(n)&&(s=(await import(T(n).href))?.default?.memory?.infer===!0)}catch{}return D.set(r,s),s}async function Ee(t,e,r){let{content:s,category:n,source:o,ticketKey:i,tier:a,memoryKey:m,infer:u}=t;if(!s||!n)return JSON.stringify({error:"content and category are required"});try{let l=await Q(r),y=X(r),d=K(a,n),p=await re(u,r);return await l.add([{role:"user",content:String(s)}],{userId:y,infer:p,metadata:{memoryKey:m||null,category:n,tier:d,source:o||"zibby-chat",ticketKey:i||null,created_at:S()}}),JSON.stringify({ok:!0,backend:"mem0",userId:y,category:n,tier:d,infer:p,memoryKey:m||null,stored:String(s).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function Se(t,e){let{query:r,category:s,ticketKey:n,tier:o,limit:i=20}=t,a=[];r&&a.push(`content LIKE ${c(`%${r}%`)}`),s&&a.push(`category = ${c(s)}`),n&&a.push(`ticket_key = ${c(n)}`),o&&a.push(`tier = ${c(o)}`);let u=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
72
72
  FROM chat_memory ${a.length>0?`WHERE ${a.join(" AND ")}`:""}
73
73
  ORDER BY relevance DESC, created_at DESC
74
- LIMIT ${i}`,l=g(e,m);return JSON.stringify({total:l.length,memories:l})}async function Q(t,e,r){let{query:s,category:n,ticketKey:o,tier:i,limit:a=20}=t;try{let y=await G(r),m=X(r),l=[];if(s&&String(s).trim()){let u=await y.search(String(s),{userId:m,limit:a});l=x(u)}else{let u=await y.getAll({userId:m,limit:Math.max(a,50)});l=x(u)}return n&&(l=l.filter(u=>u.category===n)),o&&(l=l.filter(u=>u.ticket_key===o)),i&&(l=l.filter(u=>u.tier===i)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(y){throw new Error(`mem0 recall failed: ${y.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:y})}}function Y(t,e){let{ticketKey:r}=t;_e(e);let n=g(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
75
- FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),o=r?`AND ticket_key = ${c(r)}`:"",i=g(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
76
- WHERE tier = 'long' ${o} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=g(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
77
- WHERE tier = 'mid' ${o} ORDER BY relevance DESC, created_at DESC LIMIT 8`),m=g(e,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
78
- GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=Z([...i,...a]);return JSON.stringify({recentSessions:n,topMemories:l,taskStats:m,ticketFilter:r||null})}async function q(t,e,r){let{ticketKey:s}=t,n=await Q({limit:80},e,r),o=JSON.parse(n||"{}"),i=Array.isArray(o.memories)?o.memories:[];s&&(i=i.filter(f=>f.ticket_key===s));let a=f=>{let _=Date.parse(String(f?.created_at||""))||0;return Number(f?.relevance||0)*1e12+_},y=(f,_)=>a(_)-a(f),m=i.filter(f=>f.tier==="long").sort(y).slice(0,10),l=i.filter(f=>f.tier==="mid").sort(y).slice(0,8),u=Z([...m,...l]);return JSON.stringify({recentSessions:[],topMemories:u,taskStats:[],ticketFilter:s||null,backend:"mem0"})}function ue(t,e){let{summary:r,tickets:s,tasksRun:n=0,tasksPassed:o=0,tasksFailed:i=0,keyFacts:a}=t;if(!r)return JSON.stringify({error:"summary is required"});let y=process.env.ZIBBY_CHAT_SESSION_ID||`session_${C()}`;if(p(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
79
- VALUES (${c(y)}, ${c(r)}, ${c(s)}, ${n}, ${o}, ${i}, ${c(a)}, ${c(S())})`),a)for(let m of a.split(";").map(l=>l.trim()).filter(Boolean))P({content:m,category:"fact",source:"session_summary",tier:"mid"},e);fe(e);try{d(e,["add","."]),d(e,["commit","-m",`session end: ${r.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:y,summary:r.slice(0,200)})}function de(t,e){let{title:r,type:s,status:n,ticketKey:o,specPath:i,resultSummary:a}=t;if(!r||!s||!n)return JSON.stringify({error:"title, type, and status are required"});let y=C(),m=process.env.ZIBBY_CHAT_SESSION_ID||null;p(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
80
- VALUES (${c(y)}, ${c(o)}, ${c(s)}, ${c(r)}, ${c(n)}, ${c(i)}, ${c(m)}, ${c(a)}, ${c(S())}, ${c(S())})`);try{d(e,["add","."]),d(e,["commit","-m",`task: ${n} \u2014 ${r.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:y,title:r,type:s,status:n})}function pe(t,e){let{ticketKey:r,type:s,status:n,limit:o=20}=t,i=[];r&&i.push(`ticket_key = ${c(r)}`),s&&i.push(`type = ${c(s)}`),n&&i.push(`status = ${c(n)}`);let y=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
74
+ LIMIT ${i}`,l=h(e,u);return JSON.stringify({total:l.length,memories:l})}async function se(t,e,r){let{query:s,category:n,ticketKey:o,tier:i,limit:a=20}=t;try{let m=await Q(r),u=X(r),l=[];if(s&&String(s).trim()){let y=await m.search(String(s),{filters:{user_id:u},topK:a});l=V(y)}else{let y=await m.getAll({filters:{user_id:u},topK:Math.max(a,50)});l=V(y)}return n&&(l=l.filter(y=>y.category===n)),o&&(l=l.filter(y=>y.ticket_key===o)),i&&(l=l.filter(y=>y.tier===i)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(m){throw new Error(`mem0 recall failed: ${m.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:m})}}function Re(t,e){let{ticketKey:r}=t;Me(e);let n=h(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
75
+ FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),o=r?`AND ticket_key = ${c(r)}`:"",i=h(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
76
+ WHERE tier = 'long' ${o} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=h(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
77
+ WHERE tier = 'mid' ${o} ORDER BY relevance DESC, created_at DESC LIMIT 8`),u=h(e,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
78
+ GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=P([...i,...a]);return JSON.stringify({recentSessions:n,topMemories:l,taskStats:u,ticketFilter:r||null})}async function Ae(t,e,r){let{ticketKey:s}=t,n=await se({limit:80},e,r),o=JSON.parse(n||"{}"),i=Array.isArray(o.memories)?o.memories:[];s&&(i=i.filter(d=>d.ticket_key===s));let a=d=>{let p=Date.parse(String(d?.created_at||""))||0;return Number(d?.relevance||0)*1e12+p},m=(d,p)=>a(p)-a(d),u=i.filter(d=>d.tier==="long").sort(m).slice(0,10),l=i.filter(d=>d.tier==="mid").sort(m).slice(0,8),y=P([...u,...l]);return JSON.stringify({recentSessions:[],topMemories:y,taskStats:[],ticketFilter:s||null,backend:"mem0"})}function ne(t,e){let{summary:r,tickets:s,tasksRun:n=0,tasksPassed:o=0,tasksFailed:i=0,keyFacts:a}=t;if(!r)return JSON.stringify({error:"summary is required"});let m=process.env.ZIBBY_CHAT_SESSION_ID||`session_${C()}`;if(_(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
79
+ VALUES (${c(m)}, ${c(r)}, ${c(s)}, ${n}, ${o}, ${i}, ${c(a)}, ${c(S())})`),a)for(let u of a.split(";").map(l=>l.trim()).filter(Boolean))te({content:u,category:"fact",source:"session_summary",tier:"mid"},e);Te(e);try{f(e,["add","."]),f(e,["commit","-m",`session end: ${r.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:m,summary:r.slice(0,200)})}function oe(t,e){let{title:r,type:s,status:n,ticketKey:o,specPath:i,resultSummary:a}=t;if(!r||!s||!n)return JSON.stringify({error:"title, type, and status are required"});let m=C(),u=process.env.ZIBBY_CHAT_SESSION_ID||null;_(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
80
+ VALUES (${c(m)}, ${c(o)}, ${c(s)}, ${c(r)}, ${c(n)}, ${c(i)}, ${c(u)}, ${c(a)}, ${c(S())}, ${c(S())})`);try{f(e,["add","."]),f(e,["commit","-m",`task: ${n} \u2014 ${r.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m,title:r,type:s,status:n})}function ie(t,e){let{ticketKey:r,type:s,status:n,limit:o=20}=t,i=[];r&&i.push(`ticket_key = ${c(r)}`),s&&i.push(`type = ${c(s)}`),n&&i.push(`status = ${c(n)}`);let m=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
81
81
  FROM chat_tasks ${i.length>0?`WHERE ${i.join(" AND ")}`:""}
82
- ORDER BY created_at DESC LIMIT ${o}`,m=g(e,y);return JSON.stringify({total:m.length,tasks:m})}function fe(t){try{p(t,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),p(t,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),p(t,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),p(t,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function _e(t){try{let e=new Date(Date.now()-864e5).toISOString();p(t,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${c(e)}`)}catch{}}export{Te as _resetInitCache,Ae as chatMemorySkill};
82
+ ORDER BY created_at DESC LIMIT ${o}`,u=h(e,m);return JSON.stringify({total:u.length,tasks:u})}function Te(t){try{_(t,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),_(t,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),_(t,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),_(t,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function Me(t){try{let e=new Date(Date.now()-864e5).toISOString();_(t,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${c(e)}`)}catch{}}export{De as _mem0DbPaths,Oe as _resetInitCache,be as _resolveMem0Config,Be as _resolveMem0Infer,Le as _resolveMemoryAdapter,Fe as chatMemorySkill};
@@ -1,10 +1,10 @@
1
- import{existsSync as S}from"fs";import{fileURLToPath as b}from"url";import{dirname as v,resolve as N}from"path";import{resolveIntegrationToken as O}from"@zibby/core/backend-client.js";var y=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion"}),J=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"}});function w(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let r=v(b(import.meta.url)),e=N(r,"..","bin","mcp-slack.mjs");return S(e)?e:null}async function _(r,e={}){let{token:t}=await O("slack"),s=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(r),n=`https://slack.com/api/${r}`,a={Authorization:`Bearer ${t}`},d;if(s){let l=new URLSearchParams(e).toString();l&&(n+=`?${l}`)}else a["Content-Type"]="application/json; charset=utf-8",d=JSON.stringify(e);let i=await(await fetch(n,{method:s?"GET":"POST",headers:a,body:d})).json();if(!i.ok)throw new Error(`Slack API error: ${i.error}`);return i}var m={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:y.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
1
+ import{existsSync as b}from"fs";import{fileURLToPath as S}from"url";import{dirname as v,resolve as N}from"path";import{resolveIntegrationToken as O}from"@zibby/core/backend-client.js";var y=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",PLANE:"plane"}),J=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"}});function w(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let r=v(S(import.meta.url)),e=N(r,"..","bin","mcp-slack.mjs");return b(e)?e:null}async function _(r,e={}){let{token:t}=await O("slack"),s=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(r),n=`https://slack.com/api/${r}`,a={Authorization:`Bearer ${t}`},d;if(s){let l=new URLSearchParams(e).toString();l&&(n+=`?${l}`)}else a["Content-Type"]="application/json; charset=utf-8",d=JSON.stringify(e);let i=await(await fetch(n,{method:s?"GET":"POST",headers:a,body:d})).json();if(!i.ok)throw new Error(`Slack API error: ${i.error}`);return i}var m={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:y.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
2
2
  You have access to the user's Slack workspace. Use these tools:
3
3
  - slack_list_channels, slack_post_message, slack_reply_to_thread
4
4
  - slack_add_reaction, slack_get_channel_history, slack_get_thread_replies
5
5
  - slack_get_users, slack_get_user_profile
6
6
  - slack_lookup_user_by_email (precise email\u2192user_id, prefer this over scanning slack_get_users)
7
- - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=w();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 _("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(t.channels||[]).map(s=>({id:s.id,name:s.name,topic:s.topic?.value}))})}case"slack_post_message":{if(!e.channel||!e.text)return JSON.stringify({error:"channel and text are required"});let t=await _("chat.postMessage",{channel:e.channel,text:e.text});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 _("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 _("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 _("conversations.history",{channel:e.channel,limit:e.limit||20});return JSON.stringify({messages:(t.messages||[]).map(s=>({user:s.user,text:s.text,ts:s.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 _("conversations.replies",{channel:e.channel,ts:e.thread_ts});return JSON.stringify({messages:(t.messages||[]).map(s=>({user:s.user,text:s.text,ts:s.ts}))})}case"slack_get_users":{let t=await _("users.list",{limit:100});return JSON.stringify({users:(t.members||[]).filter(s=>!s.is_bot&&!s.deleted).map(s=>({id:s.id,name:s.real_name||s.name}))})}case"slack_get_user_profile":{if(!e.user_id)return JSON.stringify({error:"user_id is required"});let t=await _("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 _("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 _("usergroups.list",{});return JSON.stringify({usergroups:(t.usergroups||[]).map(s=>({id:s.id,handle:s.handle,name:s.name,description:s.description||"",user_count:Number(s.user_count||0)}))})}case"slack_get_usergroup_members":{if(!e.usergroup)return JSON.stringify({error:"usergroup id is required"});let t=await _("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 s=Math.max(1,Math.min(Number(e.limit)||5,25)),n=[],a,d=5;for(let i=0;i<d;i+=1){let l={limit:200};a&&(l.cursor=a);let c=await _("users.list",l);for(let o of c.members||[])o.deleted||o.is_bot||n.push(o);if(a=c.response_metadata?.next_cursor,!a)break}let u=[];for(let i of n){let l=(i.real_name||"").toLowerCase(),c=(i.profile?.display_name||"").toLowerCase(),o=(i.name||"").toLowerCase(),p=0;l.includes(t)&&(p+=100-Math.abs(l.length-t.length)),c.includes(t)&&(p+=60-Math.abs(c.length-t.length)),o.includes(t)&&(p+=30-Math.abs(o.length-t.length)),(l===t||c===t)&&(p+=200),p>0&&u.push({id:i.id,name:i.real_name||i.profile?.display_name||i.name,email:i.profile?.email||void 0,_score:p})}return u.sort((i,l)=>l._score-i._score),JSON.stringify({ok:!0,matches:u.slice(0,s).map(({_score:i,...l})=>l),scanned:n.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",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Message text"}},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 I}from"fs";import{fileURLToPath as T}from"url";import{dirname as A,resolve as C}from"path";import{resolveIntegrationToken as L}from"@zibby/core/backend-client.js";function E(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=A(T(import.meta.url)),e=C(r,"..","bin","mcp-lark.mjs");return I(e)?e:null}var R=6e3*1e3,g=null;async function x(){let{appId:r,appSecret:e,host:t}=await L("lark");if(g&&g.appId===r&&g.expiresAt>Date.now())return{token:g.token,host:t};let n=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(n.code!==0)throw new Error(`Lark tenant_access_token failed: ${n.msg||n.code}`);return g={token:n.tenant_access_token,expiresAt:Date.now()+R,appId:r},{token:n.tenant_access_token,host:t}}async function f(r,e,t={}){let{token:s,host:n}=await x(),a=`${n}${e}`,d={method:r,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(d.body=JSON.stringify(t));let i=await(await fetch(a,d)).json();if(i.code!==0)throw new Error(`Lark API ${e} error: ${i.msg||i.code}`);return i.data||{}}function k(r){return JSON.stringify({text:r})}function P(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 h={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:y.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
7
+ - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let r=w();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 _("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(t.channels||[]).map(s=>({id:s.id,name:s.name,topic:s.topic?.value}))})}case"slack_post_message":{if(!e.channel||!e.text)return JSON.stringify({error:"channel and text are required"});let t=await _("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 _("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 _("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 _("conversations.history",{channel:e.channel,limit:e.limit||20});return JSON.stringify({messages:(t.messages||[]).map(s=>({user:s.user,text:s.text,ts:s.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 _("conversations.replies",{channel:e.channel,ts:e.thread_ts});return JSON.stringify({messages:(t.messages||[]).map(s=>({user:s.user,text:s.text,ts:s.ts}))})}case"slack_get_users":{let t=await _("users.list",{limit:100});return JSON.stringify({users:(t.members||[]).filter(s=>!s.is_bot&&!s.deleted).map(s=>({id:s.id,name:s.real_name||s.name}))})}case"slack_get_user_profile":{if(!e.user_id)return JSON.stringify({error:"user_id is required"});let t=await _("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 _("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 _("usergroups.list",{});return JSON.stringify({usergroups:(t.usergroups||[]).map(s=>({id:s.id,handle:s.handle,name:s.name,description:s.description||"",user_count:Number(s.user_count||0)}))})}case"slack_get_usergroup_members":{if(!e.usergroup)return JSON.stringify({error:"usergroup id is required"});let t=await _("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 s=Math.max(1,Math.min(Number(e.limit)||5,25)),n=[],a,d=5;for(let i=0;i<d;i+=1){let l={limit:200};a&&(l.cursor=a);let c=await _("users.list",l);for(let o of c.members||[])o.deleted||o.is_bot||n.push(o);if(a=c.response_metadata?.next_cursor,!a)break}let u=[];for(let i of n){let l=(i.real_name||"").toLowerCase(),c=(i.profile?.display_name||"").toLowerCase(),o=(i.name||"").toLowerCase(),p=0;l.includes(t)&&(p+=100-Math.abs(l.length-t.length)),c.includes(t)&&(p+=60-Math.abs(c.length-t.length)),o.includes(t)&&(p+=30-Math.abs(o.length-t.length)),(l===t||c===t)&&(p+=200),p>0&&u.push({id:i.id,name:i.real_name||i.profile?.display_name||i.name,email:i.profile?.email||void 0,_score:p})}return u.sort((i,l)=>l._score-i._score),JSON.stringify({ok:!0,matches:u.slice(0,s).map(({_score:i,...l})=>l),scanned:n.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 I}from"fs";import{fileURLToPath as T}from"url";import{dirname as A,resolve as C}from"path";import{resolveIntegrationToken as L}from"@zibby/core/backend-client.js";function E(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let r=A(T(import.meta.url)),e=C(r,"..","bin","mcp-lark.mjs");return I(e)?e:null}var R=6e3*1e3,g=null;async function x(){let{appId:r,appSecret:e,host:t}=await L("lark");if(g&&g.appId===r&&g.expiresAt>Date.now())return{token:g.token,host:t};let n=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:r,app_secret:e})})).json();if(n.code!==0)throw new Error(`Lark tenant_access_token failed: ${n.msg||n.code}`);return g={token:n.tenant_access_token,expiresAt:Date.now()+R,appId:r},{token:n.tenant_access_token,host:t}}async function f(r,e,t={}){let{token:s,host:n}=await x(),a=`${n}${e}`,d={method:r,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json; charset=utf-8"}};r!=="GET"&&(d.body=JSON.stringify(t));let i=await(await fetch(a,d)).json();if(i.code!==0)throw new Error(`Lark API ${e} error: ${i.msg||i.code}`);return i.data||{}}function k(r){return JSON.stringify({text:r})}function P(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 h={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:y.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
8
8
  You can send messages and replies on Lark. Use:
9
9
  - lark_send_message: post a message to a chat, user, or DM
10
10
  - lark_reply: reply to an existing message (threaded)
package/dist/github.js CHANGED
@@ -1,4 +1,4 @@
1
- import{resolveIntegrationToken as R}from"@zibby/core/backend-client.js";var S=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion"}),N=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"}});async function d(g,n={}){let{token:t}=await R("github"),o=g.startsWith("https://")?g:`https://api.github.com${g}`,i={Authorization:`Bearer ${t}`,Accept:n.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...n.body?{"Content-Type":"application/json"}:{}},e=await fetch(o,{method:n.method||"GET",headers:i,body:n.body?JSON.stringify(n.body):void 0});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`GitHub API ${e.status}: ${r.slice(0,300)}`)}return n.raw?e.text():e.json()}var J={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:S.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
1
+ import{resolveIntegrationToken as R}from"@zibby/core/backend-client.js";var S=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",PLANE:"plane"}),N=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"}});async function c(h,a={}){let{token:t}=await R("github"),i=h.startsWith("https://")?h:`https://api.github.com${h}`,r={Authorization:`Bearer ${t}`,Accept:a.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...a.body?{"Content-Type":"application/json"}:{}},e=await fetch(i,{method:a.method||"GET",headers:r,body:a.body?JSON.stringify(a.body):void 0});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`GitHub API ${e.status}: ${s.slice(0,300)}`)}return a.raw?e.text():e.json()}var v={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:S.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
2
2
  You have access to the user's GitHub repositories. Available tools:
3
3
 
4
4
  ### Discovery
@@ -21,6 +21,12 @@ You have access to the user's GitHub repositories. Available tools:
21
21
  - github_list_pr_files: List PR changed files
22
22
  - github_list_pr_comments: Get PR comments
23
23
  - github_create_issue: Create new issue
24
+ - github_list_issues: List issues in a repo (filter by state/labels/since cursor) \u2014 excludes PRs
25
+ - github_get_issue: Get a single issue's full detail (title, body, state, labels, assignee, url)
26
+ - github_get_issue_comments: Get the comment thread on an issue
27
+ - github_add_issue_comment: Add a comment to an issue (also used to record a PR link)
28
+ - github_close_issue / github_reopen_issue: Close (optionally completed/not_planned) or reopen an issue
29
+ - github_label_issue: Add / set / remove labels on an issue
24
30
 
25
31
  ### Important: "Check out" / "Clone"
26
32
  When user says "check out repo-name" or "clone repo-name":
@@ -29,6 +35,6 @@ When user says "check out repo-name" or "clone repo-name":
29
35
  3. STOP. Do not offer to inspect files or ask what to do next.
30
36
 
31
37
  When user just wants to "look at" or "read" files (not clone):
32
- - Use github_get_file to read individual files via API`,resolve(){let g={};for(let n of this.envKeys)process.env[n]&&(g[n]=process.env[n]);return{command:"npx",args:["-y","@modelcontextprotocol/server-github@latest"],env:g}},async handleToolCall(g,n){try{switch(g){case"github_search_issues":{let t=n.query;if(!t)return JSON.stringify({error:"query is required"});let o=await d(`/search/issues?q=${encodeURIComponent(t)}&per_page=${n.limit||20}`),i=(o.items||[]).map(e=>({number:e.number,title:e.title,state:e.state,repo:e.repository_url?.split("/").slice(-2).join("/"),url:e.html_url,user:e.user?.login,isPR:!!e.pull_request,labels:(e.labels||[]).map(r=>r.name),createdAt:e.created_at}));return JSON.stringify({total:o.total_count,items:i})}case"github_search_code":{let t=n.query;if(!t)return JSON.stringify({error:"query is required"});let o=n.repo?`+repo:${n.repo}`:"",i=n.language?`+language:${n.language}`:"",e=await d(`/search/code?q=${encodeURIComponent(t)}${o}${i}&per_page=${n.limit||15}`),r=(e.items||[]).map(s=>({name:s.name,path:s.path,repo:s.repository?.full_name,url:s.html_url,score:s.score}));return JSON.stringify({total:e.total_count,items:r})}case"github_get_pr":{let{owner:t,repo:o,number:i}=n;if(!t||!o||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await d(`/repos/${t}/${o}/pulls/${i}`);return JSON.stringify({number:e.number,title:e.title,state:e.state,merged:e.merged,body:e.body?.slice(0,5e3),user:e.user?.login,branch:e.head?.ref,base:e.base?.ref,changedFiles:e.changed_files,additions:e.additions,deletions:e.deletions,createdAt:e.created_at,mergedAt:e.merged_at,url:e.html_url,labels:(e.labels||[]).map(r=>r.name)})}case"github_get_pr_diff":{let{owner:t,repo:o,number:i}=n;if(!t||!o||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await d(`/repos/${t}/${o}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),r=e.length>15e3;return JSON.stringify({number:i,diff:r?e.slice(0,15e3):e,truncated:r,totalLength:e.length})}case"github_list_pr_files":{let{owner:t,repo:o,number:i}=n;if(!t||!o||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await d(`/repos/${t}/${o}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:e.length,files:e.map(r=>({filename:r.filename,status:r.status,additions:r.additions,deletions:r.deletions,patch:r.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:o,number:i}=n;if(!t||!o||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await d(`/repos/${t}/${o}/pulls/${i}/comments?per_page=50`),r=await d(`/repos/${t}/${o}/issues/${i}/comments?per_page=50`),s=[...e.map(a=>({type:"review",user:a.user?.login,body:a.body?.slice(0,1e3),path:a.path,line:a.line,createdAt:a.created_at})),...r.map(a=>({type:"issue",user:a.user?.login,body:a.body?.slice(0,1e3),createdAt:a.created_at}))].sort((a,p)=>new Date(a.createdAt)-new Date(p.createdAt));return JSON.stringify({total:s.length,comments:s})}case"github_list_commits":{let{owner:t,repo:o,branch:i,path:e,limit:r}=n;if(!t||!o)return JSON.stringify({error:"owner and repo are required"});let s=`/repos/${t}/${o}/commits?per_page=${r||20}`;i&&(s+=`&sha=${encodeURIComponent(i)}`),e&&(s+=`&path=${encodeURIComponent(e)}`);let a=await d(s);return JSON.stringify({total:a.length,commits:a.map(p=>({sha:p.sha?.slice(0,8),fullSha:p.sha,message:p.commit?.message?.slice(0,300),author:p.commit?.author?.name,date:p.commit?.author?.date,url:p.html_url}))})}case"github_get_commit":{let{owner:t,repo:o,sha:i}=n;if(!t||!o||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let e=await d(`/repos/${t}/${o}/commits/${i}`);return JSON.stringify({sha:e.sha?.slice(0,8),message:e.commit?.message,author:e.commit?.author?.name,date:e.commit?.author?.date,stats:e.stats,files:(e.files||[]).map(r=>({filename:r.filename,status:r.status,additions:r.additions,deletions:r.deletions,patch:r.patch?.slice(0,3e3)}))})}case"github_get_file":{let{owner:t,repo:o,path:i,ref:e}=n;if(!t||!o||!i)return JSON.stringify({error:"owner, repo, and path are required"});let r=`/repos/${t}/${o}/contents/${encodeURIComponent(i)}`;e&&(r+=`?ref=${encodeURIComponent(e)}`);let s=await d(r);if(s.type!=="file")return Array.isArray(s)?JSON.stringify({type:"directory",path:i,entries:s.map(m=>({name:m.name,type:m.type,size:m.size,path:m.path}))}):JSON.stringify({error:`Not a file: ${s.type}`});let a=Buffer.from(s.content||"","base64").toString("utf-8"),p=a.length>2e4;return JSON.stringify({path:s.path,size:s.size,sha:s.sha?.slice(0,8),content:p?a.slice(0,2e4):a,truncated:p})}case"github_get_user":try{let t=await d("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let o=t.repositories[0],i=o.owner.login,e=o.owner.type,r=e==="Organization"?`/orgs/${i}`:`/users/${i}`,s=await d(r);return JSON.stringify({login:s.login,name:s.name||s.login,avatar:s.avatar_url,bio:s.bio||s.description,type:e,isOrg:e==="Organization",publicRepos:s.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 o=(await d("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let r of o)r.owner.type==="Organization"&&(i.has(r.owner.login)||i.set(r.owner.login,{login:r.owner.login,description:null,url:r.owner.url}));let e=Array.from(i.values());return JSON.stringify({count:e.length,orgs:e,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 l=function(y){let b=y.replace(/^~(?=$|\/|\\)/,_);return s(b)},{owner:t,repo:o,destination:i}=n;if(!t||!o)return JSON.stringify({error:"owner and repo are required"});let{execSync:e}=await import("child_process"),{join:r,resolve:s}=await import("path"),{existsSync:a,mkdirSync:p}=await import("fs"),{homedir:m,platform:f}=await import("os"),{token:w}=await R("github"),_=m(),h=i?l(i):r(_,"zibby-repos"),u=r(h,o);if(p(h,{recursive:!0}),a(u))return JSON.stringify({error:`Directory ${u} already exists. Remove it first or use a different destination.`,existingPath:u});try{let y=`https://x-access-token:${w}@github.com/${t}/${o}.git`;e(`git clone ${y} "${u}"`,{stdio:"pipe"});let b=f()==="win32",c;return b?c=e(`dir "${u}"`,{encoding:"utf-8",shell:"cmd.exe"}):c=e(`ls -la "${u}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:u,message:`Cloned ${t}/${o} to ${u}`,contents:c.split(`
38
+ - Use github_get_file to read individual files via API`,resolve(){let h={};for(let a of this.envKeys)process.env[a]&&(h[a]=process.env[a]);return{command:"npx",args:["-y","@modelcontextprotocol/server-github@latest"],env:h}},async handleToolCall(h,a){try{switch(h){case"github_search_issues":{let t=a.query;if(!t)return JSON.stringify({error:"query is required"});let i=await c(`/search/issues?q=${encodeURIComponent(t)}&per_page=${a.limit||20}`),r=(i.items||[]).map(e=>({number:e.number,title:e.title,state:e.state,repo:e.repository_url?.split("/").slice(-2).join("/"),url:e.html_url,user:e.user?.login,isPR:!!e.pull_request,labels:(e.labels||[]).map(s=>s.name),createdAt:e.created_at}));return JSON.stringify({total:i.total_count,items:r})}case"github_search_code":{let t=a.query;if(!t)return JSON.stringify({error:"query is required"});let i=a.repo?`+repo:${a.repo}`:"",r=a.language?`+language:${a.language}`:"",e=await c(`/search/code?q=${encodeURIComponent(t)}${i}${r}&per_page=${a.limit||15}`),s=(e.items||[]).map(n=>({name:n.name,path:n.path,repo:n.repository?.full_name,url:n.html_url,score:n.score}));return JSON.stringify({total:e.total_count,items:s})}case"github_get_pr":{let{owner:t,repo:i,number:r}=a;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await c(`/repos/${t}/${i}/pulls/${r}`);return JSON.stringify({number:e.number,title:e.title,state:e.state,merged:e.merged,body:e.body?.slice(0,5e3),user:e.user?.login,branch:e.head?.ref,base:e.base?.ref,changedFiles:e.changed_files,additions:e.additions,deletions:e.deletions,createdAt:e.created_at,mergedAt:e.merged_at,url:e.html_url,labels:(e.labels||[]).map(s=>s.name)})}case"github_get_pr_diff":{let{owner:t,repo:i,number:r}=a;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await c(`/repos/${t}/${i}/pulls/${r}`,{accept:"application/vnd.github.v3.diff",raw:!0}),s=e.length>15e3;return JSON.stringify({number:r,diff:s?e.slice(0,15e3):e,truncated:s,totalLength:e.length})}case"github_list_pr_files":{let{owner:t,repo:i,number:r}=a;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await c(`/repos/${t}/${i}/pulls/${r}/files?per_page=100`);return JSON.stringify({total:e.length,files:e.map(s=>({filename:s.filename,status:s.status,additions:s.additions,deletions:s.deletions,patch:s.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:i,number:r}=a;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await c(`/repos/${t}/${i}/pulls/${r}/comments?per_page=50`),s=await c(`/repos/${t}/${i}/issues/${r}/comments?per_page=50`),n=[...e.map(o=>({type:"review",user:o.user?.login,body:o.body?.slice(0,1e3),path:o.path,line:o.line,createdAt:o.created_at})),...s.map(o=>({type:"issue",user:o.user?.login,body:o.body?.slice(0,1e3),createdAt:o.created_at}))].sort((o,u)=>new Date(o.createdAt)-new Date(u.createdAt));return JSON.stringify({total:n.length,comments:n})}case"github_list_commits":{let{owner:t,repo:i,branch:r,path:e,limit:s}=a;if(!t||!i)return JSON.stringify({error:"owner and repo are required"});let n=`/repos/${t}/${i}/commits?per_page=${s||20}`;r&&(n+=`&sha=${encodeURIComponent(r)}`),e&&(n+=`&path=${encodeURIComponent(e)}`);let o=await c(n);return JSON.stringify({total:o.length,commits:o.map(u=>({sha:u.sha?.slice(0,8),fullSha:u.sha,message:u.commit?.message?.slice(0,300),author:u.commit?.author?.name,date:u.commit?.author?.date,url:u.html_url}))})}case"github_get_commit":{let{owner:t,repo:i,sha:r}=a;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and sha are required"});let e=await c(`/repos/${t}/${i}/commits/${r}`);return JSON.stringify({sha:e.sha?.slice(0,8),message:e.commit?.message,author:e.commit?.author?.name,date:e.commit?.author?.date,stats:e.stats,files:(e.files||[]).map(s=>({filename:s.filename,status:s.status,additions:s.additions,deletions:s.deletions,patch:s.patch?.slice(0,3e3)}))})}case"github_get_file":{let{owner:t,repo:i,path:r,ref:e}=a;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and path are required"});let s=`/repos/${t}/${i}/contents/${encodeURIComponent(r)}`;e&&(s+=`?ref=${encodeURIComponent(e)}`);let n=await c(s);if(n.type!=="file")return Array.isArray(n)?JSON.stringify({type:"directory",path:r,entries:n.map(d=>({name:d.name,type:d.type,size:d.size,path:d.path}))}):JSON.stringify({error:`Not a file: ${n.type}`});let o=Buffer.from(n.content||"","base64").toString("utf-8"),u=o.length>2e4;return JSON.stringify({path:n.path,size:n.size,sha:n.sha?.slice(0,8),content:u?o.slice(0,2e4):o,truncated:u})}case"github_get_user":try{let t=await c("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let i=t.repositories[0],r=i.owner.login,e=i.owner.type,s=e==="Organization"?`/orgs/${r}`:`/users/${r}`,n=await c(s);return JSON.stringify({login:n.login,name:n.name||n.login,avatar:n.avatar_url,bio:n.bio||n.description,type:e,isOrg:e==="Organization",publicRepos:n.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 i=(await c("/installation/repositories?per_page=100")).repositories||[],r=new Map;for(let s of i)s.owner.type==="Organization"&&(r.has(s.owner.login)||r.set(s.owner.login,{login:s.owner.login,description:null,url:s.owner.url}));let e=Array.from(r.values());return JSON.stringify({count:e.length,orgs:e,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 p=function(f){let w=f.replace(/^~(?=$|\/|\\)/,y);return n(w)},{owner:t,repo:i,destination:r}=a;if(!t||!i)return JSON.stringify({error:"owner and repo are required"});let{execSync:e}=await import("child_process"),{join:s,resolve:n}=await import("path"),{existsSync:o,mkdirSync:u}=await import("fs"),{homedir:d,platform:l}=await import("os"),{token:_}=await R("github"),y=d(),b=r?p(r):s(y,"zibby-repos"),g=s(b,i);if(u(b,{recursive:!0}),o(g))return JSON.stringify({error:`Directory ${g} already exists. Remove it first or use a different destination.`,existingPath:g});try{let f=`https://x-access-token:${_}@github.com/${t}/${i}.git`;e(`git clone ${f} "${g}"`,{stdio:"pipe"});let w=l()==="win32",m;return w?m=e(`dir "${g}"`,{encoding:"utf-8",shell:"cmd.exe"}):m=e(`ls -la "${g}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:g,message:`Cloned ${t}/${i} to ${g}`,contents:m.split(`
33
39
  `).slice(0,30).join(`
34
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(y){return JSON.stringify({error:`Clone failed: ${y.message}`})}}case"github_search_repos":{let{query:t,limit:o}=n;if(!t)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(i);if(e.error)return JSON.stringify(e);let r=t.toLowerCase(),s=e.repos.filter(a=>a.name.toLowerCase().includes(r)||a.fullName.toLowerCase().includes(r)||a.description&&a.description.toLowerCase().includes(r));return JSON.stringify({query:t,count:s.length,repos:s.slice(0,o||20)})}case"github_list_repos":{let{owner:t,type:o,sort:i,direction:e,limit:r}=n,s=100,a=r||200,p=[];if(!t){let l=1,h=!0;for(;h&&p.length<a;){let c=`/installation/repositories?per_page=${s}&page=${l}`,$=(await d(c)).repositories||[];if($.length===0)break;p=p.concat($),h=$.length===s,l++}let u=p.slice(0,a).map(c=>({name:c.name,fullName:c.full_name,private:c.private,description:c.description,language:c.language,defaultBranch:c.default_branch,updatedAt:c.updated_at,stars:c.stargazers_count,url:c.html_url})),y=u.filter(c=>c.private).length,b=u.filter(c=>!c.private).length;return JSON.stringify({count:u.length,repos:u,privateCount:y,publicCount:b,message:`Found ${y} private and ${b} public repos`})}let m=await d(`/orgs/${t}`).then(()=>!0).catch(()=>!1),f=1,w=!0;for(;w&&p.length<a;){let l;m?l=`/orgs/${t}/repos?per_page=${s}&page=${f}&type=${o||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`:l=`/users/${t}/repos?per_page=${s}&page=${f}&type=${o||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`;let h=await d(l),u=Array.isArray(h)?h:[];if(u.length===0)break;p=p.concat(u),w=u.length===s,f++}let _=p.slice(0,a).map(l=>({name:l.name,fullName:l.full_name,private:l.private,description:l.description,language:l.language,defaultBranch:l.default_branch,updatedAt:l.updated_at,stars:l.stargazers_count,url:l.html_url}));return JSON.stringify({count:_.length,repos:_})}case"github_create_issue":{let{owner:t,repo:o,title:i,body:e}=n;if(!t||!o||!i)return JSON.stringify({error:"owner, repo, and title are required"});let r=await d(`/repos/${t}/${o}/issues`,{method:"POST",body:{title:i,body:e||""}});return JSON.stringify({number:r.number,url:r.html_url,title:r.title})}default:return JSON.stringify({error:`Unknown tool: ${g}`})}}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 repositories for a user or org. If no owner given, lists the authenticated user's repos.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list your own repos."},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: 30)"}}}},{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_list_commits",description:"List recent commits on a branch, 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:"Max commits (default: 20)"}},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)"}},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_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"]}}]};export{J as githubSkill};
40
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(f){return JSON.stringify({error:`Clone failed: ${f.message}`})}}case"github_search_repos":{let{query:t,limit:i}=a;if(!t)return JSON.stringify({error:"query is required"});let r=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(r);if(e.error)return JSON.stringify(e);let s=t.toLowerCase(),n=e.repos.filter(o=>o.name.toLowerCase().includes(s)||o.fullName.toLowerCase().includes(s)||o.description&&o.description.toLowerCase().includes(s));return JSON.stringify({query:t,count:n.length,repos:n.slice(0,i||20)})}case"github_list_repos":{let{owner:t,type:i,sort:r,direction:e,limit:s}=a,n=100,o=s||200,u=[];if(!t){let p=1,b=!0;for(;b&&u.length<o;){let m=`/installation/repositories?per_page=${n}&page=${p}`,$=(await c(m)).repositories||[];if($.length===0)break;u=u.concat($),b=$.length===n,p++}let g=u.slice(0,o).map(m=>({name:m.name,fullName:m.full_name,private:m.private,description:m.description,language:m.language,defaultBranch:m.default_branch,updatedAt:m.updated_at,stars:m.stargazers_count,url:m.html_url})),f=g.filter(m=>m.private).length,w=g.filter(m=>!m.private).length;return JSON.stringify({count:g.length,repos:g,privateCount:f,publicCount:w,message:`Found ${f} private and ${w} public repos`})}let d=await c(`/orgs/${t}`).then(()=>!0).catch(()=>!1),l=1,_=!0;for(;_&&u.length<o;){let p;d?p=`/orgs/${t}/repos?per_page=${n}&page=${l}&type=${i||"all"}&sort=${r||"updated"}&direction=${e||"desc"}`:p=`/users/${t}/repos?per_page=${n}&page=${l}&type=${i||"all"}&sort=${r||"updated"}&direction=${e||"desc"}`;let b=await c(p),g=Array.isArray(b)?b:[];if(g.length===0)break;u=u.concat(g),_=g.length===n,l++}let y=u.slice(0,o).map(p=>({name:p.name,fullName:p.full_name,private:p.private,description:p.description,language:p.language,defaultBranch:p.default_branch,updatedAt:p.updated_at,stars:p.stargazers_count,url:p.html_url}));return JSON.stringify({count:y.length,repos:y})}case"github_create_issue":{let{owner:t,repo:i,title:r,body:e}=a;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and title are required"});let s=await c(`/repos/${t}/${i}/issues`,{method:"POST",body:{title:r,body:e||""}});return JSON.stringify({number:s.number,url:s.html_url,title:s.title})}case"github_list_issues":{let{owner:t,repo:i,state:r,labels:e,since:s,assignee:n,sort:o,direction:u,limit:d}=a||{};if(!t||!i)return JSON.stringify({error:"owner and repo are required"});let l=new URLSearchParams;l.set("state",r||"open"),l.set("per_page",String(d||30)),l.set("sort",o||"updated"),l.set("direction",u||"desc"),e&&l.set("labels",Array.isArray(e)?e.join(","):e),s&&l.set("since",s),n&&l.set("assignee",n);let _=await c(`/repos/${t}/${i}/issues?${l.toString()}`),y=(Array.isArray(_)?_:[]).filter(p=>!p.pull_request).map(p=>({number:p.number,title:p.title,state:p.state,labels:(p.labels||[]).map(b=>typeof b=="string"?b:b.name),assignee:p.assignee?.login||null,assignees:(p.assignees||[]).map(b=>b.login),user:p.user?.login,comments:p.comments,url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at}));return JSON.stringify({count:y.length,issues:y})}case"github_get_issue":{let{owner:t,repo:i,number:r}=a||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await c(`/repos/${t}/${i}/issues/${r}`);return e.pull_request?JSON.stringify({error:`#${r} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:e.number,title:e.title,body:e.body||"",state:e.state,stateReason:e.state_reason||null,labels:(e.labels||[]).map(s=>typeof s=="string"?s:s.name),assignee:e.assignee?.login||null,assignees:(e.assignees||[]).map(s=>s.login),user:e.user?.login,milestone:e.milestone?.title||null,comments:e.comments,url:e.html_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:i,number:r,limit:e}=a||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s=await c(`/repos/${t}/${i}/issues/${r}/comments?per_page=${e||100}`),n=(Array.isArray(s)?s:[]).map(o=>({id:o.id,user:o.user?.login,body:o.body||"",createdAt:o.created_at,updatedAt:o.updated_at,url:o.html_url}));return JSON.stringify({count:n.length,comments:n})}case"github_add_issue_comment":{let{owner:t,repo:i,number:r,body:e}=a||{};if(!t||!i||!r||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await c(`/repos/${t}/${i}/issues/${r}/comments`,{method:"POST",body:{body:e}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_close_issue":{let{owner:t,repo:i,number:r,stateReason:e}=a||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s={state:"closed"};e&&(s.state_reason=e);let n=await c(`/repos/${t}/${i}/issues/${r}`,{method:"PATCH",body:s});return JSON.stringify({ok:!0,number:n.number,state:n.state,stateReason:n.state_reason||null,url:n.html_url})}case"github_reopen_issue":{let{owner:t,repo:i,number:r}=a||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await c(`/repos/${t}/${i}/issues/${r}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:e.number,state:e.state,url:e.html_url})}case"github_label_issue":{let{owner:t,repo:i,number:r,labels:e,mode:s}=a||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let n=Array.isArray(e)?e:e?[e]:[];if(!n.length)return JSON.stringify({error:"labels (string or array) is required"});let o=s||"add";if(o==="set"){let d=await c(`/repos/${t}/${i}/issues/${r}`,{method:"PATCH",body:{labels:n}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}if(o==="remove"){for(let l of n)await c(`/repos/${t}/${i}/issues/${r}/labels/${encodeURIComponent(l)}`,{method:"DELETE"});let d=await c(`/repos/${t}/${i}/issues/${r}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}let u=await c(`/repos/${t}/${i}/issues/${r}/labels`,{method:"POST",body:{labels:n}});return JSON.stringify({ok:!0,number:r,labels:(Array.isArray(u)?u:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${h}`})}}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 repositories for a user or org. If no owner given, lists the authenticated user's repos.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list your own repos."},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: 30)"}}}},{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_list_commits",description:"List recent commits on a branch, 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:"Max commits (default: 20)"}},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)"}},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_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"]}}]};export{v as githubSkill};