@zibby/skills 0.2.13 → 0.2.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/artifact.d.ts +2 -0
- package/dist/artifact.js +37 -11
- package/dist/chat-notify.js +3 -3
- package/dist/chatProgress.js +4 -4
- package/dist/discord.js +3 -3
- package/dist/figma.js +2 -2
- package/dist/git-write.js +1 -1
- package/dist/github.js +4 -4
- package/dist/gitlab.js +3 -3
- package/dist/googleDocs.js +3 -3
- package/dist/hubspot.js +1 -1
- package/dist/index.js +147 -121
- package/dist/integrations.d.ts +6 -0
- package/dist/integrations.js +1 -1
- package/dist/jira.js +3 -3
- package/dist/lark.js +2 -2
- package/dist/larkDocs.d.ts +8 -7
- package/dist/larkDocs.js +3 -3
- package/dist/linear.js +3 -3
- package/dist/llm-billing.js +1 -1
- package/dist/notion.js +4 -4
- package/dist/opendesign.js +2 -2
- package/dist/package.json +1 -1
- package/dist/plane.js +1 -1
- package/dist/sentry.js +2 -2
- package/dist/slack.js +1 -1
- package/dist/trackers/github-adapter.js +1 -1
- package/dist/trackers/index.js +1 -1
- package/dist/trackers/jira-adapter.js +2 -2
- package/dist/trackers/linear-adapter.js +1 -1
- package/dist/vikunja.js +1 -1
- package/package.json +1 -1
package/dist/integrations.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ export declare const INTEGRATIONS: Readonly<{
|
|
|
26
26
|
GITLAB: "gitlab";
|
|
27
27
|
SLACK: "slack";
|
|
28
28
|
LARK: "lark";
|
|
29
|
+
LARK_DOCS: "lark_docs";
|
|
29
30
|
OPENAI_BILLING: "openai_billing";
|
|
30
31
|
ANTHROPIC_BILLING: "anthropic_billing";
|
|
31
32
|
CURSOR_ADMIN: "cursor_admin";
|
|
@@ -85,6 +86,11 @@ export declare const INTEGRATION_REGISTRY: Readonly<{
|
|
|
85
86
|
name: string;
|
|
86
87
|
connectPath: string;
|
|
87
88
|
};
|
|
89
|
+
lark_docs: {
|
|
90
|
+
id: string;
|
|
91
|
+
name: string;
|
|
92
|
+
connectPath: string;
|
|
93
|
+
};
|
|
88
94
|
openai_billing: {
|
|
89
95
|
id: string;
|
|
90
96
|
name: string;
|
package/dist/integrations.js
CHANGED
|
@@ -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",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",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"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});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",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),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"},lark_docs:{id:"lark_docs",name:"Lark Docs",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});export{n as INTEGRATIONS,i as INTEGRATION_REGISTRY};
|
package/dist/jira.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as
|
|
1
|
+
import{createRequire as J}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",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),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"},lark_docs:{id:"lark_docs",name:"Lark Docs",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var K=J(import.meta.url);function q(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return K.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var L=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function C(c,n){if(!n||!n.length)return c;let e=c;for(let t of n)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,n=0){if(!Array.isArray(c))return"";let e=[];for(let t of c){if(t.type==="text"){e.push(C(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,n+1):"";if(t.type==="listItem")e.push(r);else if(t.type==="bulletList"){let i=(t.content||[]).map(o=>`- ${S(o.content||[],n+1).trim()}`);e.push(`
|
|
@@ -11,7 +11,7 @@ ${i.join(`
|
|
|
11
11
|
|
|
12
12
|
${"#".repeat(i)} ${r.trim()}
|
|
13
13
|
|
|
14
|
-
`)}else
|
|
14
|
+
`)}else L.has(t.type)?e.push(`
|
|
15
15
|
|
|
16
16
|
${r}
|
|
17
17
|
`):e.push(r)}return e.join("").replace(/\n{3,}/g,`
|
|
@@ -66,4 +66,4 @@ When user asks to move/transition ticket status:
|
|
|
66
66
|
3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
|
|
67
67
|
4. Call jira_get_issue(issueKey) to verify final status before claiming success.
|
|
68
68
|
5. If target wording differs (e.g. \u5DF2\u7ECF\u9A8C\u6536 vs \u5DF2\u9A8C\u6536), try toStatus first; only ask user to confirm when no reasonable match exists.
|
|
69
|
-
6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let c=q();if(!c)return null;let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);process.env.ATLASSIAN_INSTANCE_URL&&(n.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let e of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[e]&&(n[e]=process.env[e]);return{command:"node",args:[c],env:n,description:this.description}},async handleToolCall(c,n){try{switch(c){case"jira_list_projects":{let e=await f("/rest/api/3/project"),t=(Array.isArray(e)?e:[]).map(r=>({id:r.id,key:r.key,name:r.name,style:r.style}));return JSON.stringify({count:t.length,projects:t})}case"jira_list_statuses":{let{projectKey:e}=n||{};if(e){let i=await f(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(i)?i:[],s=new Map;for(let u of o)for(let p of u.statuses||[])p?.id&&(s.has(p.id)||s.set(p.id,{id:p.id,name:p.name,category:p.statusCategory?.name||null}));let a=[...s.values()].sort((u,p)=>String(u.name).localeCompare(String(p.name)));return JSON.stringify({scope:"project",projectKey:e,count:a.length,statuses:a})}let t=await f("/rest/api/3/status"),r=(Array.isArray(t)?t:[]).map(i=>({id:i.id,name:i.name,category:i.statusCategory?.name||null})).sort((i,o)=>String(i.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:r.length,statuses:r})}case"jira_list_issue_types":{let{projectKey:e}=n||{};if(!e)return JSON.stringify({error:"projectKey is required"});let t=await A(e);return JSON.stringify({projectKey:e,count:t.length,issueTypes:t})}case"jira_search":{let e=n.jql||"",t=n.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let i=`jql=${encodeURIComponent(e)}&maxResults=${t}&fields=summary,status,assignee,priority,updated,issuetype,project`,s=((await f(`/rest/api/3/search/jql?${i}`)).issues||[]).map(a=>({key:a.key,project:a.fields?.project?.key,summary:a.fields?.summary,status:a.fields?.status?.name,assignee:a.fields?.assignee?.displayName||"Unassigned",priority:a.fields?.priority?.name,type:a.fields?.issuetype?.name}));return JSON.stringify({count:s.length,issues:s})}case"jira_get_issue":{let e=n.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let t=await f(`/rest/api/3/issue/${e}`);return JSON.stringify({key:t.key,project:t.fields?.project?.key,summary:t.fields?.summary,description:t.fields?.description,status:t.fields?.status?.name,assignee:t.fields?.assignee?.displayName||"Unassigned",priority:t.fields?.priority?.name,type:t.fields?.issuetype?.name,labels:t.fields?.labels,created:t.fields?.created,updated:t.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:t,issueType:r,description:i,priority:o,labels:s,assigneeId:a,moveToSprint:u,moveToActiveSprint:p,sprintId:d,sprintName:m,target:g}=n;if(!e||!t)return JSON.stringify({error:"projectKey and summary are required"});let l={requested:r||null,resolved:null,strategy:"none"},h=[];try{h=await A(e),l=x(r,h)}catch{}let y={project:{key:e},summary:t,issuetype:l?.resolved?.id?{id:l.resolved.id}:{name:r||"Task"}};i&&(y.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:i}]}]}),o&&(y.priority={name:o}),s?.length&&(y.labels=s),a&&(y.assignee={id:a});let j=await f("/rest/api/3/issue",{method:"POST",body:{fields:y}}),_={ok:!0,key:j.key,id:j.id,self:j.self};return l?.resolved&&(_.issueType=l.resolved.name,_.issueTypeResolution=l.strategy,l.strategy!=="exact"&&l.requested&&b(l.requested)!==b(l.resolved.name)&&(_.issueTypeWarning=`Requested "${l.requested}" is not available in ${e}; used "${l.resolved.name}" instead.`)),h.length>0&&(_.availableIssueTypes=h.map(v=>v.name)),(u||p)&&(_.sprintMove=await w({issueKey:j.key,projectKey:e,sprintId:d,sprintName:m,target:g})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:e,state:t}=n,r=await R(e,t);return JSON.stringify({count:r.length,sprints:r})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:o}=n||{},s=await w({issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:o||"current"});return JSON.stringify(s)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:o}=n||{},s=await w({issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:o});return JSON.stringify(s)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:t,projectKey:r,status:i,maxResults:o}=n;if(!e&&!t)return JSON.stringify({error:"sprintName or sprintId is required"});let s=o||50,a=t?`sprint = ${t}`:`sprint = "${e}"`,u=r?`project = ${r} AND `:"",p=i?` AND status = "${i}"`:"",d=`${u}${a}${p} ORDER BY status ASC, priority DESC`,m=`jql=${encodeURIComponent(d)}&maxResults=${s}&fields=summary,status,assignee,priority,issuetype,project`,g=await f(`/rest/api/3/search/jql?${m}`),l=(g.issues||[]).map(y=>({key:y.key,project:y.fields?.project?.key,summary:y.fields?.summary,status:y.fields?.status?.name,assignee:y.fields?.assignee?.displayName||"Unassigned",priority:y.fields?.priority?.name,type:y.fields?.issuetype?.name})),h={};for(let y of l)h[y.status]=(h[y.status]||0)+1;return JSON.stringify({count:l.length,total:g.total||l.length,statusCounts:h,issues:l})}case"jira_get_comments":{let{issueKey:e,maxResults:t}=n;if(!e)return JSON.stringify({error:"issueKey is required"});let i=await f(`/rest/api/3/issue/${e}/comment?maxResults=${t||50}&orderBy=-created`),o=(i.comments||[]).map(s=>{let a="";return s.body?.content&&(a=S(s.body.content)),{id:s.id,author:s.author?.displayName||"Unknown",body:a,created:s.created,updated:s.updated}});return JSON.stringify({count:o.length,total:i.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:t}=n;return!e||!t?JSON.stringify({error:"issueKey and body are required"}):(await f(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:t}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:t}=n;return!e||!t?JSON.stringify({error:"issueKey and fields are required"}):(await f(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:t}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:t,toStatus:r,statusName:i,status:o}=n;if(!e)return JSON.stringify({error:"issueKey is required"});let s=String(r||i||o||"").trim();if(!t&&!s){let d=((await f(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(m=>({id:m.id,name:m.name,to:m.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:d})}let a=t;if(!a){let d=(await f(`/rest/api/3/issue/${e}/transitions`)).transitions||[],m=k(s),g=d.find(l=>k(l?.name||"")===m||k(l?.to?.name||"")===m);if(!g){let l=N(s);l.length>=2&&(g=d.find(h=>{let y=N(h?.name||""),j=N(h?.to?.name||""),_=y.length>=2&&(y.includes(l)||l.includes(y)),v=j.length>=2&&(j.includes(l)||l.includes(j));return _||v}))}if(!g){let l=d.map(_=>{let v=I(s,_?.name||""),J=I(s,_?.to?.name||"");return{t:_,score:Math.max(v,J)}}).sort((_,v)=>v.score-_.score),h=l[0],y=l[1];h&&h.score>=.45&&(!y||h.score-y.score>=.12)&&(g=h.t)}if(!g?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${s}"`,issueKey:e,availableTransitions:d.map(l=>({id:l.id,name:l.name,to:l.to?.name}))});a=g.id}await f(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:a}}});let u=await f(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:a,statusAfter:u?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${c}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};export{f as jiraFetch,z as jiraSkill};
|
|
69
|
+
6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let c=q();if(!c)return null;let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);process.env.ATLASSIAN_INSTANCE_URL&&(n.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let e of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[e]&&(n[e]=process.env[e]);return{command:"node",args:[c],env:n,description:this.description}},async handleToolCall(c,n){try{switch(c){case"jira_list_projects":{let e=await f("/rest/api/3/project"),t=(Array.isArray(e)?e:[]).map(r=>({id:r.id,key:r.key,name:r.name,style:r.style}));return JSON.stringify({count:t.length,projects:t})}case"jira_list_statuses":{let{projectKey:e}=n||{};if(e){let i=await f(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(i)?i:[],s=new Map;for(let u of o)for(let p of u.statuses||[])p?.id&&(s.has(p.id)||s.set(p.id,{id:p.id,name:p.name,category:p.statusCategory?.name||null}));let a=[...s.values()].sort((u,p)=>String(u.name).localeCompare(String(p.name)));return JSON.stringify({scope:"project",projectKey:e,count:a.length,statuses:a})}let t=await f("/rest/api/3/status"),r=(Array.isArray(t)?t:[]).map(i=>({id:i.id,name:i.name,category:i.statusCategory?.name||null})).sort((i,o)=>String(i.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:r.length,statuses:r})}case"jira_list_issue_types":{let{projectKey:e}=n||{};if(!e)return JSON.stringify({error:"projectKey is required"});let t=await A(e);return JSON.stringify({projectKey:e,count:t.length,issueTypes:t})}case"jira_search":{let e=n.jql||"",t=n.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let i=`jql=${encodeURIComponent(e)}&maxResults=${t}&fields=summary,status,assignee,priority,updated,issuetype,project`,s=((await f(`/rest/api/3/search/jql?${i}`)).issues||[]).map(a=>({key:a.key,project:a.fields?.project?.key,summary:a.fields?.summary,status:a.fields?.status?.name,assignee:a.fields?.assignee?.displayName||"Unassigned",priority:a.fields?.priority?.name,type:a.fields?.issuetype?.name}));return JSON.stringify({count:s.length,issues:s})}case"jira_get_issue":{let e=n.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let t=await f(`/rest/api/3/issue/${e}`);return JSON.stringify({key:t.key,project:t.fields?.project?.key,summary:t.fields?.summary,description:t.fields?.description,status:t.fields?.status?.name,assignee:t.fields?.assignee?.displayName||"Unassigned",priority:t.fields?.priority?.name,type:t.fields?.issuetype?.name,labels:t.fields?.labels,created:t.fields?.created,updated:t.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:t,issueType:r,description:i,priority:o,labels:s,assigneeId:a,moveToSprint:u,moveToActiveSprint:p,sprintId:d,sprintName:m,target:g}=n;if(!e||!t)return JSON.stringify({error:"projectKey and summary are required"});let l={requested:r||null,resolved:null,strategy:"none"},_=[];try{_=await A(e),l=x(r,_)}catch{}let y={project:{key:e},summary:t,issuetype:l?.resolved?.id?{id:l.resolved.id}:{name:r||"Task"}};i&&(y.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:i}]}]}),o&&(y.priority={name:o}),s?.length&&(y.labels=s),a&&(y.assignee={id:a});let j=await f("/rest/api/3/issue",{method:"POST",body:{fields:y}}),h={ok:!0,key:j.key,id:j.id,self:j.self};return l?.resolved&&(h.issueType=l.resolved.name,h.issueTypeResolution=l.strategy,l.strategy!=="exact"&&l.requested&&b(l.requested)!==b(l.resolved.name)&&(h.issueTypeWarning=`Requested "${l.requested}" is not available in ${e}; used "${l.resolved.name}" instead.`)),_.length>0&&(h.availableIssueTypes=_.map(v=>v.name)),(u||p)&&(h.sprintMove=await w({issueKey:j.key,projectKey:e,sprintId:d,sprintName:m,target:g})),JSON.stringify(h)}case"jira_list_sprints":{let{projectKey:e,state:t}=n,r=await R(e,t);return JSON.stringify({count:r.length,sprints:r})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:o}=n||{},s=await w({issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:o||"current"});return JSON.stringify(s)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:o}=n||{},s=await w({issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:o});return JSON.stringify(s)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:t,projectKey:r,status:i,maxResults:o}=n;if(!e&&!t)return JSON.stringify({error:"sprintName or sprintId is required"});let s=o||50,a=t?`sprint = ${t}`:`sprint = "${e}"`,u=r?`project = ${r} AND `:"",p=i?` AND status = "${i}"`:"",d=`${u}${a}${p} ORDER BY status ASC, priority DESC`,m=`jql=${encodeURIComponent(d)}&maxResults=${s}&fields=summary,status,assignee,priority,issuetype,project`,g=await f(`/rest/api/3/search/jql?${m}`),l=(g.issues||[]).map(y=>({key:y.key,project:y.fields?.project?.key,summary:y.fields?.summary,status:y.fields?.status?.name,assignee:y.fields?.assignee?.displayName||"Unassigned",priority:y.fields?.priority?.name,type:y.fields?.issuetype?.name})),_={};for(let y of l)_[y.status]=(_[y.status]||0)+1;return JSON.stringify({count:l.length,total:g.total||l.length,statusCounts:_,issues:l})}case"jira_get_comments":{let{issueKey:e,maxResults:t}=n;if(!e)return JSON.stringify({error:"issueKey is required"});let i=await f(`/rest/api/3/issue/${e}/comment?maxResults=${t||50}&orderBy=-created`),o=(i.comments||[]).map(s=>{let a="";return s.body?.content&&(a=S(s.body.content)),{id:s.id,author:s.author?.displayName||"Unknown",body:a,created:s.created,updated:s.updated}});return JSON.stringify({count:o.length,total:i.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:t}=n;return!e||!t?JSON.stringify({error:"issueKey and body are required"}):(await f(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:t}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:t}=n;return!e||!t?JSON.stringify({error:"issueKey and fields are required"}):(await f(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:t}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:t,toStatus:r,statusName:i,status:o}=n;if(!e)return JSON.stringify({error:"issueKey is required"});let s=String(r||i||o||"").trim();if(!t&&!s){let d=((await f(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(m=>({id:m.id,name:m.name,to:m.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:d})}let a=t;if(!a){let d=(await f(`/rest/api/3/issue/${e}/transitions`)).transitions||[],m=k(s),g=d.find(l=>k(l?.name||"")===m||k(l?.to?.name||"")===m);if(!g){let l=N(s);l.length>=2&&(g=d.find(_=>{let y=N(_?.name||""),j=N(_?.to?.name||""),h=y.length>=2&&(y.includes(l)||l.includes(y)),v=j.length>=2&&(j.includes(l)||l.includes(j));return h||v}))}if(!g){let l=d.map(h=>{let v=I(s,h?.name||""),P=I(s,h?.to?.name||"");return{t:h,score:Math.max(v,P)}}).sort((h,v)=>v.score-h.score),_=l[0],y=l[1];_&&_.score>=.45&&(!y||_.score-y.score>=.12)&&(g=_.t)}if(!g?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${s}"`,issueKey:e,availableTransitions:d.map(l=>({id:l.id,name:l.name,to:l.to?.name}))});a=g.id}await f(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:a}}});let u=await f(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:a,statusAfter:u?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${c}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};export{f as jiraFetch,z as jiraSkill};
|
package/dist/lark.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as k}from"fs";import{fileURLToPath as y}from"url";import{dirname as f,resolve as b}from"path";import{resolveIntegrationToken as v}from"@zibby/core/backend-client.js";var h=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),P=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"},lark_docs:{id:"lark_docs",name:"Lark Docs",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function I(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let i=f(y(import.meta.url)),e=b(i,"..","bin","mcp-lark.mjs");return k(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 C={id:"lark",callsBackend:!0,serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:h.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],promptFragment:`## Lark
|
|
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)
|
|
5
5
|
- lark_list_chats: list chats the bot is a member of
|
|
6
6
|
- lark_get_chat_history: fetch recent messages in a chat
|
|
7
7
|
- lark_lookup_user_by_email: resolve an email \u2192 open_id for direct DM (prefer this over emailing through lark_send_message when the agent has a user_id already)
|
|
8
|
-
When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let i=I();if(!i)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[i],env:e,alwaysLoad:!0}},tools:[{name:"lark_send_message",description:"Send a text message to a Lark chat, user, or DM. receive_id can be a chat_id (oc_*), open_id (ou_*), union_id (on_*), or email.",input_schema:{type:"object",properties:{receive_id:{type:"string",description:"Target id: chat_id (oc_*), open_id (ou_*), union_id (on_*), or email"},text:{type:"string",description:"Message text"}},required:["receive_id","text"]}},{name:"lark_reply",description:"Reply to an existing Lark message (creates a thread). Use the message_id from the inbound event.",input_schema:{type:"object",properties:{message_id:{type:"string",description:"Lark message id (om_*) to reply to"},text:{type:"string",description:"Reply text"}},required:["message_id","text"]}},{name:"lark_list_chats",description:"List chats (groups + DMs) the bot is a member of.",input_schema:{type:"object",properties:{page_size:{type:"number",description:"Max results (default 50)"}}}},{name:"lark_get_chat_history",description:"Fetch recent messages in a chat.",input_schema:{type:"object",properties:{chat_id:{type:"string",description:"Chat id (oc_*)"},page_size:{type:"number",description:"Max messages (default 20)"}},required:["chat_id"]}},{name:"lark_lookup_user_by_email",description:"Resolve an email address to a Lark user id (open_id). Returns { ok:true, user:{open_id,email,name} } on hit, { ok:false } if no Lark user has that email. Use the open_id as `receive_id` in lark_send_message to DM.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"lark_search_users",description:'Fuzzy-search users by name across chats the bot is a member of. Lark has no public org-wide user search API for bots \u2014 this walks the bot\'s chat memberships and matches names client-side. Best for "send to Sam" style routing where you have a name but no email. Returns up to `limit` ranked matches { open_id, name }.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against user names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}],async handleToolCall(i,e){try{switch(i){case"lark_send_message":{if(!e.receive_id||!e.text)return JSON.stringify({error:"receive_id and text are required"});let t=O(e.receive_id),a=await _("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:g(e.text)});return JSON.stringify({ok:!0,message_id:a.message_id})}case"lark_reply":{if(!e.message_id||!e.text)return JSON.stringify({error:"message_id and text are required"});let t=await _("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:g(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,n=((await _("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(r=>({chat_id:r.chat_id,name:r.name,description:r.description,owner_id:r.owner_id,chat_mode:r.chat_mode}));return JSON.stringify({chats:n})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,n=((await _("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(r=>({message_id:r.message_id,sender_id:r.sender?.id,sender_type:r.sender?.sender_type,msg_type:r.msg_type,content:r.body?.content,create_time:r.create_time}));return JSON.stringify({messages:n})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let a=((await _("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(n=>n.email===e.email&&n.user_id);return JSON.stringify(a?{ok:!0,user:{open_id:a.user_id,email:a.email,name:a.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let a=Math.max(1,Math.min(Number(e.limit)||5,25)),n=200,m=((await _("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(o=>o.chat_id),l=new Set,c=[];for(let o of m){if(c.length>=n)break;try{let s=await _("GET",`/open-apis/im/v1/chats/${encodeURIComponent(o)}/members?member_id_type=open_id&page_size=100`);for(let d of s.items||[])if(!(!d.member_id||l.has(d.member_id))&&(l.add(d.member_id),c.push({open_id:d.member_id,name:d.name||""}),c.length>=n))break}catch(s){console.warn(`[lark] member scan failed for ${o}: ${s.message}`)}}let u=[];for(let o of c){let s=(o.name||"").toLowerCase();if(!s)continue;let d=0;s.includes(t)&&(d+=100-Math.abs(s.length-t.length)),s===t&&(d+=200),d>0&&u.push({open_id:o.open_id,name:o.name,_score:d})}return u.sort((o,s)=>s._score-o._score),JSON.stringify({ok:!0,matches:u.slice(0,a).map(({_score:o,...s})=>s),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${i}`})}}catch(t){return JSON.stringify({error:t.message})}}};function
|
|
8
|
+
When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let i=I();if(!i)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[i],env:e,alwaysLoad:!0}},tools:[{name:"lark_send_message",description:"Send a text message to a Lark chat, user, or DM. receive_id can be a chat_id (oc_*), open_id (ou_*), union_id (on_*), or email.",input_schema:{type:"object",properties:{receive_id:{type:"string",description:"Target id: chat_id (oc_*), open_id (ou_*), union_id (on_*), or email"},text:{type:"string",description:"Message text"}},required:["receive_id","text"]}},{name:"lark_reply",description:"Reply to an existing Lark message (creates a thread). Use the message_id from the inbound event.",input_schema:{type:"object",properties:{message_id:{type:"string",description:"Lark message id (om_*) to reply to"},text:{type:"string",description:"Reply text"}},required:["message_id","text"]}},{name:"lark_list_chats",description:"List chats (groups + DMs) the bot is a member of.",input_schema:{type:"object",properties:{page_size:{type:"number",description:"Max results (default 50)"}}}},{name:"lark_get_chat_history",description:"Fetch recent messages in a chat.",input_schema:{type:"object",properties:{chat_id:{type:"string",description:"Chat id (oc_*)"},page_size:{type:"number",description:"Max messages (default 20)"}},required:["chat_id"]}},{name:"lark_lookup_user_by_email",description:"Resolve an email address to a Lark user id (open_id). Returns { ok:true, user:{open_id,email,name} } on hit, { ok:false } if no Lark user has that email. Use the open_id as `receive_id` in lark_send_message to DM.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"lark_search_users",description:'Fuzzy-search users by name across chats the bot is a member of. Lark has no public org-wide user search API for bots \u2014 this walks the bot\'s chat memberships and matches names client-side. Best for "send to Sam" style routing where you have a name but no email. Returns up to `limit` ranked matches { open_id, name }.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against user names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}],async handleToolCall(i,e){try{switch(i){case"lark_send_message":{if(!e.receive_id||!e.text)return JSON.stringify({error:"receive_id and text are required"});let t=O(e.receive_id),a=await _("POST",`/open-apis/im/v1/messages?receive_id_type=${t}`,{receive_id:e.receive_id,msg_type:"text",content:g(e.text)});return JSON.stringify({ok:!0,message_id:a.message_id})}case"lark_reply":{if(!e.message_id||!e.text)return JSON.stringify({error:"message_id and text are required"});let t=await _("POST",`/open-apis/im/v1/messages/${encodeURIComponent(e.message_id)}/reply`,{msg_type:"text",content:g(e.text)});return JSON.stringify({ok:!0,message_id:t.message_id})}case"lark_list_chats":{let t=e.page_size||50,n=((await _("GET",`/open-apis/im/v1/chats?page_size=${t}`)).items||[]).map(r=>({chat_id:r.chat_id,name:r.name,description:r.description,owner_id:r.owner_id,chat_mode:r.chat_mode}));return JSON.stringify({chats:n})}case"lark_get_chat_history":{if(!e.chat_id)return JSON.stringify({error:"chat_id is required"});let t=e.page_size||20,n=((await _("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(e.chat_id)}&page_size=${t}&sort_type=ByCreateTimeDesc`)).items||[]).map(r=>({message_id:r.message_id,sender_id:r.sender?.id,sender_type:r.sender?.sender_type,msg_type:r.msg_type,content:r.body?.content,create_time:r.create_time}));return JSON.stringify({messages:n})}case"lark_lookup_user_by_email":{if(!e.email)return JSON.stringify({error:"email is required"});let a=((await _("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[e.email]})).user_list||[]).find(n=>n.email===e.email&&n.user_id);return JSON.stringify(a?{ok:!0,user:{open_id:a.user_id,email:a.email,name:a.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!e.query||typeof e.query!="string")return JSON.stringify({error:"query is required"});let t=e.query.trim().toLowerCase();if(!t)return JSON.stringify({ok:!0,matches:[]});let a=Math.max(1,Math.min(Number(e.limit)||5,25)),n=200,m=((await _("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(o=>o.chat_id),l=new Set,c=[];for(let o of m){if(c.length>=n)break;try{let s=await _("GET",`/open-apis/im/v1/chats/${encodeURIComponent(o)}/members?member_id_type=open_id&page_size=100`);for(let d of s.items||[])if(!(!d.member_id||l.has(d.member_id))&&(l.add(d.member_id),c.push({open_id:d.member_id,name:d.name||""}),c.length>=n))break}catch(s){console.warn(`[lark] member scan failed for ${o}: ${s.message}`)}}let u=[];for(let o of c){let s=(o.name||"").toLowerCase();if(!s)continue;let d=0;s.includes(t)&&(d+=100-Math.abs(s.length-t.length)),s===t&&(d+=200),d>0&&u.push({open_id:o.open_id,name:o.name,_score:d})}return u.sort((o,s)=>s._score-o._score),JSON.stringify({ok:!0,matches:u.slice(0,a).map(({_score:o,...s})=>s),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${i}`})}}catch(t){return JSON.stringify({error:t.message})}}};function x(){p=null}export{x as _resetLarkTokenCache,C as larkSkill};
|
package/dist/larkDocs.d.ts
CHANGED
|
@@ -2,20 +2,19 @@
|
|
|
2
2
|
* Lark / Feishu Docs skill — read / create / append Lark Docx documents.
|
|
3
3
|
*
|
|
4
4
|
* The document-world twin of googleDocs.js + notion.js, but for Lark/Feishu.
|
|
5
|
-
* It
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* resolveIntegrationToken('lark') → { appId, appSecret, host } →
|
|
5
|
+
* It runs on the DEDICATED Lark Docs app (integration `lark_docs`) — the app
|
|
6
|
+
* carrying the docx (+ wiki/drive) scopes — and falls back to the chat app
|
|
7
|
+
* (`lark`) so a single-app setup keeps working. Auth:
|
|
8
|
+
* resolveLarkDocsApp() → { appId, appSecret, host } →
|
|
10
9
|
* tenant_access_token (cached ~2h) → Bearer on every Docx call.
|
|
11
10
|
*
|
|
12
11
|
* Design rules (mirrors notion.js / googleDocs.js):
|
|
13
|
-
* -
|
|
12
|
+
* - resolveLarkDocsApp() is the SINGLE auth chokepoint (via the
|
|
14
13
|
* larkDocsApi() helper). Don't re-resolve at call sites.
|
|
15
14
|
* - handleToolCall() dispatches the tools and NEVER throws — any HTTP or
|
|
16
15
|
* parse failure is returned as { ok:false, error } so a missing/broken
|
|
17
16
|
* Lark connection can't crash the run.
|
|
18
|
-
* - Region-aware host: whatever
|
|
17
|
+
* - Region-aware host: whatever resolveLarkDocsApp() returns as
|
|
19
18
|
* `host` (open.feishu.cn vs open.larksuite.com) is used verbatim, so the
|
|
20
19
|
* skill always matches the connected app's region. No baked host, no CLI,
|
|
21
20
|
* no heavy deps — pure `fetch`.
|
|
@@ -33,6 +32,8 @@
|
|
|
33
32
|
* POST /open-apis/wiki/v2/spaces/{space_id}/nodes → { node:{node_token,obj_token,obj_type} }
|
|
34
33
|
* (obj_type='docx', node_type='origin', optional parent_node_token)
|
|
35
34
|
*/
|
|
35
|
+
/** Every env name the app-credential resolution below can read (→ envKeys). */
|
|
36
|
+
export declare const LARK_DOCS_APP_ENV_KEYS: readonly ("LARK_DOCS_APP_ID" | "LARK_DOCS_APP_SECRET" | "LARK_DOCS_HOST" | "LARK_APP_ID" | "LARK_APP_SECRET" | "LARK_HOST")[];
|
|
36
37
|
/**
|
|
37
38
|
* Derive the human-facing doc web URL from the open-api host + document id.
|
|
38
39
|
* The open-api host (open.feishu.cn / open.larksuite.com) is region-specific;
|
package/dist/larkDocs.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync as N,statSync as
|
|
2
|
-
`),
|
|
3
|
-
`)){let o=i.replace(/\s+$/,"");if(!o.trim())continue;let r=/^(#{1,3})\s+(.*)$/.exec(o),s=/^\s*[-*]\s+(.*)$/.exec(o),a=/^\s*\d+[.)]\s+(.*)$/.exec(o),c,d,l;if(r){let u=r[1].length;c=`heading${u}`,d=2+u,l=r[2]}else s?(c="bullet",d=12,l=s[1]):a?(c="ordered",d=13,l=a[1]):(c="text",d=2,l=o);t.push({block_type:d,[c]:{elements:[{text_run:{content:l}}],style:{}}})}return t}function g(n){let e=typeof n?.markdown=="string"?n.markdown:null,t=typeof n?.text=="string"?n.text:null;return e??t}async function L(n,e){let t;for(let i=0;i<e.length;i+=T){let o=e.slice(i,i+T);t=(await p("POST",`/open-apis/docx/v1/documents/${n}/blocks/${n}/children?document_revision_id=-1`,{children:o})).host}return t}function G(n){let e=typeof n=="string"?n.trim():"";if(!e)throw new Error("imagePath is required");if(!N(e)||!O(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=P(e);if(t.length>F)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return t}async function M({fileName:n,parentNode:e,bytes:t}){let{token:i,host:o}=await A(),r=new FormData;r.set("file_name",n),r.set("parent_type","docx_image"),r.set("parent_node",e),r.set("size",String(t.length)),r.set("file",new Blob([t]),n);let a=await(await fetch(`${o}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:r})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var K="docx",H=50;function v(n){return[{type:"text_run",text_run:{text:String(n??"")}}]}function z(n){return Array.isArray(n)?n.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function Y(n){let e=Array.isArray(n?.reply_list?.replies)?n.reply_list.replies:[];return{commentId:n?.comment_id||"",resolved:!!n?.is_solved,replies:e.map(t=>({replyId:t?.reply_id||"",author:t?.user_id||"",text:z(t?.content?.elements),createTime:t?.create_time||""}))}}function x(n){return typeof n?.fileType=="string"&&n.fileType.trim()?n.fileType.trim():K}var ne={id:"lark-docs",callsBackend:!0,serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:S.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],promptFragment:'## Lark Docs\nYou can read, create, and append Lark/Feishu documents (docx), and read/post/reply to their comments. This reuses the same connected Lark app as messaging. Each `larkdoc_*` / `larkwiki_*` tool documents its own params and return shape in its tool description \u2014 they are not restated here.\nThese tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.',resolve(){let n=D();if(!n)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[n,"../dist/larkDocs.js","larkDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,i=f(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await h(i),r="";try{r=(await p("GET",`/open-apis/docx/v1/documents/${o}`)).data?.document?.title||""}catch{}let{data:s,host:a}=await p("GET",`/open-apis/docx/v1/documents/${o}/raw_content?lang=0`),c=String(s?.content||""),d=!1;return c.length>b&&(c=c.slice(0,b),d=!0),JSON.stringify({ok:!0,documentId:o,title:r,url:y(a,o),text:c,...d?{truncated:!0}:{}})}case"larkdoc_create":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let i=typeof e?.wikiSpaceId=="string"&&e.wikiSpaceId.trim()?e.wikiSpaceId.trim():null;if(i){let c=typeof e?.parentNodeToken=="string"&&e.parentNodeToken.trim()?e.parentNodeToken.trim():null,{data:d,host:l}=await p("POST",`/open-apis/wiki/v2/spaces/${encodeURIComponent(i)}/nodes`,{obj_type:"docx",node_type:"origin",title:t,...c?{parent_node_token:c}:{}}),u=d?.node||{},m=u.obj_token;if(!m)return JSON.stringify({ok:!1,error:"Lark wiki node create returned no obj_token"});let k=g(e);if(k&&k.trim()){let w=I(k);w.length&&await L(m,w)}return JSON.stringify({ok:!0,documentId:m,title:t,wikiSpaceId:i,wikiNodeToken:u.node_token||"",url:u.node_token?q(l,u.node_token):y(l,m)})}let{data:o,host:r}=await p("POST","/open-apis/docx/v1/documents",{title:t,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),s=o?.document?.document_id;if(!s)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let a=g(e);if(a&&a.trim()){let c=I(a);c.length&&await L(s,c)}return JSON.stringify({ok:!0,documentId:s,title:t,url:y(r,s)})}case"larkdoc_append":{let t=e?.documentId||e?.url||e?.id,i=f(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=g(e);if(!o||!o.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let r=await h(i),s=I(o);if(!s.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await L(r,s);return JSON.stringify({ok:!0,documentId:r,url:y(a,r)})}case"larkdoc_insert_image":{let t=e?.documentId||e?.url||e?.id,i=f(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let o=await h(i),r=e.imagePath.trim(),s=G(r),a=E(r),d=(await p("POST",`/open-apis/docx/v1/documents/${o}/blocks/${o}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!d)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let l=await M({fileName:a,parentNode:d,bytes:s}),u={token:l},m=Number(e?.width),k=Number(e?.height);Number.isFinite(m)&&m>0&&(u.width=Math.round(m)),Number.isFinite(k)&&k>0&&(u.height=Math.round(k));let{host:w}=await p("PATCH",`/open-apis/docx/v1/documents/${o}/blocks/${d}?document_revision_id=-1`,{replace_image:u});return JSON.stringify({ok:!0,documentId:o,blockId:d,fileToken:l,url:y(w,o)})}case"larkwiki_list_spaces":{let t=[],i=null;for(let o=0;o<J;o++){let r=new URLSearchParams({page_size:String(C)});i&&r.set("page_token",i);let{data:s}=await p("GET",`/open-apis/wiki/v2/spaces?${r.toString()}`),a=Array.isArray(s?.items)?s.items:[];for(let c of a)t.push({spaceId:String(c?.space_id||""),name:String(c?.name||"")});if(!s?.has_more||!s?.page_token)break;i=s.page_token}return JSON.stringify({ok:!0,count:t.length,spaces:t})}case"larkdoc_list_comments":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,i=f(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await h(i),r=x(e),s=new URLSearchParams({file_type:r,page_size:String(H)}),{data:a}=await p("GET",`/open-apis/drive/v1/files/${o}/comments?${s.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(Y);return JSON.stringify({ok:!0,documentId:o,count:d.length,comments:d})}case"larkdoc_add_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,i=f(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=g({text:e?.text??e?.body});if(!o||!o.trim())return JSON.stringify({ok:!1,error:"text is required"});let r=await h(i),s=x(e),{data:a}=await p("POST",`/open-apis/drive/v1/files/${r}/comments?file_type=${encodeURIComponent(s)}`,{reply_list:{replies:[{content:{elements:v(o)}}]}});return JSON.stringify({ok:!0,documentId:r,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let t=e?.documentId||e?.url||e?.id||e?.fileToken,i=f(t);if(!i)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 r=g({text:e?.text??e?.body});if(!r||!r.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await h(i),a=x(e),{data:c}=await p("POST",`/open-apis/drive/v1/files/${s}/comments/${encodeURIComponent(o)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:v(r)}});return JSON.stringify({ok:!0,documentId:s,commentId:String(o),replyId:c?.reply_id||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${n}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"larkdoc_get",description:"Read a Lark/Feishu document (docx) as plain text, for use as reference context. Accepts a raw doc id OR a full Lark doc URL (a /docx/ or /wiki/ link \u2014 wiki links are resolved to their backing docx). Returns { ok, documentId, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL (/docx/\u2026 or /wiki/\u2026)."}},required:["documentId"]}},{name:"larkdoc_create",description:"Create a new Lark/Feishu document (docx) with a title and optional content (markdown: #/##/### headings, - bullets, 1. ordered; or plain text). Pass wikiSpaceId (from larkwiki_list_spaces) to create the doc INSIDE a wiki space instead of as a standalone doc \u2014 optionally nested under parentNodeToken. Returns { ok, documentId, url } (plus wikiNodeToken when created in a wiki) \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root. Ignored when wikiSpaceId is set."},wikiSpaceId:{type:"string",description:"Optional wiki space id (from larkwiki_list_spaces) \u2014 create the doc as a node inside this wiki space."},parentNodeToken:{type:"string",description:"Optional wiki node token to nest the new doc under (only with wikiSpaceId). Absent = the space root."}},required:["title"]}},{name:"larkwiki_list_spaces",description:"List the Lark/Feishu wiki spaces visible to the connected app. Returns { ok, count, spaces:[{ spaceId, name }] }. Use to discover the wikiSpaceId for larkdoc_create.",input_schema:{type:"object",properties:{}}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};function oe(){_=null}export{oe as _resetLarkDocsTokenCache,y as docWebUrl,ne as larkDocsSkill,I as markdownToLarkBlocks,f as parseLarkDocRef,q as wikiWebUrl};
|
|
1
|
+
import{existsSync as N,statSync as E,readFileSync as D}from"fs";import{fileURLToPath as $}from"url";import{basename as j,dirname as C,resolve as U}from"path";import{resolveIntegrationToken as T}from"@zibby/core/backend-client.js";var y=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),te=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"},lark_docs:{id:"lark_docs",name:"Lark Docs",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function J(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let t=C($(import.meta.url)),e=U(t,"..","bin","mcp-skill.mjs");return N(e)?e:null}var A=2e4,O=50,F=50,K=20,B=10*1024*1024,q=6e3*1e3,_=null,G="https://open.larksuite.com",R=Object.freeze([Object.freeze({appId:"LARK_DOCS_APP_ID",appSecret:"LARK_DOCS_APP_SECRET",host:"LARK_DOCS_HOST"}),Object.freeze({appId:"LARK_APP_ID",appSecret:"LARK_APP_SECRET",host:"LARK_HOST"})]),M=Object.freeze(R.flatMap(t=>[t.appId,t.appSecret,t.host]));function b(t){let e=String(t||"").trim().replace(/\/+$/,"");return e?/^https?:\/\//i.test(e)?e:`https://${e}`:G}function z(t){let e=String(process.env[t.appId]||"").trim(),n=String(process.env[t.appSecret]||"").trim();return!e||!n?null:{appId:e,appSecret:n,host:b(process.env[t.host])}}async function H(){for(let t of R){let e=z(t);if(e)return e}try{let t=await T(y.LARK_DOCS);return{appId:t?.appId,appSecret:t?.appSecret,host:b(t?.host)}}catch(t){if(!/unknown provider/i.test(String(t?.message||"")))throw t;let e=await T(y.LARK);return{appId:e?.appId,appSecret:e?.appSecret,host:b(e?.host)}}}async function P(){let{appId:t,appSecret:e,host:n}=await H();if(_&&_.appId===t&&_.expiresAt>Date.now())return{token:_.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 _={token:o.tenant_access_token,expiresAt:Date.now()+q,appId:t},{token:o.tenant_access_token,host:n}}async function l(t,e,n){let{token:i,host:o}=await P(),r={method:t,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json; charset=utf-8"}};t!=="GET"&&n!==void 0&&(r.body=JSON.stringify(n));let a=await(await fetch(`${o}${e}`,r)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:o}}function g(t,e){return String(t||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function Y(t,e){return String(t||"").includes("feishu")?`https://feishu.cn/wiki/${e}`:`https://www.larksuite.com/wiki/${e}`}function f(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 h(t){let e=typeof t=="string"?f(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)}`),i=n?.node||{};if(i.obj_type!=="docx"||!i.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${i.obj_type||"unknown"})`);return i.obj_token}function S(t){let e=String(t??"").replace(/\r\n/g,`
|
|
2
|
+
`),n=[];for(let i of e.split(`
|
|
3
|
+
`)){let o=i.replace(/\s+$/,"");if(!o.trim())continue;let r=/^(#{1,3})\s+(.*)$/.exec(o),s=/^\s*[-*]\s+(.*)$/.exec(o),a=/^\s*\d+[.)]\s+(.*)$/.exec(o),c,d,p;if(r){let u=r[1].length;c=`heading${u}`,d=2+u,p=r[2]}else s?(c="bullet",d=12,p=s[1]):a?(c="ordered",d=13,p=a[1]):(c="text",d=2,p=o);n.push({block_type:d,[c]:{elements:[{text_run:{content:p}}],style:{}}})}return n}function I(t){let e=typeof t?.markdown=="string"?t.markdown:null,n=typeof t?.text=="string"?t.text:null;return e??n}async function L(t,e){let n;for(let i=0;i<e.length;i+=O){let o=e.slice(i,i+O);n=(await l("POST",`/open-apis/docx/v1/documents/${t}/blocks/${t}/children?document_revision_id=-1`,{children:o})).host}return n}function W(t){let e=typeof t=="string"?t.trim():"";if(!e)throw new Error("imagePath is required");if(!N(e)||!E(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let n=D(e);if(n.length>B)throw new Error(`image is ${(n.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return n}async function X({fileName:t,parentNode:e,bytes:n}){let{token:i,host:o}=await P(),r=new FormData;r.set("file_name",t),r.set("parent_type","docx_image"),r.set("parent_node",e),r.set("size",String(n.length)),r.set("file",new Blob([n]),t);let a=await(await fetch(`${o}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:r})).json();if(a.code!==0)throw new Error(`Lark media upload_all error: ${a.msg||a.code}`);let c=a.data?.file_token;if(!c)throw new Error("Lark media upload_all returned no file_token");return c}var Z="docx",V=50;function v(t){return[{type:"text_run",text_run:{text:String(t??"")}}]}function Q(t){return Array.isArray(t)?t.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function ee(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:Q(n?.content?.elements),createTime:n?.create_time||""}))}}function x(t){return typeof t?.fileType=="string"&&t.fileType.trim()?t.fileType.trim():Z}var ce={id:"lark-docs",callsBackend:!0,serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:[y.LARK_DOCS,y.LARK],description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV",...M],promptFragment:'## Lark Docs\nYou can read, create, and append Lark/Feishu documents (docx), and read/post/reply to their comments. This runs on the connected Lark Docs app (the chat app is used when no separate docs app is connected). Each `larkdoc_*` / `larkwiki_*` tool documents its own params and return shape in its tool description \u2014 they are not restated here.\nThese tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.',resolve(){let t=J();if(!t)return null;let e={};for(let n of this.envKeys)process.env[n]&&(e[n]=process.env[n]);return{type:"stdio",command:"node",args:[t,"../dist/larkDocs.js","larkDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(t,e){try{switch(t){case"larkdoc_get":{let n=e?.documentId||e?.url||e?.id,i=f(n);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await h(i),r="";try{r=(await l("GET",`/open-apis/docx/v1/documents/${o}`)).data?.document?.title||""}catch{}let{data:s,host:a}=await l("GET",`/open-apis/docx/v1/documents/${o}/raw_content?lang=0`),c=String(s?.content||""),d=!1;return c.length>A&&(c=c.slice(0,A),d=!0),JSON.stringify({ok:!0,documentId:o,title:r,url:g(a,o),text:c,...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 i=typeof e?.wikiSpaceId=="string"&&e.wikiSpaceId.trim()?e.wikiSpaceId.trim():null;if(i){let c=typeof e?.parentNodeToken=="string"&&e.parentNodeToken.trim()?e.parentNodeToken.trim():null,{data:d,host:p}=await l("POST",`/open-apis/wiki/v2/spaces/${encodeURIComponent(i)}/nodes`,{obj_type:"docx",node_type:"origin",title:n,...c?{parent_node_token:c}:{}}),u=d?.node||{},m=u.obj_token;if(!m)return JSON.stringify({ok:!1,error:"Lark wiki node create returned no obj_token"});let k=I(e);if(k&&k.trim()){let w=S(k);w.length&&await L(m,w)}return JSON.stringify({ok:!0,documentId:m,title:n,wikiSpaceId:i,wikiNodeToken:u.node_token||"",url:u.node_token?Y(p,u.node_token):g(p,m)})}let{data:o,host:r}=await l("POST","/open-apis/docx/v1/documents",{title:n,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),s=o?.document?.document_id;if(!s)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let a=I(e);if(a&&a.trim()){let c=S(a);c.length&&await L(s,c)}return JSON.stringify({ok:!0,documentId:s,title:n,url:g(r,s)})}case"larkdoc_append":{let n=e?.documentId||e?.url||e?.id,i=f(n);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=I(e);if(!o||!o.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let r=await h(i),s=S(o);if(!s.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await L(r,s);return JSON.stringify({ok:!0,documentId:r,url:g(a,r)})}case"larkdoc_insert_image":{let n=e?.documentId||e?.url||e?.id,i=f(n);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let o=await h(i),r=e.imagePath.trim(),s=W(r),a=j(r),d=(await l("POST",`/open-apis/docx/v1/documents/${o}/blocks/${o}/children?document_revision_id=-1`,{children:[{block_type:27,image:{}}]})).data?.children?.[0]?.block_id;if(!d)return JSON.stringify({ok:!1,error:"Lark image block create returned no block_id"});let p=await X({fileName:a,parentNode:d,bytes:s}),u={token:p},m=Number(e?.width),k=Number(e?.height);Number.isFinite(m)&&m>0&&(u.width=Math.round(m)),Number.isFinite(k)&&k>0&&(u.height=Math.round(k));let{host:w}=await l("PATCH",`/open-apis/docx/v1/documents/${o}/blocks/${d}?document_revision_id=-1`,{replace_image:u});return JSON.stringify({ok:!0,documentId:o,blockId:d,fileToken:p,url:g(w,o)})}case"larkwiki_list_spaces":{let n=[],i=null;for(let o=0;o<K;o++){let r=new URLSearchParams({page_size:String(F)});i&&r.set("page_token",i);let{data:s}=await l("GET",`/open-apis/wiki/v2/spaces?${r.toString()}`),a=Array.isArray(s?.items)?s.items:[];for(let c of a)n.push({spaceId:String(c?.space_id||""),name:String(c?.name||"")});if(!s?.has_more||!s?.page_token)break;i=s.page_token}return JSON.stringify({ok:!0,count:n.length,spaces:n})}case"larkdoc_list_comments":{let n=e?.documentId||e?.url||e?.id||e?.fileToken,i=f(n);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await h(i),r=x(e),s=new URLSearchParams({file_type:r,page_size:String(V)}),{data:a}=await l("GET",`/open-apis/drive/v1/files/${o}/comments?${s.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(ee);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,i=f(n);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=I({text:e?.text??e?.body});if(!o||!o.trim())return JSON.stringify({ok:!1,error:"text is required"});let r=await h(i),s=x(e),{data:a}=await l("POST",`/open-apis/drive/v1/files/${r}/comments?file_type=${encodeURIComponent(s)}`,{reply_list:{replies:[{content:{elements:v(o)}}]}});return JSON.stringify({ok:!0,documentId:r,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let n=e?.documentId||e?.url||e?.id||e?.fileToken,i=f(n);if(!i)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 r=I({text:e?.text??e?.body});if(!r||!r.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await h(i),a=x(e),{data:c}=await l("POST",`/open-apis/drive/v1/files/${s}/comments/${encodeURIComponent(o)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:v(r)}});return JSON.stringify({ok:!0,documentId:s,commentId:String(o),replyId:c?.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). Pass wikiSpaceId (from larkwiki_list_spaces) to create the doc INSIDE a wiki space instead of as a standalone doc \u2014 optionally nested under parentNodeToken. Returns { ok, documentId, url } (plus wikiNodeToken when created in a wiki) \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root. Ignored when wikiSpaceId is set."},wikiSpaceId:{type:"string",description:"Optional wiki space id (from larkwiki_list_spaces) \u2014 create the doc as a node inside this wiki space."},parentNodeToken:{type:"string",description:"Optional wiki node token to nest the new doc under (only with wikiSpaceId). Absent = the space root."}},required:["title"]}},{name:"larkwiki_list_spaces",description:"List the Lark/Feishu wiki spaces visible to the connected app. Returns { ok, count, spaces:[{ spaceId, name }] }. Use to discover the wikiSpaceId for larkdoc_create.",input_schema:{type:"object",properties:{}}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};function de(){_=null}export{M as LARK_DOCS_APP_ENV_KEYS,de as _resetLarkDocsTokenCache,g as docWebUrl,ce as larkDocsSkill,S as markdownToLarkBlocks,f as parseLarkDocRef,Y as wikiWebUrl};
|
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",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",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"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function v(){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 S=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(S,{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 P(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 E(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:P(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",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),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"},lark_docs:{id:"lark_docs",name:"Lark Docs",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function v(){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 S=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(S,{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 P(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 E(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:P(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
|
-
`,
|
|
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
|
|
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,
|
|
114
|
+
`,{id:t}))?.issue||null}export{f as linearFetch,K as linearSkill};
|
package/dist/llm-billing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveIntegrationToken as w}from"@zibby/core/backend-client.js";var f=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",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),P=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"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var
|
|
1
|
+
import{resolveIntegrationToken as w}from"@zibby/core/backend-client.js";var f=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),P=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"},lark_docs:{id:"lark_docs",name:"Lark Docs",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var S=Object.freeze({id:"openai_billing",callsBackend:!0,requiresIntegration:f.OPENAI_BILLING,description:"OpenAI organization billing/usage admin API (paste sk-admin-... key)"}),j=Object.freeze({id:"anthropic_billing",callsBackend:!0,requiresIntegration:f.ANTHROPIC_BILLING,description:"Anthropic organization cost/usage admin API (paste sk-ant-admin-... key)"}),L=Object.freeze({id:"cursor_admin",callsBackend:!0,requiresIntegration:f.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 k(t){let a=await w(t);if(!a?.token)throw new Error(`${t} token resolver returned no token`);return a.token}async function v({startMs:t,endMs:a,groupBy:o=["project_id","line_item"]}){let i=await k("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 k("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 k("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 $(){let t=await k("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 A({startMs:t,endMs:a}){let o=await k("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 B({startMs:t,endMs:a}){let[o,i,e]=await Promise.allSettled([v({startMs:t,endMs:a}),y({startMs:t,endMs:a}),A({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 E(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 x(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{j as anthropicBillingSkill,L as cursorAdminSkill,B as fetchAllProviders,y as fetchAnthropicCosts,$ as fetchAnthropicWorkspaces,A as fetchCursorSpend,v as fetchOpenAICosts,R as fetchOpenAIProjects,E as groupByKey,x as meanStddev,S as openaiBillingSkill};
|
package/dist/notion.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{existsSync as R,statSync as S,readFileSync as L}from"fs";import{fileURLToPath as $}from"url";import{basename as U,dirname as v,resolve as T}from"path";import{resolveIntegrationToken as j,clearTokenCache as E}from"@zibby/core/backend-client.js";var
|
|
1
|
+
import{existsSync as R,statSync as S,readFileSync as L}from"fs";import{fileURLToPath as $}from"url";import{basename as U,dirname as v,resolve as T}from"path";import{resolveIntegrationToken as j,clearTokenCache as E}from"@zibby/core/backend-client.js";var y=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Y=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"},lark_docs:{id:"lark_docs",name:"Lark Docs",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function q(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let i=v($(import.meta.url)),e=T(i,"..","bin","mcp-skill.mjs");return R(e)?e:null}var B="2022-06-28",C="https://api.notion.com/v1",h=2e4,I=25,D=25,b=100,N=500,J=20*1024*1024;function u(i){if(!i||typeof i!="string")return null;let t=i.trim().split(/[?#]/)[0],n=t.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);if(n)return n[0].toLowerCase();let o=t.match(/[0-9a-fA-F]{32}/g);if(o&&o.length){let r=o[o.length-1].toLowerCase();return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}return null}async function p(i,e={}){let t=async()=>{let{token:n}=await j("notion");if(typeof n!="string"||!n)throw new Error(`Invalid notion token type: ${typeof n}`);let o=await fetch(`${C}${i}`,{method:e.method||"GET",headers:{Authorization:`Bearer ${n}`,"Notion-Version":B,Accept:"application/json",...e.body&&!e.formData?{"Content-Type":"application/json"}:{},...e.headers},body:e.formData?e.formData:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(`Notion API ${o.status}: ${s.slice(0,300)}`)}let r=await o.text().catch(()=>"");if(!r||!r.trim())return{};try{return JSON.parse(r)}catch{return{raw:r}}};try{return await t()}catch(n){let o=String(n?.message||n||"").toLowerCase();if(!(o.includes("token")||o.includes("401")||o.includes("unauthorized")))throw n;return E("notion"),t()}}function g(i){if(!Array.isArray(i))return"";let e="";for(let t of i){let n=t?.plain_text??t?.text?.content??"";if(!n)continue;let o=t.annotations||{};o.code&&(n=`\`${n}\``),o.bold&&(n=`**${n}**`),o.italic&&(n=`_${n}_`),o.strikethrough&&(n=`~~${n}~~`);let r=t?.href||t?.text?.link?.url;r&&(n=`[${n}](${r})`),e+=n}return e}function M(i,e,t){let n=i?.type,o=i?.[n]||{},r=" ".repeat(Math.max(0,e)),s=(c="rich_text")=>g(o[c]),a;switch(n){case"paragraph":a=s();break;case"heading_1":a=`# ${s()}`;break;case"heading_2":a=`## ${s()}`;break;case"heading_3":a=`### ${s()}`;break;case"bulleted_list_item":a=`${r}- ${s()}`;break;case"numbered_list_item":a=`${r}1. ${s()}`;break;case"to_do":a=`${r}- [${o.checked?"x":" "}] ${s()}`;break;case"toggle":a=`${r}- ${s()}`;break;case"quote":a=`> ${s()}`;break;case"callout":{a=`> ${o.icon?.emoji?`${o.icon.emoji} `:""}${s()}`;break}case"code":{a=`\`\`\`${o.language||""}
|
|
2
2
|
${s()}
|
|
3
3
|
\`\`\``;break}case"divider":a="---";break;case"child_page":a=`[child page: ${o.title||""}]`;break;case"child_database":a=`[child database: ${o.title||""}]`;break;case"bookmark":case"embed":case"link_preview":a=o.url?`<${o.url}>`:"";break;case"equation":a=o.expression?`$${o.expression}$`:"";break;case"table":case"column_list":case"column":a="";break;case"table_row":{let c=(o.cells||[]).map(l=>g(l).trim());a=`${r}| ${c.join(" | ")} |`;break}default:a=s();break}let d=[];return a&&a.trim()&&d.push(a),t&&t.trim()&&d.push(t),d.join(`
|
|
4
|
-
`)}async function A(i,e,t){let n=[],o,r=0;do{if(t.used>=h)break;let s=new URLSearchParams({page_size:"100"});o&&s.set("start_cursor",o);let a=await p(`/blocks/${i}/children?${s.toString()}`),d=Array.isArray(a.results)?a.results:[];for(let c of d){let l="";c.has_children&&(l=await A(c.id,e+1,t));let m=M(c,e,l);if(m&&(n.push(m),t.used+=m.length+1),t.used>=h)break}o=a.has_more?a.next_cursor:void 0,r+=1}while(o&&r<
|
|
4
|
+
`)}async function A(i,e,t){let n=[],o,r=0;do{if(t.used>=h)break;let s=new URLSearchParams({page_size:"100"});o&&s.set("start_cursor",o);let a=await p(`/blocks/${i}/children?${s.toString()}`),d=Array.isArray(a.results)?a.results:[];for(let c of d){let l="";c.has_children&&(l=await A(c.id,e+1,t));let m=M(c,e,l);if(m&&(n.push(m),t.used+=m.length+1),t.used>=h)break}o=a.has_more?a.next_cursor:void 0,r+=1}while(o&&r<D);return n.join(`
|
|
5
5
|
`)}function w(i){let e=i?.properties||{};for(let t of Object.values(e))if(t?.type==="title"){let n=g(t.title).trim();if(n)return n}return""}function f(i){let e=String(i??"");if(!e)return[{type:"text",text:{content:""}}];let t=[];for(let n=0;n<e.length;n+=2e3)t.push({type:"text",text:{content:e.slice(n,n+2e3)}});return t}function G(i){return{id:i?.id||"",discussionId:i?.discussion_id||"",text:g(i?.rich_text).trim(),author:i?.created_by?.id||"",createdTime:i?.created_time||""}}function F(i){if(!i||!i.type)return"";switch(i.type){case"title":return g(i.title).trim();case"rich_text":return g(i.rich_text).trim();case"number":return i.number==null?"":String(i.number);case"select":return i.select?.name||"";case"status":return i.status?.name||"";case"multi_select":return(i.multi_select||[]).map(t=>t.name).join(", ");case"checkbox":return i.checkbox?"true":"false";case"url":return i.url||"";case"email":return i.email||"";case"phone_number":return i.phone_number||"";case"date":return i.date?.start||"";case"people":return(i.people||[]).map(t=>t.name||t.id).join(", ");default:return""}}function k(i){return`https://www.notion.so/${String(i||"").replace(/-/g,"")}`}function K(i){let e=String(i??"").replace(/\r\n/g,`
|
|
6
6
|
`),t=[];for(let n of e.split(`
|
|
7
|
-
`)){let o=n.replace(/\s+$/,"");if(!o.trim())continue;let r=/^(#{1,3})\s+(.*)$/.exec(o),s=/^\s*[-*]\s+(.*)$/.exec(o),a=/^\s*\d+[.)]\s+(.*)$/.exec(o),d,c;r?(d=`heading_${r[1].length}`,c=r[2]):s?(d="bulleted_list_item",c=s[1]):a?(d="numbered_list_item",c=a[1]):(d="paragraph",c=o),t.push({object:"block",type:d,[d]:{rich_text:f(c)}})}return t}function P(i){return Array.isArray(i?.blocks)&&i.blocks.length?i.blocks.slice(0,N):typeof i?.markdown=="string"&&i.markdown.trim()?K(i.markdown).slice(0,N):null}async function x(i,e){for(let t=0;t<e.length;t+=b)await p(`/blocks/${i}/children`,{method:"PATCH",body:{children:e.slice(t,t+b)}})}function H(i){let e=typeof i=="string"?i.trim():"";if(!e)throw new Error("imagePath is required");if(!R(e)||!S(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=L(e);if(t.length>
|
|
7
|
+
`)){let o=n.replace(/\s+$/,"");if(!o.trim())continue;let r=/^(#{1,3})\s+(.*)$/.exec(o),s=/^\s*[-*]\s+(.*)$/.exec(o),a=/^\s*\d+[.)]\s+(.*)$/.exec(o),d,c;r?(d=`heading_${r[1].length}`,c=r[2]):s?(d="bulleted_list_item",c=s[1]):a?(d="numbered_list_item",c=a[1]):(d="paragraph",c=o),t.push({object:"block",type:d,[d]:{rich_text:f(c)}})}return t}function P(i){return Array.isArray(i?.blocks)&&i.blocks.length?i.blocks.slice(0,N):typeof i?.markdown=="string"&&i.markdown.trim()?K(i.markdown).slice(0,N):null}async function x(i,e){for(let t=0;t<e.length;t+=b)await p(`/blocks/${i}/children`,{method:"PATCH",body:{children:e.slice(t,t+b)}})}function H(i){let e=typeof i=="string"?i.trim():"";if(!e)throw new Error("imagePath is required");if(!R(e)||!S(e).isFile())throw new Error(`imagePath not found (or not a file): ${e}`);if(!/\.(png|jpe?g)$/i.test(e))throw new Error("imagePath must be a .png or .jpg/.jpeg file");let t=L(e);if(t.length>J)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 20MB (Notion single_part upload cap)`);return t}async function z(i){let e=H(i),t=U(i.trim()),n=/\.png$/i.test(t)?"image/png":"image/jpeg",r=(await p("/file_uploads",{method:"POST",body:{mode:"single_part",filename:t}}))?.id;if(!r)throw new Error("Notion file upload create returned no id");let s=new FormData;return s.set("file",new Blob([e],{type:n}),t),await p(`/file_uploads/${r}/send`,{method:"POST",formData:s}),r}var te={id:"notion",callsBackend:!0,serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:y.NOTION,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"Notion \u2014 read pages/databases as context + create pages, append blocks, and insert images",promptFragment:`## Notion
|
|
8
8
|
You can read Notion content as context AND write to Notion (create pages, append blocks, insert images).
|
|
9
9
|
- notion_get_page: pass a Notion page id OR a full Notion URL; returns { id, title, url, text } where text is the page flattened to markdown (truncated to ~20k chars). Use the text as reference context.
|
|
10
10
|
- notion_query_database: pass a database id/URL; returns a small list of rows ({ id, title, url, props }). Use to find a specific page, then notion_get_page it.
|
|
@@ -13,4 +13,4 @@ You can read Notion content as context AND write to Notion (create pages, append
|
|
|
13
13
|
- notion_insert_image: append an image block to a page. Pass { pageId, imagePath } for a LOCAL png/jpg file (\u226420MB, uploaded via Notion's File Upload API) or { pageId, imageUrl } for an external, publicly reachable image URL. Optional caption. Returns { ok, pageId, url }.
|
|
14
14
|
- notion_list_comments: pass a page/block id OR URL; returns the open comment discussions on it ({ id, discussionId, text, author }). Use to read the comment thread you are replying to.
|
|
15
15
|
- notion_add_comment: post a comment. To REPLY in an existing discussion pass { discussionId, text }; to start a NEW top-level comment on a page pass { pageId, text }. Returns { ok, id, discussionId }. Use this to answer a user who @mentioned Zibby in a Notion comment \u2014 reply in the SAME discussionId.
|
|
16
|
-
Do not block the task if Notion is unavailable \u2014 these tools return { ok:false, error } on failure; treat a missing page as "no extra context" / "cannot deliver to Notion" and continue.`,resolve(){let i=q();if(!i)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[i,"../dist/notion.js","notionSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(i,e){try{switch(i){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,n=u(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let o=await p(`/pages/${n}`),r=w(o),s=o?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,d=await A(n,0,{used:0}),c=!1;return d.length>h&&(d=d.slice(0,h),c=!0),JSON.stringify({ok:!0,id:n,title:r,url:s,text:d,...c?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,n=u(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let r={page_size:Math.max(1,Math.min(Number(e?.maxResults)||I,I))};e?.filter&&typeof e.filter=="object"&&(r.filter=e.filter);let s=await p(`/databases/${n}/query`,{method:"POST",body:r}),d=(Array.isArray(s.results)?s.results:[]).map(c=>{let l={};for(let[m,O]of Object.entries(c.properties||{})){let
|
|
16
|
+
Do not block the task if Notion is unavailable \u2014 these tools return { ok:false, error } on failure; treat a missing page as "no extra context" / "cannot deliver to Notion" and continue.`,resolve(){let i=q();if(!i)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[i,"../dist/notion.js","notionSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(i,e){try{switch(i){case"notion_get_page":{let t=e?.pageId||e?.page||e?.url||e?.id,n=u(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let o=await p(`/pages/${n}`),r=w(o),s=o?.url||`https://www.notion.so/${n.replace(/-/g,"")}`,d=await A(n,0,{used:0}),c=!1;return d.length>h&&(d=d.slice(0,h),c=!0),JSON.stringify({ok:!0,id:n,title:r,url:s,text:d,...c?{truncated:!0}:{}})}case"notion_query_database":{let t=e?.databaseId||e?.database||e?.url||e?.id,n=u(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let r={page_size:Math.max(1,Math.min(Number(e?.maxResults)||I,I))};e?.filter&&typeof e.filter=="object"&&(r.filter=e.filter);let s=await p(`/databases/${n}/query`,{method:"POST",body:r}),d=(Array.isArray(s.results)?s.results:[]).map(c=>{let l={};for(let[m,O]of Object.entries(c.properties||{})){let _=F(O);_&&(l[m]=_)}return{id:c.id,title:w(c),url:c.url||`https://www.notion.so/${String(c.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:n,count:d.length,hasMore:!!s.has_more,rows:d})}case"notion_create_page":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let n=e?.databaseId?u(e.databaseId):null,o=e?.parentPageId?u(e.parentPageId):u(e?.parent||e?.pageId);if(!n&&!o)return JSON.stringify({ok:!1,error:"A valid parentPageId or databaseId is required"});let r=n?{database_id:n}:{page_id:o},s={title:{title:f(t)}},a=P(e)||[],d=a.slice(0,b),c=await p("/pages",{method:"POST",body:{parent:r,properties:s,...d.length?{children:d}:{}}}),l=c?.id;if(!l)return JSON.stringify({ok:!1,error:"Notion page create returned no id"});let m=a.slice(b);return m.length&&await x(l,m),JSON.stringify({ok:!0,pageId:l,url:c?.url||k(l)})}case"notion_append_blocks":{let t=u(e?.pageId||e?.blockId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=P(e);return!n||!n.length?JSON.stringify({ok:!1,error:"markdown or blocks content is required"}):(await x(t,n),JSON.stringify({ok:!0,pageId:t,url:k(t)}))}case"notion_insert_image":{let t=u(e?.pageId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let n=typeof e?.caption=="string"&&e.caption.trim()?f(e.caption.trim()):null,o,r;if(typeof e?.imagePath=="string"&&e.imagePath.trim())r=await z(e.imagePath),o={type:"file_upload",file_upload:{id:r}};else if(typeof e?.imageUrl=="string"&&e.imageUrl.trim())o={type:"external",external:{url:e.imageUrl.trim()}};else return JSON.stringify({ok:!1,error:"imagePath (local png/jpg) or imageUrl is required"});return n&&(o.caption=n),await p(`/blocks/${t}/children`,{method:"PATCH",body:{children:[{object:"block",type:"image",image:o}]}}),JSON.stringify({ok:!0,pageId:t,url:k(t),...r?{fileUploadId:r}:{}})}case"notion_list_comments":{let t=e?.blockId||e?.pageId||e?.block||e?.page||e?.url||e?.id,n=u(t);if(!n)return JSON.stringify({ok:!1,error:"A valid Notion page/block id or URL is required"});let o=new URLSearchParams({block_id:n,page_size:"100"}),r=await p(`/comments?${o.toString()}`),a=(Array.isArray(r.results)?r.results:[]).map(G);return JSON.stringify({ok:!0,id:n,count:a.length,comments:a})}case"notion_add_comment":{let t=typeof e?.text=="string"?e.text:typeof e?.body=="string"?e.body:"";if(!t||!t.trim())return JSON.stringify({ok:!1,error:"text is required"});let n=e?.discussionId||e?.discussion_id||null,o;if(n)o={discussion_id:String(n),rich_text:f(t)};else{let s=e?.pageId||e?.page||e?.url||e?.id,a=u(s);if(!a)return JSON.stringify({ok:!1,error:"Either discussionId (to reply) or a valid pageId (to start a comment) is required"});o={parent:{page_id:a},rich_text:f(t)}}let r=await p("/comments",{method:"POST",body:o});return JSON.stringify({ok:!0,id:r?.id||"",discussionId:r?.discussion_id||n||""})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${i}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}},{name:"notion_create_page",description:"Create a new Notion page under a parent page (parentPageId) OR in a database (databaseId) \u2014 exactly one parent is required. Body from markdown (#/##/### headings, - bullets, 1. ordered lists; inline marks kept as literal text) or raw Notion block objects. Long bodies are chunked automatically (Notion caps 100 blocks/request). Returns { ok, pageId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{parentPageId:{type:"string",description:"Parent PAGE id/URL to create the page under (used when databaseId is absent)."},databaseId:{type:"string",description:"Parent DATABASE id/URL to create the page in (title goes into the title property)."},title:{type:"string",description:"Page title."},markdown:{type:"string",description:"Page body as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["title"]}},{name:"notion_append_blocks",description:"Append markdown (or raw Notion blocks) to the END of an existing Notion page. Accepts a page id or full Notion URL. Chunks automatically at Notion's 100-blocks-per-request cap. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},blocks:{type:"array",description:"Raw Notion block objects (advanced; used instead of markdown, max 500).",items:{type:"object",additionalProperties:!0}}},required:["pageId"]}},{name:"notion_insert_image",description:"Append an image block to a Notion page. Pass imagePath for a LOCAL .png/.jpg file (max 20MB \u2014 uploaded via Notion's File Upload API, stored by Notion) or imageUrl for an external publicly-reachable image URL. Optional caption. Returns { ok, pageId, url }.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 20MB). Preferred for locally rendered charts."},imageUrl:{type:"string",description:"External image URL (must be publicly reachable; used when imagePath is absent)."},caption:{type:"string",description:"Optional image caption."}},required:["pageId"]}},{name:"notion_list_comments",description:"List the open comment discussions on a Notion page/block. Accepts a page/block id OR a full Notion URL. Returns { ok, comments:[{ id, discussionId, text, author }] }. Use to read the comment thread you are replying to.",input_schema:{type:"object",properties:{blockId:{type:"string",description:"Notion page or block id (dashed UUID or 32-char) OR a full Notion URL."}},required:["blockId"]}},{name:"notion_add_comment",description:"Post a comment on Notion. To REPLY within an existing discussion, pass { discussionId, text }. To start a NEW top-level comment on a page, pass { pageId, text }. Returns { ok, id, discussionId }. Use this to answer a user who @mentioned Zibby in a Notion comment (reply in the same discussionId).",input_schema:{type:"object",properties:{discussionId:{type:"string",description:"The discussion_id to reply into (from notion_list_comments). Preferred for replies."},pageId:{type:"string",description:"Page id/URL to start a NEW top-level comment on (used when discussionId is absent)."},text:{type:"string",description:"The comment body (plain text)."}},required:["text"]}}]};export{K as markdownToNotionBlocks,p as notionApi,te as notionSkill,u as parseNotionId};
|