@zibby/skills 0.1.65 → 0.1.70

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.
@@ -37,6 +37,7 @@ export const INTEGRATIONS: Readonly<{
37
37
  OPEN_DESIGN: "open_design";
38
38
  LINKEDIN_PERSONAL: "linkedin_personal";
39
39
  LINKEDIN_BUSINESS: "linkedin_business";
40
+ DISCORD: "discord";
40
41
  }>;
41
42
  /**
42
43
  * Display metadata. Surface this to humans (modal copy, missing-list
@@ -137,4 +138,9 @@ export const INTEGRATION_REGISTRY: Readonly<{
137
138
  name: string;
138
139
  connectPath: string;
139
140
  };
141
+ discord: {
142
+ id: string;
143
+ name: string;
144
+ connectPath: string;
145
+ };
140
146
  }>;
@@ -1 +1 @@
1
- var n=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business"}),i=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"}});export{n as INTEGRATIONS,i as INTEGRATION_REGISTRY};
1
+ var n=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),i=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});export{n as INTEGRATIONS,i as INTEGRATION_REGISTRY};
package/dist/jira.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire as T}from"module";import{resolveIntegrationToken as P,clearTokenCache as $}from"@zibby/core/backend-client.js";var O=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business"}),U=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"}});var q=T(import.meta.url);function K(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return q.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var C=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function L(c,a){if(!a||!a.length)return c;let e=c;for(let t of a)t.type==="strong"?e=`**${e}**`:t.type==="em"?e=`_${e}_`:t.type==="code"?e=`\`${e}\``:t.type==="strike"?e=`~~${e}~~`:t.type==="link"&&t.attrs?.href&&(e=`[${e}](${t.attrs.href})`);return e}function S(c,a=0){if(!Array.isArray(c))return"";let e=[];for(let t of c){if(t.type==="text"){e.push(L(t.text||"",t.marks));continue}if(t.type==="hardBreak"){e.push(`
1
+ import{createRequire as P}from"module";import{resolveIntegrationToken as T,clearTokenCache as $}from"@zibby/core/backend-client.js";var O=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),U=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var q=P(import.meta.url);function K(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return q.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var C=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function L(c,a){if(!a||!a.length)return c;let e=c;for(let t of a)t.type==="strong"?e=`**${e}**`:t.type==="em"?e=`_${e}_`:t.type==="code"?e=`\`${e}\``:t.type==="strike"?e=`~~${e}~~`:t.type==="link"&&t.attrs?.href&&(e=`[${e}](${t.attrs.href})`);return e}function S(c,a=0){if(!Array.isArray(c))return"";let e=[];for(let t of c){if(t.type==="text"){e.push(L(t.text||"",t.marks));continue}if(t.type==="hardBreak"){e.push(`
2
2
  `);continue}if(t.type==="rule"){e.push(`
3
3
  ---
4
4
  `);continue}let r=t.content?S(t.content,a+1):"";if(t.type==="listItem")e.push(r);else if(t.type==="bulletList"){let i=(t.content||[]).map(o=>`- ${S(o.content||[],a+1).trim()}`);e.push(`
@@ -16,7 +16,7 @@ ${"#".repeat(i)} ${r.trim()}
16
16
  ${r}
17
17
  `):e.push(r)}return e.join("").replace(/\n{3,}/g,`
18
18
 
19
- `)}function k(c){return String(c||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function N(c){return k(c).replace(/[a-z0-9]+/g,"")}function I(c,a){let e=k(c),t=k(a);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let r=p=>{let d=new Map;for(let m=0;m<p.length-1;m++){let g=p.slice(m,m+2);d.set(g,(d.get(g)||0)+1)}return d},i=r(e),o=r(t),s=0,n=0,u=0;for(let p of i.values())n+=p;for(let p of o.values())u+=p;for(let[p,d]of i.entries()){let m=o.get(p)||0;s+=Math.min(d,m)}return 2*s/Math.max(1,n+u)}function b(c){return String(c||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function x(c,a=[]){let e=Array.isArray(a)?a:[];if(e.length===0)return{requested:c||null,resolved:null,strategy:"none"};let t=e.filter(s=>!s.subtask),r=t.length>0?t:e,i=b(c);if(i){let s=r.find(p=>b(p.name)===i);if(s)return{requested:c,resolved:s,strategy:"exact"};let n={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let p of Object.values(n)){if(!p.some(m=>b(m)===i))continue;let d=r.find(m=>p.some(g=>b(g)===b(m.name)));if(d)return{requested:c,resolved:d,strategy:"alias"}}let u=r.map(p=>({t:p,score:I(c,p.name)})).sort((p,d)=>d.score-p.score);if(u[0]&&u[0].score>=.5)return{requested:c,resolved:u[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let s of o){let n=r.find(u=>b(u.name)===s);if(n)return{requested:c||null,resolved:n,strategy:"default-preferred"}}return{requested:c||null,resolved:r[0],strategy:"default-first"}}async function A(c){let a=`projectKeys=${encodeURIComponent(c)}&expand=projects.issuetypes`,e=await f(`/rest/api/3/issue/createmeta?${a}`),t=Array.isArray(e?.projects)?e.projects:[],i=t.find(s=>String(s?.key||"").toUpperCase()===String(c||"").toUpperCase())||t[0]||null;return(Array.isArray(i?.issuetypes)?i.issuetypes:[]).map(s=>({id:s.id,name:s.name,subtask:!!s.subtask,description:s.description||null}))}async function R(c,a){if(!c)throw new Error("projectKey is required");let e="sprint is not EMPTY";a==="active"?e="sprint in openSprints()":a==="closed"?e="sprint in closedSprints()":a==="future"&&(e="sprint in futureSprints()");let t=`project = ${c} AND ${e} ORDER BY updated DESC`,r=`jql=${encodeURIComponent(t)}&maxResults=100&fields=customfield_10020`,i=await f(`/rest/api/3/search/jql?${r}`),o=new Map;for(let s of i.issues||[])for(let n of s.fields?.customfield_10020||[])n&&!o.has(n.id)&&o.set(n.id,{id:n.id,name:n.name,state:n.state,boardId:n.boardId||null,startDate:n.startDate||null,endDate:n.endDate||null,goal:n.goal||null});return[...o.values()].sort((s,n)=>{let u={active:0,future:1,closed:2},p=(u[s.state]??3)-(u[n.state]??3);return p!==0?p:String(n.startDate||"").localeCompare(String(s.startDate||""))})}function D(c,{sprintId:a,sprintName:e,target:t}={}){let r=Array.isArray(c)?c:[];if(!r.length)return{sprint:null,selectedBy:"none"};if(a!=null&&String(a).trim()!=="")return{sprint:r.find(s=>String(s.id)===String(a))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),s=r.find(u=>String(u.name||"").toLowerCase()===o.toLowerCase());if(s)return{sprint:s,selectedBy:"name-exact"};let n=r.map(u=>({s:u,score:I(o,u.name||"")})).sort((u,p)=>p.score-u.score);return n[0]&&n[0].score>=.5?{sprint:n[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let i=String(t||"current").trim().toLowerCase();return i==="active"||i==="current"||i==="latest"?{sprint:r[0],selectedBy:i}:{sprint:r[0],selectedBy:"default"}}function E(c,a){let e=c?.fields?.customfield_10020;return Array.isArray(e)?e.some(t=>String(t?.id)===String(a)):!1}async function B({issueKey:c,projectKey:a,sprintId:e,attempts:t=3,delayMs:r=450}){let i=[];for(let o=0;o<t;o++){try{let s=`project = ${a} AND key = ${c} AND sprint = ${e}`,n=`jql=${encodeURIComponent(s)}&maxResults=1&fields=key,status`,u=await f(`/rest/api/3/search/jql?${n}`);if(Number(u?.total||0)>0)return i.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:i};let d=await f(`/rest/api/3/issue/${c}?fields=customfield_10020,status`),m=E(d,e);if(i.push({attempt:o+1,jql:!1,issueField:m}),m)return{ok:!0,method:"issue_field",traces:i}}catch(s){i.push({attempt:o+1,error:String(s?.message||s)})}o<t-1&&await new Promise(s=>setTimeout(s,r))}return{ok:!1,method:"none",traces:i}}async function w({issueKey:c,projectKey:a,sprintId:e,sprintName:t,target:r}){if(!c)return{ok:!1,error:"issueKey is required"};let i=a;if(!i&&(i=(await f(`/rest/api/3/issue/${c}?fields=project`))?.fields?.project?.key||null,!i))return{ok:!1,error:`Could not resolve project for ${c}`};let o=await R(i,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${i}`};let{sprint:s,selectedBy:n}=D(o,{sprintId:e,sprintName:t,target:r});if(!s)return{ok:!1,error:`No matching sprint found in ${i}`,requested:{sprintId:e??null,sprintName:t??null,target:r??"current"},availableSprints:o.map(d=>({id:d.id,name:d.name,state:d.state}))};await f(`/rest/api/3/issue/${c}`,{method:"PUT",body:{fields:{customfield_10020:Number(s.id)}}});let u=await B({issueKey:c,projectKey:i,sprintId:s.id}),p=u.ok;return{ok:p,issueKey:c,projectKey:i,sprintId:s.id,sprintName:s.name,selectedBy:n,verifiedBy:u.method,verified:p,verificationTrace:u.traces,warning:p?null:`Sprint assignment attempted but verification did not find ${c} in sprint ${s.id}`}}async function f(c,a={}){let e=async()=>{let{token:t,cloudId:r}=await P("jira");if(typeof t!="string"||!t)throw new Error(`Invalid jira token type: ${typeof t}`);if(!r)throw new Error("Invalid jira cloudId: missing");let i=`https://api.atlassian.com/ex/jira/${r}${c}`,o=await fetch(i,{method:a.method||"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...a.body?{"Content-Type":"application/json"}:{},...a.headers},body:a.body?JSON.stringify(a.body):void 0});if(!o.ok){let n=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${n.slice(0,300)}`)}let s=await o.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await e()}catch(t){let r=String(t?.message||t||"").toLowerCase();if(!(r.includes("token")||r.includes("401")||r.includes("403")||r.includes("substring")))throw t;return $("jira"),e()}}var z={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:O.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
19
+ `)}function k(c){return String(c||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function N(c){return k(c).replace(/[a-z0-9]+/g,"")}function I(c,a){let e=k(c),t=k(a);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let r=p=>{let d=new Map;for(let m=0;m<p.length-1;m++){let g=p.slice(m,m+2);d.set(g,(d.get(g)||0)+1)}return d},i=r(e),o=r(t),s=0,n=0,u=0;for(let p of i.values())n+=p;for(let p of o.values())u+=p;for(let[p,d]of i.entries()){let m=o.get(p)||0;s+=Math.min(d,m)}return 2*s/Math.max(1,n+u)}function b(c){return String(c||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function x(c,a=[]){let e=Array.isArray(a)?a:[];if(e.length===0)return{requested:c||null,resolved:null,strategy:"none"};let t=e.filter(s=>!s.subtask),r=t.length>0?t:e,i=b(c);if(i){let s=r.find(p=>b(p.name)===i);if(s)return{requested:c,resolved:s,strategy:"exact"};let n={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let p of Object.values(n)){if(!p.some(m=>b(m)===i))continue;let d=r.find(m=>p.some(g=>b(g)===b(m.name)));if(d)return{requested:c,resolved:d,strategy:"alias"}}let u=r.map(p=>({t:p,score:I(c,p.name)})).sort((p,d)=>d.score-p.score);if(u[0]&&u[0].score>=.5)return{requested:c,resolved:u[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let s of o){let n=r.find(u=>b(u.name)===s);if(n)return{requested:c||null,resolved:n,strategy:"default-preferred"}}return{requested:c||null,resolved:r[0],strategy:"default-first"}}async function A(c){let a=`projectKeys=${encodeURIComponent(c)}&expand=projects.issuetypes`,e=await f(`/rest/api/3/issue/createmeta?${a}`),t=Array.isArray(e?.projects)?e.projects:[],i=t.find(s=>String(s?.key||"").toUpperCase()===String(c||"").toUpperCase())||t[0]||null;return(Array.isArray(i?.issuetypes)?i.issuetypes:[]).map(s=>({id:s.id,name:s.name,subtask:!!s.subtask,description:s.description||null}))}async function R(c,a){if(!c)throw new Error("projectKey is required");let e="sprint is not EMPTY";a==="active"?e="sprint in openSprints()":a==="closed"?e="sprint in closedSprints()":a==="future"&&(e="sprint in futureSprints()");let t=`project = ${c} AND ${e} ORDER BY updated DESC`,r=`jql=${encodeURIComponent(t)}&maxResults=100&fields=customfield_10020`,i=await f(`/rest/api/3/search/jql?${r}`),o=new Map;for(let s of i.issues||[])for(let n of s.fields?.customfield_10020||[])n&&!o.has(n.id)&&o.set(n.id,{id:n.id,name:n.name,state:n.state,boardId:n.boardId||null,startDate:n.startDate||null,endDate:n.endDate||null,goal:n.goal||null});return[...o.values()].sort((s,n)=>{let u={active:0,future:1,closed:2},p=(u[s.state]??3)-(u[n.state]??3);return p!==0?p:String(n.startDate||"").localeCompare(String(s.startDate||""))})}function D(c,{sprintId:a,sprintName:e,target:t}={}){let r=Array.isArray(c)?c:[];if(!r.length)return{sprint:null,selectedBy:"none"};if(a!=null&&String(a).trim()!=="")return{sprint:r.find(s=>String(s.id)===String(a))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),s=r.find(u=>String(u.name||"").toLowerCase()===o.toLowerCase());if(s)return{sprint:s,selectedBy:"name-exact"};let n=r.map(u=>({s:u,score:I(o,u.name||"")})).sort((u,p)=>p.score-u.score);return n[0]&&n[0].score>=.5?{sprint:n[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let i=String(t||"current").trim().toLowerCase();return i==="active"||i==="current"||i==="latest"?{sprint:r[0],selectedBy:i}:{sprint:r[0],selectedBy:"default"}}function E(c,a){let e=c?.fields?.customfield_10020;return Array.isArray(e)?e.some(t=>String(t?.id)===String(a)):!1}async function B({issueKey:c,projectKey:a,sprintId:e,attempts:t=3,delayMs:r=450}){let i=[];for(let o=0;o<t;o++){try{let s=`project = ${a} AND key = ${c} AND sprint = ${e}`,n=`jql=${encodeURIComponent(s)}&maxResults=1&fields=key,status`,u=await f(`/rest/api/3/search/jql?${n}`);if(Number(u?.total||0)>0)return i.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:i};let d=await f(`/rest/api/3/issue/${c}?fields=customfield_10020,status`),m=E(d,e);if(i.push({attempt:o+1,jql:!1,issueField:m}),m)return{ok:!0,method:"issue_field",traces:i}}catch(s){i.push({attempt:o+1,error:String(s?.message||s)})}o<t-1&&await new Promise(s=>setTimeout(s,r))}return{ok:!1,method:"none",traces:i}}async function w({issueKey:c,projectKey:a,sprintId:e,sprintName:t,target:r}){if(!c)return{ok:!1,error:"issueKey is required"};let i=a;if(!i&&(i=(await f(`/rest/api/3/issue/${c}?fields=project`))?.fields?.project?.key||null,!i))return{ok:!1,error:`Could not resolve project for ${c}`};let o=await R(i,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${i}`};let{sprint:s,selectedBy:n}=D(o,{sprintId:e,sprintName:t,target:r});if(!s)return{ok:!1,error:`No matching sprint found in ${i}`,requested:{sprintId:e??null,sprintName:t??null,target:r??"current"},availableSprints:o.map(d=>({id:d.id,name:d.name,state:d.state}))};await f(`/rest/api/3/issue/${c}`,{method:"PUT",body:{fields:{customfield_10020:Number(s.id)}}});let u=await B({issueKey:c,projectKey:i,sprintId:s.id}),p=u.ok;return{ok:p,issueKey:c,projectKey:i,sprintId:s.id,sprintName:s.name,selectedBy:n,verifiedBy:u.method,verified:p,verificationTrace:u.traces,warning:p?null:`Sprint assignment attempted but verification did not find ${c} in sprint ${s.id}`}}async function f(c,a={}){let e=async()=>{let{token:t,cloudId:r}=await T("jira");if(typeof t!="string"||!t)throw new Error(`Invalid jira token type: ${typeof t}`);if(!r)throw new Error("Invalid jira cloudId: missing");let i=`https://api.atlassian.com/ex/jira/${r}${c}`,o=await fetch(i,{method:a.method||"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...a.body?{"Content-Type":"application/json"}:{},...a.headers},body:a.body?JSON.stringify(a.body):void 0});if(!o.ok){let n=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${n.slice(0,300)}`)}let s=await o.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await e()}catch(t){let r=String(t?.message||t||"").toLowerCase();if(!(r.includes("token")||r.includes("401")||r.includes("403")||r.includes("substring")))throw t;return $("jira"),e()}}var z={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:O.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
20
20
  You have direct access to the user's Jira. Use these tools proactively:
21
21
 
22
22
  ### Issue tools
package/dist/lark.js CHANGED
@@ -1,4 +1,4 @@
1
- import{existsSync as f}from"fs";import{fileURLToPath as y}from"url";import{dirname as k,resolve as b}from"path";import{resolveIntegrationToken as v}from"@zibby/core/backend-client.js";var u=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business"}),T=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"}});function I(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let i=k(y(import.meta.url)),e=b(i,"..","bin","mcp-lark.mjs");return f(e)?e:null}var N=6e3*1e3,p=null;async function S(){let{appId:i,appSecret:e,host:t}=await v("lark");if(p&&p.appId===i&&p.expiresAt>Date.now())return{token:p.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:i,app_secret:e})})).json();if(n.code!==0)throw new Error(`Lark tenant_access_token failed: ${n.msg||n.code}`);return p={token:n.tenant_access_token,expiresAt:Date.now()+N,appId:i},{token:n.tenant_access_token,host:t}}async function _(i,e,t={}){let{token:a,host:n}=await S(),r=`${n}${e}`,m={method:i,headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json; charset=utf-8"}};i!=="GET"&&(m.body=JSON.stringify(t));let c=await(await fetch(r,m)).json();if(c.code!==0)throw new Error(`Lark API ${e} error: ${c.msg||c.code}`);return c.data||{}}function g(i){return JSON.stringify({text:i})}function O(i){return!i||typeof i!="string"||i.startsWith("oc_")?"chat_id":i.startsWith("ou_")?"open_id":i.startsWith("on_")?"union_id":i.startsWith("cli_")?"app_id":i.includes("@")?"email":"chat_id"}var x={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:u.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
1
+ import{existsSync as f}from"fs";import{fileURLToPath as y}from"url";import{dirname as k,resolve as b}from"path";import{resolveIntegrationToken as v}from"@zibby/core/backend-client.js";var u=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),T=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function I(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let i=k(y(import.meta.url)),e=b(i,"..","bin","mcp-lark.mjs");return f(e)?e:null}var N=6e3*1e3,p=null;async function S(){let{appId:i,appSecret:e,host:t}=await v("lark");if(p&&p.appId===i&&p.expiresAt>Date.now())return{token:p.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:i,app_secret:e})})).json();if(n.code!==0)throw new Error(`Lark tenant_access_token failed: ${n.msg||n.code}`);return p={token:n.tenant_access_token,expiresAt:Date.now()+N,appId:i},{token:n.tenant_access_token,host:t}}async function _(i,e,t={}){let{token:a,host:n}=await S(),r=`${n}${e}`,m={method:i,headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json; charset=utf-8"}};i!=="GET"&&(m.body=JSON.stringify(t));let c=await(await fetch(r,m)).json();if(c.code!==0)throw new Error(`Lark API ${e} error: ${c.msg||c.code}`);return c.data||{}}function g(i){return JSON.stringify({text:i})}function O(i){return!i||typeof i!="string"||i.startsWith("oc_")?"chat_id":i.startsWith("ou_")?"open_id":i.startsWith("on_")?"union_id":i.startsWith("cli_")?"app_id":i.includes("@")?"email":"chat_id"}var x={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:u.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
2
2
  You can send messages and replies on Lark. Use:
3
3
  - lark_send_message: post a message to a chat, user, or DM
4
4
  - lark_reply: reply to an existing message (threaded)
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Derive the human-facing doc web URL from the open-api host + document id.
3
+ * The open-api host (open.feishu.cn / open.larksuite.com) is region-specific;
4
+ * the web doc lives on the corresponding product domain. This is a best-effort
5
+ * canonical URL — a tenant with a vanity subdomain may render its own host, but
6
+ * the product-domain URL still resolves for the user.
7
+ */
8
+ export function docWebUrl(host: any, id: any): string;
9
+ /**
10
+ * Parse a Lark/Feishu doc reference (raw token OR URL) into { type, token }.
11
+ * - .../docx/<token> → { type:'docx', token }
12
+ * - .../wiki/<token> → { type:'wiki', token } (resolved to its docx obj_token)
13
+ * - bare token → { type:'docx', token }
14
+ * Returns null when nothing usable can be extracted. Pure + side-effect-free.
15
+ */
16
+ export function parseLarkDocRef(ref: any): {
17
+ type: string;
18
+ token: string;
19
+ };
20
+ /**
21
+ * Map a small, common subset of markdown into Lark Docx block objects.
22
+ * Each block is a single line: headings (#/##/### → heading1/2/3), bullets
23
+ * (- / *), ordered (1.), everything else a text paragraph. Inline marks are
24
+ * kept as literal text (content is preserved; we don't emit Lark text-element
25
+ * styles — honest + robust). Empty lines are skipped (Lark rejects empty text
26
+ * blocks). Bounded by the caller's chunking to MAX_BLOCK_CHILDREN per request.
27
+ */
28
+ export function markdownToLarkBlocks(markdown: any): {
29
+ [x: string]: number | {
30
+ elements: {
31
+ text_run: {
32
+ content: string;
33
+ };
34
+ }[];
35
+ style: {};
36
+ };
37
+ block_type: number;
38
+ }[];
39
+ export function _resetLarkDocsTokenCache(): void;
40
+ export namespace larkDocsSkill {
41
+ let id: string;
42
+ let serverName: string;
43
+ let allowedTools: string[];
44
+ let requiresIntegration: "lark";
45
+ let description: string;
46
+ let envKeys: any[];
47
+ let promptFragment: string;
48
+ /**
49
+ * Spawn the GENERIC skill MCP server (bin/mcp-skill.mjs) pointing at this
50
+ * module's larkDocsSkill export, so the AGENT gets real mcp__larkdocs__*
51
+ * tools. Auth flows through the INHERITED env (PROJECT_API_TOKEN →
52
+ * resolveIntegrationToken('lark')), so no provider-specific env keys are
53
+ * needed here. When unconnected, handleToolCall returns { ok:false, error }.
54
+ */
55
+ function resolve(): {
56
+ type: string;
57
+ command: string;
58
+ args: any[];
59
+ env: {};
60
+ description: string;
61
+ alwaysLoad: boolean;
62
+ };
63
+ function handleToolCall(name: any, args: any): Promise<string>;
64
+ let tools: ({
65
+ name: string;
66
+ description: string;
67
+ input_schema: {
68
+ type: string;
69
+ properties: {
70
+ documentId: {
71
+ type: string;
72
+ description: string;
73
+ };
74
+ title?: undefined;
75
+ markdown?: undefined;
76
+ text?: undefined;
77
+ folderToken?: undefined;
78
+ fileType?: undefined;
79
+ commentId?: undefined;
80
+ };
81
+ required: string[];
82
+ };
83
+ } | {
84
+ name: string;
85
+ description: string;
86
+ input_schema: {
87
+ type: string;
88
+ properties: {
89
+ title: {
90
+ type: string;
91
+ description: string;
92
+ };
93
+ markdown: {
94
+ type: string;
95
+ description: string;
96
+ };
97
+ text: {
98
+ type: string;
99
+ description: string;
100
+ };
101
+ folderToken: {
102
+ type: string;
103
+ description: string;
104
+ };
105
+ documentId?: undefined;
106
+ fileType?: undefined;
107
+ commentId?: undefined;
108
+ };
109
+ required: string[];
110
+ };
111
+ } | {
112
+ name: string;
113
+ description: string;
114
+ input_schema: {
115
+ type: string;
116
+ properties: {
117
+ documentId: {
118
+ type: string;
119
+ description: string;
120
+ };
121
+ markdown: {
122
+ type: string;
123
+ description: string;
124
+ };
125
+ text: {
126
+ type: string;
127
+ description: string;
128
+ };
129
+ title?: undefined;
130
+ folderToken?: undefined;
131
+ fileType?: undefined;
132
+ commentId?: undefined;
133
+ };
134
+ required: string[];
135
+ };
136
+ } | {
137
+ name: string;
138
+ description: string;
139
+ input_schema: {
140
+ type: string;
141
+ properties: {
142
+ documentId: {
143
+ type: string;
144
+ description: string;
145
+ };
146
+ fileType: {
147
+ type: string;
148
+ description: string;
149
+ };
150
+ title?: undefined;
151
+ markdown?: undefined;
152
+ text?: undefined;
153
+ folderToken?: undefined;
154
+ commentId?: undefined;
155
+ };
156
+ required: string[];
157
+ };
158
+ } | {
159
+ name: string;
160
+ description: string;
161
+ input_schema: {
162
+ type: string;
163
+ properties: {
164
+ documentId: {
165
+ type: string;
166
+ description: string;
167
+ };
168
+ text: {
169
+ type: string;
170
+ description: string;
171
+ };
172
+ fileType: {
173
+ type: string;
174
+ description: string;
175
+ };
176
+ title?: undefined;
177
+ markdown?: undefined;
178
+ folderToken?: undefined;
179
+ commentId?: undefined;
180
+ };
181
+ required: string[];
182
+ };
183
+ } | {
184
+ name: string;
185
+ description: string;
186
+ input_schema: {
187
+ type: string;
188
+ properties: {
189
+ documentId: {
190
+ type: string;
191
+ description: string;
192
+ };
193
+ commentId: {
194
+ type: string;
195
+ description: string;
196
+ };
197
+ text: {
198
+ type: string;
199
+ description: string;
200
+ };
201
+ fileType: {
202
+ type: string;
203
+ description: string;
204
+ };
205
+ title?: undefined;
206
+ markdown?: undefined;
207
+ folderToken?: undefined;
208
+ };
209
+ required: string[];
210
+ };
211
+ })[];
212
+ }
@@ -0,0 +1,11 @@
1
+ import{existsSync as b}from"fs";import{fileURLToPath as S}from"url";import{dirname as v,resolve as R}from"path";import{resolveIntegrationToken as A}from"@zibby/core/backend-client.js";var g=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),C=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function N(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let t=v(S(import.meta.url)),e=R(t,"..","bin","mcp-skill.mjs");return b(e)?e:null}var I=2e4,x=50,O=6e3*1e3,u=null;async function E(){let{appId:t,appSecret:e,host:n}=await A("lark");if(u&&u.appId===t&&u.expiresAt>Date.now())return{token:u.token,host:n};let o=await(await fetch(`${n}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:t,app_secret:e})})).json();if(o.code!==0)throw new Error(`Lark tenant_access_token failed: ${o.msg||o.code}`);return u={token:o.tenant_access_token,expiresAt:Date.now()+O,appId:t},{token:o.tenant_access_token,host:n}}async function l(t,e,n){let{token:r,host:o}=await E(),i={method:t,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}};t!=="GET"&&n!==void 0&&(i.body=JSON.stringify(n));let c=await(await fetch(`${o}${e}`,i)).json();if(c.code!==0)throw new Error(`Lark Docx API ${e} error: ${c.msg||c.code}`);return{data:c.data||{},host:o}}function h(t,e){return String(t||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function m(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e)return null;let n=e.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return n?{type:n[1],token:n[2]}:/^[A-Za-z0-9]{10,}$/.test(e)?{type:"docx",token:e}:null}async function k(t){let e=typeof t=="string"?m(t):t;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:n}=await l("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),r=n?.node||{};if(r.obj_type!=="docx"||!r.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${r.obj_type||"unknown"})`);return r.obj_token}function L(t){let e=String(t??"").replace(/\r\n/g,`
2
+ `),n=[];for(let r of e.split(`
3
+ `)){let o=r.replace(/\s+$/,"");if(!o.trim())continue;let i=/^(#{1,3})\s+(.*)$/.exec(o),s=/^\s*[-*]\s+(.*)$/.exec(o),c=/^\s*\d+[.)]\s+(.*)$/.exec(o),a,d,p;if(i){let _=i[1].length;a=`heading${_}`,d=2+_,p=i[2]}else s?(a="bullet",d=12,p=s[1]):c?(a="ordered",d=13,p=c[1]):(a="text",d=2,p=o);n.push({block_type:d,[a]:{elements:[{text_run:{content:p}}],style:{}}})}return n}function f(t){let e=typeof t?.markdown=="string"?t.markdown:null,n=typeof t?.text=="string"?t.text:null;return e??n}async function w(t,e){let n;for(let r=0;r<e.length;r+=x){let o=e.slice(r,r+x);n=(await l("POST",`/open-apis/docx/v1/documents/${t}/blocks/${t}/children?document_revision_id=-1`,{children:o})).host}return n}var P="docx",U=50;function T(t){return[{type:"text_run",text_run:{text:String(t??"")}}]}function D(t){return Array.isArray(t)?t.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function $(t){let e=Array.isArray(t?.reply_list?.replies)?t.reply_list.replies:[];return{commentId:t?.comment_id||"",resolved:!!t?.is_solved,replies:e.map(n=>({replyId:n?.reply_id||"",author:n?.user_id||"",text:D(n?.content?.elements),createTime:n?.create_time||""}))}}function y(t){return typeof t?.fileType=="string"&&t.fileType.trim()?t.fileType.trim():P}var M={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:g.LARK,description:"Lark / Feishu Docs \u2014 read, create, and append Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs (connected)
4
+ You can read, create, and append Lark/Feishu documents (docx). This reuses the same connected Lark app as messaging.
5
+ - larkdoc_get: pass a Lark doc id OR a full doc URL (a /docx/ or /wiki/ link); returns { ok, documentId, title, url, text } where text is the doc as plain text (truncated to ~20k chars). Use it as reference context.
6
+ - larkdoc_create: create a new doc from a title + markdown/text (#/##/### headings, - bullets, 1. ordered supported); returns { ok, documentId, url }. Share the url.
7
+ - larkdoc_append: append markdown/text to the end of an existing doc (pass the documentId or doc URL).
8
+ - larkdoc_list_comments: list the comment threads on a doc (pass the documentId or doc URL); returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.
9
+ - larkdoc_reply_comment: reply INSIDE an existing comment thread \u2014 pass { documentId, commentId, text }. Use this to answer a user who @mentioned Zibby in a doc comment (reply in the SAME commentId).
10
+ - larkdoc_add_comment: post a NEW top-level comment on a doc \u2014 pass { documentId, text }.
11
+ These tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.`,resolve(){let t=N();return t?{type:"stdio",command:"node",args:[t,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(t,e){try{switch(t){case"larkdoc_get":{let n=e?.documentId||e?.url||e?.id,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await k(r),i="";try{i=(await l("GET",`/open-apis/docx/v1/documents/${o}`)).data?.document?.title||""}catch{}let{data:s,host:c}=await l("GET",`/open-apis/docx/v1/documents/${o}/raw_content?lang=0`),a=String(s?.content||""),d=!1;return a.length>I&&(a=a.slice(0,I),d=!0),JSON.stringify({ok:!0,documentId:o,title:i,url:h(c,o),text:a,...d?{truncated:!0}:{}})}case"larkdoc_create":{let n=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!n)return JSON.stringify({ok:!1,error:"title is required"});let{data:r,host:o}=await l("POST","/open-apis/docx/v1/documents",{title:n,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),i=r?.document?.document_id;if(!i)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let s=f(e);if(s&&s.trim()){let c=L(s);c.length&&await w(i,c)}return JSON.stringify({ok:!0,documentId:i,title:n,url:h(o,i)})}case"larkdoc_append":{let n=e?.documentId||e?.url||e?.id,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=f(e);if(!o||!o.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let i=await k(r),s=L(o);if(!s.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let c=await w(i,s);return JSON.stringify({ok:!0,documentId:i,url:h(c,i)})}case"larkdoc_list_comments":{let n=e?.documentId||e?.url||e?.id||e?.fileToken,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await k(r),i=y(e),s=new URLSearchParams({file_type:i,page_size:String(U)}),{data:c}=await l("GET",`/open-apis/drive/v1/files/${o}/comments?${s.toString()}`),d=(Array.isArray(c?.items)?c.items:[]).map($);return JSON.stringify({ok:!0,documentId:o,count:d.length,comments:d})}case"larkdoc_add_comment":{let n=e?.documentId||e?.url||e?.id||e?.fileToken,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=f({text:e?.text??e?.body});if(!o||!o.trim())return JSON.stringify({ok:!1,error:"text is required"});let i=await k(r),s=y(e),{data:c}=await l("POST",`/open-apis/drive/v1/files/${i}/comments?file_type=${encodeURIComponent(s)}`,{reply_list:{replies:[{content:{elements:T(o)}}]}});return JSON.stringify({ok:!0,documentId:i,commentId:c?.comment_id||""})}case"larkdoc_reply_comment":{let n=e?.documentId||e?.url||e?.id||e?.fileToken,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=e?.commentId||e?.comment_id;if(!o)return JSON.stringify({ok:!1,error:"commentId is required"});let i=f({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await k(r),c=y(e),{data:a}=await l("POST",`/open-apis/drive/v1/files/${s}/comments/${encodeURIComponent(o)}/replies?file_type=${encodeURIComponent(c)}`,{content:{elements:T(i)}});return JSON.stringify({ok:!0,documentId:s,commentId:String(o),replyId:a?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${t}`})}}catch(n){return JSON.stringify({ok:!1,error:n.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root."}},required:["title"]}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};function K(){u=null}export{K as _resetLarkDocsTokenCache,h as docWebUrl,M as larkDocsSkill,L as markdownToLarkBlocks,m as parseLarkDocRef};
package/dist/linear.js CHANGED
@@ -1,4 +1,4 @@
1
- import{existsSync as N}from"fs";import{fileURLToPath as k}from"url";import{dirname as L,resolve as w}from"path";var h=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business"}),R=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"}});function S(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let a=L(k(import.meta.url)),i=w(a,"..","bin","mcp-skill.mjs");return N(i)?i:null}var v=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function O(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let a=process.env.LINEAR_API_KEY;if(!a)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return a}async function f(a,i={}){let t=await fetch(v,{method:"POST",headers:{Authorization:O(),"Content-Type":"application/json"},body:JSON.stringify({query:a,variables:i})});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Linear API ${t.status}: ${s.slice(0,300)}`)}let e=await t.json().catch(()=>null);if(!e)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(e.errors)&&e.errors.length){let s=e.errors.map(n=>n?.message||String(n)).join("; ");throw new Error(`Linear GraphQL error: ${s.slice(0,300)}`)}return e.data}function _(a){return String(a||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function E(a,i){let t=_(a),e=_(i);if(!t||!e)return 0;if(t===e)return 1;if(t.length===1||e.length===1)return t===e?1:0;let s=d=>{let u=new Map;for(let y=0;y<d.length-1;y++){let g=d.slice(y,y+2);u.set(g,(u.get(g)||0)+1)}return u},n=s(t),r=s(e),o=0,l=0,m=0;for(let d of n.values())l+=d;for(let d of r.values())m+=d;for(let[d,u]of n.entries())o+=Math.min(u,r.get(d)||0);return 2*o/Math.max(1,l+m)}function P(a,i){let t=Array.isArray(a)?a:[];if(!t.length)return{state:null,strategy:"no-states"};let e=_(i);if(!e)return{state:null,strategy:"no-target"};let s=t.find(o=>_(o.name)===e);if(s)return{state:s,strategy:"exact"};let n={backlog:["backlog"],unstarted:["todo","unstarted","open"],started:["inprogress","started","doing","wip"],completed:["done","completed","closed","resolved","fixed"],canceled:["canceled","cancelled","wontfix","won'tfix"],triage:["triage"]};for(let[o,l]of Object.entries(n)){if(!l.some(d=>_(d)===e))continue;let m=t.find(d=>d.type===o);if(m)return{state:m,strategy:"type-alias"}}let r=t.map(o=>({s:o,score:E(i,o.name)})).sort((o,l)=>l.score-o.score);return r[0]&&r[0].score>=.5?{state:r[0].s,strategy:"fuzzy"}:{state:null,strategy:"no-match"}}var T=`
1
+ import{existsSync as N}from"fs";import{fileURLToPath as k}from"url";import{dirname as L,resolve as w}from"path";var h=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),R=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function S(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let a=L(k(import.meta.url)),i=w(a,"..","bin","mcp-skill.mjs");return N(i)?i:null}var v=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function O(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let a=process.env.LINEAR_API_KEY;if(!a)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return a}async function f(a,i={}){let t=await fetch(v,{method:"POST",headers:{Authorization:O(),"Content-Type":"application/json"},body:JSON.stringify({query:a,variables:i})});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Linear API ${t.status}: ${s.slice(0,300)}`)}let e=await t.json().catch(()=>null);if(!e)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(e.errors)&&e.errors.length){let s=e.errors.map(n=>n?.message||String(n)).join("; ");throw new Error(`Linear GraphQL error: ${s.slice(0,300)}`)}return e.data}function _(a){return String(a||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function E(a,i){let t=_(a),e=_(i);if(!t||!e)return 0;if(t===e)return 1;if(t.length===1||e.length===1)return t===e?1:0;let s=d=>{let u=new Map;for(let y=0;y<d.length-1;y++){let g=d.slice(y,y+2);u.set(g,(u.get(g)||0)+1)}return u},n=s(t),r=s(e),o=0,l=0,m=0;for(let d of n.values())l+=d;for(let d of r.values())m+=d;for(let[d,u]of n.entries())o+=Math.min(u,r.get(d)||0);return 2*o/Math.max(1,l+m)}function P(a,i){let t=Array.isArray(a)?a:[];if(!t.length)return{state:null,strategy:"no-states"};let e=_(i);if(!e)return{state:null,strategy:"no-target"};let s=t.find(o=>_(o.name)===e);if(s)return{state:s,strategy:"exact"};let n={backlog:["backlog"],unstarted:["todo","unstarted","open"],started:["inprogress","started","doing","wip"],completed:["done","completed","closed","resolved","fixed"],canceled:["canceled","cancelled","wontfix","won'tfix"],triage:["triage"]};for(let[o,l]of Object.entries(n)){if(!l.some(d=>_(d)===e))continue;let m=t.find(d=>d.type===o);if(m)return{state:m,strategy:"type-alias"}}let r=t.map(o=>({s:o,score:E(i,o.name)})).sort((o,l)=>l.score-o.score);return r[0]&&r[0].score>=.5?{state:r[0].s,strategy:"fuzzy"}:{state:null,strategy:"no-match"}}var T=`
2
2
  id
3
3
  identifier
4
4
  number
@@ -12,7 +12,7 @@ import{existsSync as N}from"fs";import{fileURLToPath as k}from"url";import{dirna
12
12
  assignee { id name displayName email }
13
13
  labels { nodes { id name color } }
14
14
  team { id key name }
15
- `,U={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:h.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear (connected)
15
+ `,K={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:h.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear (connected)
16
16
  You have direct access to the user's Linear workspace (GraphQL API). Tools:
17
17
 
18
18
  ### Discovery
@@ -111,4 +111,4 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
111
111
  query IssueById($id: String!) {
112
112
  issue(id: $id) { ${i} }
113
113
  }
114
- `,{id:t}))?.issue||null}export{f as linearFetch,U as linearSkill};
114
+ `,{id:t}))?.issue||null}export{f as linearFetch,K as linearSkill};
@@ -25,6 +25,34 @@ export function injectedPersonalToken(): {
25
25
  token: string;
26
26
  memberId: string;
27
27
  };
28
+ /**
29
+ * STRICT CHAT-TURN INVARIANT (fail-CLOSED) — ZIBBY_CHAT_STRICT_PERSONAL=1.
30
+ * Set UNCONDITIONALLY by the Copilot runtime for EVERY chat turn (Slack +
31
+ * Lark, owner or not). Under it, the PERSONAL-tier provider
32
+ * (linkedin_personal) must NEVER fall through to the PAT-resolved project-
33
+ * owner token: the ONLY accepted credential is the per-turn injected sender
34
+ * token (the runtime injects the OWNER's own LinkedIn through the same path,
35
+ * so the owner keeps working). No injected token → HARD REFUSE for ANY sender
36
+ * — verified non-owner, same-account colleague, UNVERIFIED sender (the class
37
+ * the old per-sender flags failed OPEN on), or the owner with no LinkedIn.
38
+ * The business/org provider (company Pages) is team-tier and unaffected.
39
+ * Absent the flag (Fargate workflows, self-host, direct tool use) → the
40
+ * normal PAT chokepoint runs unchanged.
41
+ */
42
+ export function chatStrictPersonal(): boolean;
43
+ /** Belt-and-braces legacy flag: this turn's verified sender ≠ the tenant owner. */
44
+ export function senderIsNonOwner(): boolean;
45
+ /**
46
+ * The single PERSONAL-tier credential gate for linkedin_personal calls:
47
+ * injected sender token wins; otherwise a strict chat turn (or a flagged
48
+ * non-owner sender) HARD-REFUSES rather than falling through to the owner's
49
+ * PAT-resolved token. Returns the injected token/memberId or null (= caller
50
+ * may use the legacy PAT path). Throws PERSONAL_REFUSAL on the gated paths.
51
+ */
52
+ export function personalTierCredentialGate(): {
53
+ token: string;
54
+ memberId: string;
55
+ };
28
56
  /**
29
57
  * Extract a numeric organization id from a urn (urn:li:organization:123) or a
30
58
  * bare numeric id. Returns the id string, or null if none can be found.
@@ -46,6 +74,7 @@ export function linkedinApi(path: any, opts?: {}, provider?: string): Promise<{
46
74
  headers: Headers;
47
75
  body: {};
48
76
  }>;
77
+ export const PERSONAL_REFUSAL: "You haven't connected your own LinkedIn account \u2014 connect it at https://studio.zibby.dev/integrations (LinkedIn). For privacy, I can't post or act as anyone else's LinkedIn (including the project owner's) on your behalf.";
49
78
  export namespace linkedinSkill {
50
79
  let id: string;
51
80
  let serverName: string;
package/dist/linkedin.js CHANGED
@@ -1,4 +1,4 @@
1
- import{existsSync as b}from"fs";import{fileURLToPath as k}from"url";import{dirname as L,resolve as _}from"path";import{resolveIntegrationToken as g,clearTokenCache as w}from"@zibby/core/backend-client.js";function S(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let t=L(k(import.meta.url)),e=_(t,"..","bin","mcp-skill.mjs");return b(e)?e:null}function I(){let t=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!t)return null;let e=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:t,memberId:e}}var T="202506",v="https://api.linkedin.com";function f(t){if(t==null)return null;let e=String(t).trim();if(!e)return null;let i=e.match(/urn:li:organization:(\d+)/i);return i?i[1]:/^\d+$/.test(e)?e:null}function m(t){if(!t)return"";if(t.localizedName)return String(t.localizedName);let e=t.name&&t.name.localized;if(e&&typeof e=="object"){let i=Object.values(e)[0];if(i)return String(i)}return""}function p(t,e){return t?typeof t.get=="function"?t.get(e):t[e]||t[e.toLowerCase()]||null:null}async function c(t,e={},i="linkedin_business"){let l=async()=>{let n;if(i==="linkedin_personal"){let u=I();u&&(n=u.token)}if(n||({token:n}=await g(i)),typeof n!="string"||!n)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let o=t.startsWith("https://")?t:`${v}${t}`,r=await fetch(o,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"LinkedIn-Version":T,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!r.ok){let u=await r.text().catch(()=>"");throw new Error(`LinkedIn API ${r.status}: ${u.slice(0,300)}`)}let d=await r.text().catch(()=>""),s={};if(d&&d.trim())try{s=JSON.parse(d)}catch{s={raw:d}}return{status:r.status,headers:r.headers,body:s}};try{return await l()}catch(n){let o=String(n?.message||n||"").toLowerCase();if(!(o.includes("token")||o.includes("401")||o.includes("unauthorized")))throw n;return w(i),l()}}var E={id:"linkedin",serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn (connected)
1
+ import{existsSync as b}from"fs";import{fileURLToPath as _}from"url";import{dirname as k,resolve as L}from"path";import{resolveIntegrationToken as m,clearTokenCache as S}from"@zibby/core/backend-client.js";function N(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let t=k(_(import.meta.url)),e=L(t,"..","bin","mcp-skill.mjs");return b(e)?e:null}function w(){let t=String(process.env.ZIBBY_INJECTED_LINKEDIN_TOKEN||"").trim();if(!t)return null;let e=String(process.env.ZIBBY_INJECTED_LINKEDIN_MEMBER_ID||"").trim();return{token:t,memberId:e}}function T(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}function E(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}var v="You haven't connected your own LinkedIn account \u2014 connect it at https://studio.zibby.dev/integrations (LinkedIn). For privacy, I can't post or act as anyone else's LinkedIn (including the project owner's) on your behalf.";function g(){let t=w();if(t)return t;if(T()||E())throw new Error(v);return null}var A="202506",R="https://api.linkedin.com";function f(t){if(t==null)return null;let e=String(t).trim();if(!e)return null;let i=e.match(/urn:li:organization:(\d+)/i);return i?i[1]:/^\d+$/.test(e)?e:null}function I(t){if(!t)return"";if(t.localizedName)return String(t.localizedName);let e=t.name&&t.name.localized;if(e&&typeof e=="object"){let i=Object.values(e)[0];if(i)return String(i)}return""}function p(t,e){return t?typeof t.get=="function"?t.get(e):t[e]||t[e.toLowerCase()]||null:null}async function u(t,e={},i="linkedin_business"){let d=async()=>{let n;if(i==="linkedin_personal"){let c=g();c&&(n=c.token)}if(n||({token:n}=await m(i)),typeof n!="string"||!n)throw new Error("LinkedIn is not connected: no access token available. Connect LinkedIn in Integrations.");let o=t.startsWith("https://")?t:`${R}${t}`,r=await fetch(o,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"LinkedIn-Version":A,"X-Restli-Protocol-Version":"2.0.0",Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.body?JSON.stringify(e.body):void 0});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`LinkedIn API ${r.status}: ${c.slice(0,300)}`)}let l=await r.text().catch(()=>""),s={};if(l&&l.trim())try{s=JSON.parse(l)}catch{s={raw:l}}return{status:r.status,headers:r.headers,body:s}};try{return await d()}catch(n){let o=String(n?.message||n||"").toLowerCase();if(!(o.includes("token")||o.includes("401")||o.includes("unauthorized")))throw n;return S(i),d()}}var U={id:"linkedin",serverName:"linkedin",allowedTools:["mcp__linkedin__*"],envKeys:[],description:"LinkedIn \u2014 (business) list admin Organizations + create DRAFT posts on a company Page, and (personal) PUBLISH a post to your own member profile feed",promptFragment:`## LinkedIn (connected)
2
2
  You can post to LinkedIn two ways \u2014 an ORG company Page (business) and your own member PROFILE (personal). Each path needs its own LinkedIn integration connected.
3
3
 
4
4
  Business (company Page) \u2014 DRAFT only:
@@ -11,4 +11,4 @@ Personal (your own profile) \u2014 PUBLISHES IMMEDIATELY:
11
11
  Notes:
12
12
  - Org-page posts are ALWAYS created as a DRAFT; personal-profile posts are ALWAYS published live \u2014 choose the tool accordingly.
13
13
  - PUBLISHING IS OUTWARD-FACING AND IRREVERSIBLE. linkedin_publish_post posts live to a real audience the instant you call it \u2014 there is no undo and no draft state for member profiles. Only call it after the human has EXPLICITLY approved publishing THIS specific text in THIS conversation. If you wrote or edited the text, show it and get an explicit "yes, publish" first; if you are unsure, HOLD/draft rather than publish. The org draft tool (linkedin_create_draft_post) is the safe default when a human still needs to review.
14
- - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let t=S();return t?{type:"stdio",command:"node",args:[t,"../dist/linkedin.js","linkedinSkill"],env:{},description:this.description,alwaysLoad:!0}:{command:null,args:[],env:{},description:this.description}},async handleToolCall(t,e){try{switch(t){case"linkedin_list_organizations":{let{body:i}=await c("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),l=Array.isArray(i.elements)?i.elements:[],n=[];for(let o of l){let r=o.organizationalTarget||o["organizationalTarget~"]||o.organization,d=f(r);if(!d)continue;let s="",u="";try{let a=(await c(`/rest/organizations/${d}`,{},"linkedin_business")).body;s=m(a),u=a.vanityName||""}catch{}n.push({id:d,urn:`urn:li:organization:${d}`,name:s,vanityName:u})}return JSON.stringify({ok:!0,count:n.length,organizations:n})}case"linkedin_create_draft_post":{let i=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,l=f(i);if(!l)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let n=e?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let o=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",r=`urn:li:organization:${l}`;if(e?.dry_run===!0)try{let a="";try{let h=(await c(`/rest/organizations/${l}`,{},"linkedin_business")).body;a=m(h)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:a,id:l,urn:r},visibility:o,textPreview:n,note:"DRY RUN \u2014 nothing was posted"})}catch(a){return JSON.stringify({dryRun:!0,ok:!1,error:a.message})}let s=await c("/rest/posts",{method:"POST",body:{author:r,commentary:n,visibility:o,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1}},"linkedin_business"),u=p(s.headers,"x-restli-id")||p(s.headers,"x-linkedin-id")||s.body?.id||null;return JSON.stringify({ok:!0,postUrn:u,author:r,lifecycleState:"DRAFT",visibility:o,status:s.status})}case"linkedin_publish_post":{let i=I(),l=i?i.memberId:(await g("linkedin_personal")).memberId;if(!l)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let n=e?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let o=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",r=`urn:li:person:${l}`;if(e?.dry_run===!0)try{let a=(await c("/v2/userinfo",{},"linkedin_personal")).body,h=a?.name||[a?.given_name,a?.family_name].filter(Boolean).join(" ")||"",y=a?.sub?String(a.sub):l;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:h,id:y,urn:`urn:li:person:${y}`},visibility:o,textPreview:n,note:"DRY RUN \u2014 nothing was posted"})}catch(a){return JSON.stringify({dryRun:!0,ok:!1,error:a.message})}let s=await c("/rest/posts",{method:"POST",body:{author:r,commentary:n,visibility:o,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}},"linkedin_personal"),u=p(s.headers,"x-restli-id")||p(s.headers,"x-linkedin-id")||s.body?.id||null;return JSON.stringify({ok:!0,postUrn:u,author:r,lifecycleState:"PUBLISHED",visibility:o,status:s.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${t}`})}}catch(i){return JSON.stringify({ok:!1,error:i.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}}]};export{I as injectedPersonalToken,c as linkedinApi,E as linkedinSkill,f as parseOrgId};
14
+ - If the relevant LinkedIn integration is not connected these tools return { ok:false, error }; treat that as "LinkedIn unavailable" and continue.`,resolve(){let t=N();if(!t)return{command:null,args:[],env:{},description:this.description};let e={};for(let i of["ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_INJECTED_LINKEDIN_MEMBER_ID","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[i]&&(e[i]=process.env[i]);return{type:"stdio",command:"node",args:[t,"../dist/linkedin.js","linkedinSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(t,e){try{switch(t){case"linkedin_list_organizations":{let{body:i}=await u("/rest/organizationAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED",{},"linkedin_business"),d=Array.isArray(i.elements)?i.elements:[],n=[];for(let o of d){let r=o.organizationalTarget||o["organizationalTarget~"]||o.organization,l=f(r);if(!l)continue;let s="",c="";try{let a=(await u(`/rest/organizations/${l}`,{},"linkedin_business")).body;s=I(a),c=a.vanityName||""}catch{}n.push({id:l,urn:`urn:li:organization:${l}`,name:s,vanityName:c})}return JSON.stringify({ok:!0,count:n.length,organizations:n})}case"linkedin_create_draft_post":{let i=e?.organizationUrn||e?.organizationId||e?.organization||e?.orgId,d=f(i);if(!d)return JSON.stringify({ok:!1,error:"A valid organizationId or organizationUrn (urn:li:organization:{id}) is required"});let n=e?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post commentary) is required"});let o=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",r=`urn:li:organization:${d}`;if(e?.dry_run===!0)try{let a="";try{let h=(await u(`/rest/organizations/${d}`,{},"linkedin_business")).body;a=I(h)}catch{}return JSON.stringify({dryRun:!0,target:"organization",wouldPostAs:{name:a,id:d,urn:r},visibility:o,textPreview:n,note:"DRY RUN \u2014 nothing was posted"})}catch(a){return JSON.stringify({dryRun:!0,ok:!1,error:a.message})}let s=await u("/rest/posts",{method:"POST",body:{author:r,commentary:n,visibility:o,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"DRAFT",isReshareDisabledByAuthor:!1}},"linkedin_business"),c=p(s.headers,"x-restli-id")||p(s.headers,"x-linkedin-id")||s.body?.id||null;return JSON.stringify({ok:!0,postUrn:c,author:r,lifecycleState:"DRAFT",visibility:o,status:s.status})}case"linkedin_publish_post":{let i=g(),d=i?i.memberId:(await m("linkedin_personal")).memberId;if(!d)return JSON.stringify({ok:!1,error:"LinkedIn (personal) not connected or member id unavailable \u2014 reconnect LinkedIn Personal"});let n=e?.text;if(typeof n!="string"||!n.trim())return JSON.stringify({ok:!1,error:"text (the post body) is required"});let o=e?.visibility?String(e.visibility).toUpperCase():"PUBLIC",r=`urn:li:person:${d}`;if(e?.dry_run===!0)try{let a=(await u("/v2/userinfo",{},"linkedin_personal")).body,h=a?.name||[a?.given_name,a?.family_name].filter(Boolean).join(" ")||"",y=a?.sub?String(a.sub):d;return JSON.stringify({dryRun:!0,target:"member",wouldPostAs:{name:h,id:y,urn:`urn:li:person:${y}`},visibility:o,textPreview:n,note:"DRY RUN \u2014 nothing was posted"})}catch(a){return JSON.stringify({dryRun:!0,ok:!1,error:a.message})}let s=await u("/rest/posts",{method:"POST",body:{author:r,commentary:n,visibility:o,distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}},"linkedin_personal"),c=p(s.headers,"x-restli-id")||p(s.headers,"x-linkedin-id")||s.body?.id||null;return JSON.stringify({ok:!0,postUrn:c,author:r,lifecycleState:"PUBLISHED",visibility:o,status:s.status})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${t}`})}}catch(i){return JSON.stringify({ok:!1,error:i.message})}},tools:[{name:"linkedin_list_organizations",description:"List the LinkedIn Organizations (company Pages) the authenticated member ADMINISTERS. Returns [{ id, urn, name, vanityName }]. Call this first to choose the author org for a draft post.",input_schema:{type:"object",properties:{}}},{name:"linkedin_create_draft_post",description:"Create a DRAFT post on a LinkedIn Organization (company Page). The post is created in DRAFT state (never published automatically) so a human can review and publish it in LinkedIn. Returns the created post URN. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{organizationId:{type:"string",description:'The numeric organization id (e.g. "12345"). Alternative to organizationUrn.'},organizationUrn:{type:"string",description:'The organization URN, e.g. "urn:li:organization:12345". Alternative to organizationId.'},text:{type:"string",description:"The post commentary (the body text of the post)."},visibility:{type:"string",enum:["PUBLIC"],description:"Post visibility. Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}},{name:"linkedin_publish_post",description:"PUBLISH a post to the authenticated member's OWN LinkedIn profile feed (personal). UNLIKE linkedin_create_draft_post (which only drafts on a company Page), this PUBLISHES the post IMMEDIATELY \u2014 LinkedIn has no DRAFT state for member profiles, so there is no human review step. Returns the created post URN. Requires the LinkedIn Personal integration connected. Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published.",input_schema:{type:"object",properties:{text:{type:"string",description:"The post body (the commentary text of the post)."},visibility:{type:"string",enum:["PUBLIC","CONNECTIONS"],description:"Post visibility: PUBLIC (anyone) or CONNECTIONS (your connections only). Defaults to PUBLIC."},dry_run:{type:"boolean",description:"Set dry_run:true to VALIDATE which LinkedIn account/profile the post would go to (and preview the text) WITHOUT posting \u2014 nothing is published. Returns { dryRun, target, wouldPostAs, visibility, textPreview }. Defaults to false."}},required:["text"]}}]};export{v as PERSONAL_REFUSAL,T as chatStrictPersonal,w as injectedPersonalToken,u as linkedinApi,U as linkedinSkill,f as parseOrgId,g as personalTierCredentialGate,E as senderIsNonOwner};
@@ -1 +1 @@
1
- import{resolveIntegrationToken as w}from"@zibby/core/backend-client.js";var k=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business"}),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"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"}});var S=Object.freeze({id:"openai_billing",requiresIntegration:k.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),$=Object.freeze({id:"anthropic_billing",requiresIntegration:k.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),E=Object.freeze({id:"cursor_admin",requiresIntegration:k.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function I(t){return Math.floor(t/1e3)}function _(t){return new Date(t).toISOString().slice(0,10)}function b(t){return new Date(t).toISOString()}async function f(t){let a=await w(t);if(!a?.token)throw new Error(`${t} token resolver returned no token`);return a.token}async function A({startMs:t,endMs:a,groupBy:o=["project_id","line_item"]}){let i=await f("openai_billing"),e=[],n=0,m=o.map(d=>`group_by[]=${encodeURIComponent(d)}`).join("&"),u=null;for(let d=0;d<50;d++){let r=`https://api.openai.com/v1/organization/costs?${[`start_time=${I(t)}`,`end_time=${I(a)}`,"bucket_width=1d","limit=180",m,u?`page=${encodeURIComponent(u)}`:""].filter(Boolean).join("&")}`,c=await fetch(r,{headers:{Authorization:`Bearer ${i}`}});if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`OpenAI costs API ${c.status}: ${l.slice(0,200)}`)}let p=await c.json();for(let l of p.data||[]){n+=1;let h=_((l.start_time||0)*1e3);for(let s of l.results||[])e.push({provider:"openai",day:h,costUsd:Number(s.amount?.value??0),projectId:s.project_id||void 0,apiKeyId:s.api_key_id||void 0,model:s.line_item||void 0})}if(!p.has_more||!p.next_page)break;u=p.next_page}return{ok:!0,items:e,rawBuckets:n}}async function j(){let t=await f("openai_billing"),o=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let n=await o.text().catch(()=>"");throw new Error(`OpenAI projects API ${o.status}: ${n.slice(0,200)}`)}let i=await o.json(),e=new Map;for(let n of i.data||[])e.set(n.id,n.name);return e}async function y({startMs:t,endMs:a,groupBy:o=["workspace_id"]}){let i=await f("anthropic_billing"),e=[],n=0,m=o.map(d=>`group_by[]=${encodeURIComponent(d)}`).join("&"),u=null;for(let d=0;d<50;d++){let r=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(b(t))}`,`ending_at=${encodeURIComponent(b(a))}`,"bucket=1d","limit=100",m,u?`page=${encodeURIComponent(u)}`:""].filter(Boolean).join("&")}`,c=await fetch(r,{headers:{"x-api-key":i,"anthropic-version":"2023-06-01"}});if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`Anthropic cost_report ${c.status}: ${l.slice(0,200)}`)}let p=await c.json();for(let l of p.data||[]){n+=1;let h=(l.starting_at||"").slice(0,10);for(let s of l.results||[])e.push({provider:"anthropic",day:h,costUsd:Number(s.amount??s.cost??0),workspaceId:s.workspace_id||void 0,apiKeyId:s.api_key_id||void 0,model:s.model||void 0,tokensIn:s.uncached_input_tokens!=null?Number(s.uncached_input_tokens):void 0,tokensOut:s.output_tokens!=null?Number(s.output_tokens):void 0,cachedTokens:s.cached_input_tokens!=null?Number(s.cached_input_tokens):void 0})}if(!p.has_more||!p.next_page)break;u=p.next_page}return{ok:!0,items:e,rawBuckets:n}}async function L(){let t=await f("anthropic_billing"),o=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":t,"anthropic-version":"2023-06-01"}});if(!o.ok){let n=await o.text().catch(()=>"");throw new Error(`Anthropic workspaces ${o.status}: ${n.slice(0,200)}`)}let i=await o.json(),e=new Map;for(let n of i.data||[])e.set(n.id,n.name);return e}async function v({startMs:t,endMs:a}){let o=await f("cursor_admin"),i=_(t),e=_(a),n=`https://api.cursor.com/teams/daily-usage-data?startDate=${i}&endDate=${e}`,m=await fetch(n,{headers:{Authorization:`Bearer ${o}`}});if(!m.ok){let r=await m.text().catch(()=>"");throw new Error(`Cursor daily-usage ${m.status}: ${r.slice(0,200)}`)}let u=await m.json(),d=[],g=0;for(let r of u.data||[]){g+=1;let c=r.date;for(let p of r.userMetrics||[]){for(let l of p.modelUsage||[]){let h=Number(l.acceptedLines??0),s=Number(l.suggestedLines??0);d.push({provider:"cursor",day:c,costUsd:Number(l.totalCents??0)/100,userEmail:p.email,model:l.model,requestCount:Number(l.requestCount??0),acceptanceRate:s>0?h/s:void 0})}(!p.modelUsage||p.modelUsage.length===0)&&d.push({provider:"cursor",day:c,costUsd:Number(p.totalCents??0)/100,userEmail:p.email})}}return{ok:!0,items:d,rawBuckets:g}}async function R({startMs:t,endMs:a}){let[o,i,e]=await Promise.allSettled([A({startMs:t,endMs:a}),y({startMs:t,endMs:a}),v({startMs:t,endMs:a})]),n=r=>r.status==="fulfilled"?r.value:{ok:!1,error:r.reason?.message||String(r.reason),items:[]},m=n(o),u=n(i),d=n(e),g=[{provider:"openai",totalUsd:m.items.reduce((r,c)=>r+(c.costUsd||0),0)},{provider:"anthropic",totalUsd:u.items.reduce((r,c)=>r+(c.costUsd||0),0)},{provider:"cursor",totalUsd:d.items.reduce((r,c)=>r+(c.costUsd||0),0)}];return{openai:m,anthropic:u,cursor:d,totals:g}}function x(t,a){let o=new Map;for(let i of t){let e=a(i);if(!e)continue;let n=o.get(e)||{key:e,totalUsd:0,count:0};n.totalUsd+=i.costUsd||0,n.count+=1,o.set(e,n)}return[...o.values()].sort((i,e)=>e.totalUsd-i.totalUsd)}function B(t){if(!t.length)return{mean:0,stddev:0};let a=t.reduce((i,e)=>i+e,0)/t.length,o=t.reduce((i,e)=>i+(e-a)**2,0)/t.length;return{mean:a,stddev:Math.sqrt(o)}}export{$ as anthropicBillingSkill,E as cursorAdminSkill,R as fetchAllProviders,y as fetchAnthropicCosts,L as fetchAnthropicWorkspaces,v as fetchCursorSpend,A as fetchOpenAICosts,j as fetchOpenAIProjects,x as groupByKey,B as meanStddev,S as openaiBillingSkill};
1
+ import{resolveIntegrationToken as w}from"@zibby/core/backend-client.js";var k=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),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"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var S=Object.freeze({id:"openai_billing",requiresIntegration:k.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),$=Object.freeze({id:"anthropic_billing",requiresIntegration:k.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),E=Object.freeze({id:"cursor_admin",requiresIntegration:k.CURSOR_ADMIN,description:"Cursor Team/Enterprise admin API (paste admin key)"});function I(t){return Math.floor(t/1e3)}function _(t){return new Date(t).toISOString().slice(0,10)}function b(t){return new Date(t).toISOString()}async function f(t){let a=await w(t);if(!a?.token)throw new Error(`${t} token resolver returned no token`);return a.token}async function A({startMs:t,endMs:a,groupBy:o=["project_id","line_item"]}){let i=await f("openai_billing"),e=[],n=0,m=o.map(d=>`group_by[]=${encodeURIComponent(d)}`).join("&"),u=null;for(let d=0;d<50;d++){let r=`https://api.openai.com/v1/organization/costs?${[`start_time=${I(t)}`,`end_time=${I(a)}`,"bucket_width=1d","limit=180",m,u?`page=${encodeURIComponent(u)}`:""].filter(Boolean).join("&")}`,c=await fetch(r,{headers:{Authorization:`Bearer ${i}`}});if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`OpenAI costs API ${c.status}: ${l.slice(0,200)}`)}let p=await c.json();for(let l of p.data||[]){n+=1;let h=_((l.start_time||0)*1e3);for(let s of l.results||[])e.push({provider:"openai",day:h,costUsd:Number(s.amount?.value??0),projectId:s.project_id||void 0,apiKeyId:s.api_key_id||void 0,model:s.line_item||void 0})}if(!p.has_more||!p.next_page)break;u=p.next_page}return{ok:!0,items:e,rawBuckets:n}}async function R(){let t=await f("openai_billing"),o=await fetch("https://api.openai.com/v1/organization/projects?limit=100",{headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let n=await o.text().catch(()=>"");throw new Error(`OpenAI projects API ${o.status}: ${n.slice(0,200)}`)}let i=await o.json(),e=new Map;for(let n of i.data||[])e.set(n.id,n.name);return e}async function v({startMs:t,endMs:a,groupBy:o=["workspace_id"]}){let i=await f("anthropic_billing"),e=[],n=0,m=o.map(d=>`group_by[]=${encodeURIComponent(d)}`).join("&"),u=null;for(let d=0;d<50;d++){let r=`https://api.anthropic.com/v1/organizations/cost_report?${[`starting_at=${encodeURIComponent(b(t))}`,`ending_at=${encodeURIComponent(b(a))}`,"bucket=1d","limit=100",m,u?`page=${encodeURIComponent(u)}`:""].filter(Boolean).join("&")}`,c=await fetch(r,{headers:{"x-api-key":i,"anthropic-version":"2023-06-01"}});if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`Anthropic cost_report ${c.status}: ${l.slice(0,200)}`)}let p=await c.json();for(let l of p.data||[]){n+=1;let h=(l.starting_at||"").slice(0,10);for(let s of l.results||[])e.push({provider:"anthropic",day:h,costUsd:Number(s.amount??s.cost??0),workspaceId:s.workspace_id||void 0,apiKeyId:s.api_key_id||void 0,model:s.model||void 0,tokensIn:s.uncached_input_tokens!=null?Number(s.uncached_input_tokens):void 0,tokensOut:s.output_tokens!=null?Number(s.output_tokens):void 0,cachedTokens:s.cached_input_tokens!=null?Number(s.cached_input_tokens):void 0})}if(!p.has_more||!p.next_page)break;u=p.next_page}return{ok:!0,items:e,rawBuckets:n}}async function j(){let t=await f("anthropic_billing"),o=await fetch("https://api.anthropic.com/v1/organizations/workspaces?limit=100",{headers:{"x-api-key":t,"anthropic-version":"2023-06-01"}});if(!o.ok){let n=await o.text().catch(()=>"");throw new Error(`Anthropic workspaces ${o.status}: ${n.slice(0,200)}`)}let i=await o.json(),e=new Map;for(let n of i.data||[])e.set(n.id,n.name);return e}async function y({startMs:t,endMs:a}){let o=await f("cursor_admin"),i=_(t),e=_(a),n=`https://api.cursor.com/teams/daily-usage-data?startDate=${i}&endDate=${e}`,m=await fetch(n,{headers:{Authorization:`Bearer ${o}`}});if(!m.ok){let r=await m.text().catch(()=>"");throw new Error(`Cursor daily-usage ${m.status}: ${r.slice(0,200)}`)}let u=await m.json(),d=[],g=0;for(let r of u.data||[]){g+=1;let c=r.date;for(let p of r.userMetrics||[]){for(let l of p.modelUsage||[]){let h=Number(l.acceptedLines??0),s=Number(l.suggestedLines??0);d.push({provider:"cursor",day:c,costUsd:Number(l.totalCents??0)/100,userEmail:p.email,model:l.model,requestCount:Number(l.requestCount??0),acceptanceRate:s>0?h/s:void 0})}(!p.modelUsage||p.modelUsage.length===0)&&d.push({provider:"cursor",day:c,costUsd:Number(p.totalCents??0)/100,userEmail:p.email})}}return{ok:!0,items:d,rawBuckets:g}}async function L({startMs:t,endMs:a}){let[o,i,e]=await Promise.allSettled([A({startMs:t,endMs:a}),v({startMs:t,endMs:a}),y({startMs:t,endMs:a})]),n=r=>r.status==="fulfilled"?r.value:{ok:!1,error:r.reason?.message||String(r.reason),items:[]},m=n(o),u=n(i),d=n(e),g=[{provider:"openai",totalUsd:m.items.reduce((r,c)=>r+(c.costUsd||0),0)},{provider:"anthropic",totalUsd:u.items.reduce((r,c)=>r+(c.costUsd||0),0)},{provider:"cursor",totalUsd:d.items.reduce((r,c)=>r+(c.costUsd||0),0)}];return{openai:m,anthropic:u,cursor:d,totals:g}}function x(t,a){let o=new Map;for(let i of t){let e=a(i);if(!e)continue;let n=o.get(e)||{key:e,totalUsd:0,count:0};n.totalUsd+=i.costUsd||0,n.count+=1,o.set(e,n)}return[...o.values()].sort((i,e)=>e.totalUsd-i.totalUsd)}function C(t){if(!t.length)return{mean:0,stddev:0};let a=t.reduce((i,e)=>i+e,0)/t.length,o=t.reduce((i,e)=>i+(e-a)**2,0)/t.length;return{mean:a,stddev:Math.sqrt(o)}}export{$ as anthropicBillingSkill,E as cursorAdminSkill,L as fetchAllProviders,v as fetchAnthropicCosts,j as fetchAnthropicWorkspaces,y as fetchCursorSpend,A as fetchOpenAICosts,R as fetchOpenAIProjects,x as groupByKey,C as meanStddev,S as openaiBillingSkill};