@zibby/skills 0.2.4 → 0.2.6

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.
@@ -27,6 +27,11 @@
27
27
  * POST /open-apis/docx/v1/documents/{id}/blocks/{block}/children
28
28
  * (block == document_id == the doc root) → append blocks at the end
29
29
  * GET /open-apis/wiki/v2/spaces/get_node?token={t} → { node:{obj_token,obj_type} }
30
+ *
31
+ * Wiki v2 API (write support — requires wiki:node:create / wiki:space:read):
32
+ * GET /open-apis/wiki/v2/spaces?page_size=50[&page_token] → { items:[{space_id,name}], has_more, page_token }
33
+ * POST /open-apis/wiki/v2/spaces/{space_id}/nodes → { node:{node_token,obj_token,obj_type} }
34
+ * (obj_type='docx', node_type='origin', optional parent_node_token)
30
35
  */
31
36
  /**
32
37
  * Derive the human-facing doc web URL from the open-api host + document id.
@@ -36,6 +41,12 @@
36
41
  * the product-domain URL still resolves for the user.
37
42
  */
38
43
  export declare function docWebUrl(host: any, id: any): string;
44
+ /**
45
+ * Derive the human-facing wiki node web URL (same region logic as docWebUrl).
46
+ * A wiki-resident doc is best shared by its /wiki/<node_token> link — opening
47
+ * it shows the doc in its wiki-space context.
48
+ */
49
+ export declare function wikiWebUrl(host: any, nodeToken: any): string;
39
50
  /**
40
51
  * Parse a Lark/Feishu doc reference (raw token OR URL) into { type, token }.
41
52
  * - .../docx/<token> → { type:'docx', token }
package/dist/larkDocs.js CHANGED
@@ -1,12 +1,13 @@
1
- import{existsSync as v,statSync as A,readFileSync as R}from"fs";import{fileURLToPath as P}from"url";import{basename as E,dirname as U,resolve as $}from"path";import{resolveIntegrationToken as D}from"@zibby/core/backend-client.js";var x=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),K=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},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=U(P(import.meta.url)),e=$(t,"..","bin","mcp-skill.mjs");return v(e)?e:null}var L=2e4,w=50,C=10*1024*1024,J=6e3*1e3,h=null;async function O(){let{appId:t,appSecret:e,host:n}=await D("lark");if(h&&h.appId===t&&h.expiresAt>Date.now())return{token:h.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 h={token:o.tenant_access_token,expiresAt:Date.now()+J,appId:t},{token:o.tenant_access_token,host:n}}async function l(t,e,n){let{token:r,host:o}=await O(),i={method:t,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}};t!=="GET"&&n!==void 0&&(i.body=JSON.stringify(n));let a=await(await fetch(`${o}${e}`,i)).json();if(a.code!==0)throw new Error(`Lark Docx API ${e} error: ${a.msg||a.code}`);return{data:a.data||{},host:o}}function f(t,e){return String(t||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function m(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e)return null;let n=e.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return n?{type:n[1],token:n[2]}:/^[A-Za-z0-9]{10,}$/.test(e)?{type:"docx",token:e}:null}async function k(t){let e=typeof t=="string"?m(t):t;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:n}=await l("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),r=n?.node||{};if(r.obj_type!=="docx"||!r.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${r.obj_type||"unknown"})`);return r.obj_token}function b(t){let e=String(t??"").replace(/\r\n/g,`
2
- `),n=[];for(let r of e.split(`
3
- `)){let o=r.replace(/\s+$/,"");if(!o.trim())continue;let i=/^(#{1,3})\s+(.*)$/.exec(o),s=/^\s*[-*]\s+(.*)$/.exec(o),a=/^\s*\d+[.)]\s+(.*)$/.exec(o),c,d,p;if(i){let u=i[1].length;c=`heading${u}`,d=2+u,p=i[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 y(t){let e=typeof t?.markdown=="string"?t.markdown:null,n=typeof t?.text=="string"?t.text:null;return e??n}async function S(t,e){let n;for(let r=0;r<e.length;r+=w){let o=e.slice(r,r+w);n=(await l("POST",`/open-apis/docx/v1/documents/${t}/blocks/${t}/children?document_revision_id=-1`,{children:o})).host}return n}function F(t){let e=typeof t=="string"?t.trim():"";if(!e)throw new Error("imagePath is required");if(!v(e)||!A(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=R(e);if(n.length>C)throw new Error(`image is ${(n.length/(1024*1024)).toFixed(1)}MB \u2014 max 10MB`);return n}async function q({fileName:t,parentNode:e,bytes:n}){let{token:r,host:o}=await O(),i=new FormData;i.set("file_name",t),i.set("parent_type","docx_image"),i.set("parent_node",e),i.set("size",String(n.length)),i.set("file",new Blob([n]),t);let a=await(await fetch(`${o}/open-apis/drive/v1/medias/upload_all`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:i})).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 B="docx",G=50;function T(t){return[{type:"text_run",text_run:{text:String(t??"")}}]}function M(t){return Array.isArray(t)?t.map(e=>e?.text_run?.text??e?.docs_link?.url??(e?.person?`@${e.person.user_id||""}`:"")).join(""):""}function H(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:M(n?.content?.elements),createTime:n?.create_time||""}))}}function I(t){return typeof t?.fileType=="string"&&t.fileType.trim()?t.fileType.trim():B}var V={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:x.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs
1
+ import{existsSync as v,statSync as O,readFileSync as R}from"fs";import{fileURLToPath as P}from"url";import{basename as E,dirname as U,resolve as $}from"path";import{resolveIntegrationToken as D}from"@zibby/core/backend-client.js";var S=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),X=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},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 n=U(P(import.meta.url)),e=$(n,"..","bin","mcp-skill.mjs");return v(e)?e:null}var b=2e4,T=50,C=50,J=20,F=10*1024*1024,q=6e3*1e3,_=null;async function A(){let{appId:n,appSecret:e,host:t}=await D("lark");if(_&&_.appId===n&&_.expiresAt>Date.now())return{token:_.token,host:t};let o=await(await fetch(`${t}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:n,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:n},{token:o.tenant_access_token,host:t}}async function p(n,e,t){let{token:i,host:o}=await A(),r={method:n,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json; charset=utf-8"}};n!=="GET"&&t!==void 0&&(r.body=JSON.stringify(t));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 y(n,e){return String(n||"").includes("feishu")?`https://feishu.cn/docx/${e}`:`https://www.larksuite.com/docx/${e}`}function G(n,e){return String(n||"").includes("feishu")?`https://feishu.cn/wiki/${e}`:`https://www.larksuite.com/wiki/${e}`}function h(n){if(!n||typeof n!="string")return null;let e=n.trim();if(!e)return null;let t=e.match(/\/(docx|wiki)\/([A-Za-z0-9]+)/);return t?{type:t[1],token:t[2]}:/^[A-Za-z0-9]{10,}$/.test(e)?{type:"docx",token:e}:null}async function f(n){let e=typeof n=="string"?h(n):n;if(!e)throw new Error("A valid Lark doc id or URL is required");if(e.type==="docx")return e.token;let{data:t}=await p("GET",`/open-apis/wiki/v2/spaces/get_node?token=${encodeURIComponent(e.token)}`),i=t?.node||{};if(i.obj_type!=="docx"||!i.obj_token)throw new Error(`Wiki node is not a docx document (obj_type=${i.obj_type||"unknown"})`);return i.obj_token}function I(n){let e=String(n??"").replace(/\r\n/g,`
2
+ `),t=[];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,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 x(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 B(n){let e=typeof n=="string"?n.trim():"";if(!e)throw new Error("imagePath is required");if(!v(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=R(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 N(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 W(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 L(n){return typeof n?.fileType=="string"&&n.fileType.trim()?n.fileType.trim():K}var ne={id:"lark-docs",serverName:"larkdocs",allowedTools:["mcp__larkdocs__*"],requiresIntegration:S.LARK,description:"Lark / Feishu Docs \u2014 read, create, append, and insert images into Lark documents (docx).",envKeys:[],promptFragment:`## Lark Docs
4
4
  You can read, create, and append Lark/Feishu documents (docx). This reuses the same connected Lark app as messaging.
5
5
  - larkdoc_get: pass a Lark doc id OR a full doc URL (a /docx/ or /wiki/ link); returns { ok, documentId, title, url, text } where text is the doc as plain text (truncated to ~20k chars). Use it as reference context.
6
- - larkdoc_create: create a new doc from a title + markdown/text (#/##/### headings, - bullets, 1. ordered supported); returns { ok, documentId, url }. Share the url.
6
+ - larkdoc_create: create a new doc from a title + markdown/text (#/##/### headings, - bullets, 1. ordered supported); returns { ok, documentId, url }. Share the url. To create the doc INSIDE a wiki space, first call larkwiki_list_spaces to find the space id, then pass wikiSpaceId (+ optional parentNodeToken to nest under a wiki node) \u2014 the doc is created as a wiki node and the returned url is the wiki link.
7
+ - larkwiki_list_spaces: list the wiki spaces the connected Lark app can see; returns { ok, spaces:[{ spaceId, name }] }. Use it to discover the wikiSpaceId before larkdoc_create.
7
8
  - larkdoc_append: append markdown/text to the end of an existing doc (pass the documentId or doc URL).
8
9
  - larkdoc_insert_image: append a LOCAL image file (png/jpg, \u226410MB) to the end of a doc \u2014 pass { documentId, imagePath, width?, height? } (width/height in px, optional). Returns { ok, documentId, blockId, url }. Use this to deliver a rendered chart/report image into the doc.
9
10
  - larkdoc_list_comments: list the comment threads on a doc (pass the documentId or doc URL); returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.
10
11
  - larkdoc_reply_comment: reply INSIDE an existing comment thread \u2014 pass { documentId, commentId, text }. Use this to answer a user who @mentioned Zibby in a doc comment (reply in the SAME commentId).
11
12
  - larkdoc_add_comment: post a NEW top-level comment on a doc \u2014 pass { documentId, text }.
12
- These tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.`,resolve(){let t=j();return t?{type:"stdio",command:"node",args:[t,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(t,e){try{switch(t){case"larkdoc_get":{let n=e?.documentId||e?.url||e?.id,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await k(r),i="";try{i=(await l("GET",`/open-apis/docx/v1/documents/${o}`)).data?.document?.title||""}catch{}let{data:s,host:a}=await l("GET",`/open-apis/docx/v1/documents/${o}/raw_content?lang=0`),c=String(s?.content||""),d=!1;return c.length>L&&(c=c.slice(0,L),d=!0),JSON.stringify({ok:!0,documentId:o,title:i,url:f(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{data:r,host:o}=await l("POST","/open-apis/docx/v1/documents",{title:n,...e?.folderToken?{folder_token:String(e.folderToken)}:{}}),i=r?.document?.document_id;if(!i)return JSON.stringify({ok:!1,error:"Lark Docs create returned no document_id"});let s=y(e);if(s&&s.trim()){let a=b(s);a.length&&await S(i,a)}return JSON.stringify({ok:!0,documentId:i,title:n,url:f(o,i)})}case"larkdoc_append":{let n=e?.documentId||e?.url||e?.id,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=y(e);if(!o||!o.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let i=await k(r),s=b(o);if(!s.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await S(i,s);return JSON.stringify({ok:!0,documentId:i,url:f(a,i)})}case"larkdoc_insert_image":{let n=e?.documentId||e?.url||e?.id,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let o=await k(r),i=e.imagePath.trim(),s=F(i),a=E(i),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 q({fileName:a,parentNode:d,bytes:s}),u={token:p},g=Number(e?.width),_=Number(e?.height);Number.isFinite(g)&&g>0&&(u.width=Math.round(g)),Number.isFinite(_)&&_>0&&(u.height=Math.round(_));let{host:N}=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:f(N,o)})}case"larkdoc_list_comments":{let n=e?.documentId||e?.url||e?.id||e?.fileToken,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await k(r),i=I(e),s=new URLSearchParams({file_type:i,page_size:String(G)}),{data:a}=await l("GET",`/open-apis/drive/v1/files/${o}/comments?${s.toString()}`),d=(Array.isArray(a?.items)?a.items:[]).map(H);return JSON.stringify({ok:!0,documentId:o,count:d.length,comments:d})}case"larkdoc_add_comment":{let n=e?.documentId||e?.url||e?.id||e?.fileToken,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=y({text:e?.text??e?.body});if(!o||!o.trim())return JSON.stringify({ok:!1,error:"text is required"});let i=await k(r),s=I(e),{data:a}=await l("POST",`/open-apis/drive/v1/files/${i}/comments?file_type=${encodeURIComponent(s)}`,{reply_list:{replies:[{content:{elements:T(o)}}]}});return JSON.stringify({ok:!0,documentId:i,commentId:a?.comment_id||""})}case"larkdoc_reply_comment":{let n=e?.documentId||e?.url||e?.id||e?.fileToken,r=m(n);if(!r)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=e?.commentId||e?.comment_id;if(!o)return JSON.stringify({ok:!1,error:"commentId is required"});let i=y({text:e?.text??e?.body});if(!i||!i.trim())return JSON.stringify({ok:!1,error:"text is required"});let s=await k(r),a=I(e),{data:c}=await l("POST",`/open-apis/drive/v1/files/${s}/comments/${encodeURIComponent(o)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:T(i)}});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). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."},folderToken:{type:"string",description:"Optional Lark drive folder token to create the doc in. Absent = the app root."}},required:["title"]}},{name:"larkdoc_append",description:"Append markdown/text content to the END of an existing Lark/Feishu document (docx). Accepts a documentId or a full Lark doc URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"larkdoc_insert_image",description:"Append a LOCAL image file (png/jpg, max 10MB) to the END of an existing Lark/Feishu document (docx). Accepts a documentId or full doc URL plus a local file path. Optional width/height in pixels. Returns { ok, documentId, blockId, fileToken, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 10MB)."},width:{type:"number",description:"Optional display width in pixels."},height:{type:"number",description:"Optional display height in pixels."}},required:["documentId","imagePath"]}},{name:"larkdoc_list_comments",description:"List the comment threads on a Lark/Feishu document. Accepts a documentId or full doc URL. Returns { ok, comments:[{ commentId, replies:[{ replyId, author, text }] }] }. Use to read the thread you are replying to.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'. Only change for non-docx files (doc/sheet/bitable/file/slides)."}},required:["documentId"]}},{name:"larkdoc_add_comment",description:"Post a NEW top-level comment on a Lark/Feishu document. Accepts a documentId or full doc URL plus text. Returns { ok, documentId, commentId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},text:{type:"string",description:"The comment body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","text"]}},{name:"larkdoc_reply_comment",description:"Reply INSIDE an existing comment thread on a Lark/Feishu document. Pass { documentId, commentId, text }. Use to answer a user who @mentioned Zibby in a doc comment (reply in the same commentId). Returns { ok, documentId, commentId, replyId }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Lark doc id (docx token) OR a full Lark/Feishu doc URL."},commentId:{type:"string",description:"The comment_id of the thread to reply into (from larkdoc_list_comments or the webhook event)."},text:{type:"string",description:"The reply body (plain text)."},fileType:{type:"string",description:"Drive file type \u2014 defaults to 'docx'."}},required:["documentId","commentId","text"]}}]};function ee(){h=null}export{ee as _resetLarkDocsTokenCache,f as docWebUrl,V as larkDocsSkill,b as markdownToLarkBlocks,m as parseLarkDocRef};
13
+ These tools return { ok:false, error } on failure \u2014 treat an unavailable Lark connection as "cannot read/deliver to Lark Docs" and continue rather than blocking the task.`,resolve(){let n=j();return n?{type:"stdio",command:"node",args:[n,"../dist/larkDocs.js","larkDocsSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(n,e){try{switch(n){case"larkdoc_get":{let t=e?.documentId||e?.url||e?.id,i=h(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await f(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 x(m,w)}return JSON.stringify({ok:!0,documentId:m,title:t,wikiSpaceId:i,wikiNodeToken:u.node_token||"",url:u.node_token?G(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 x(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=h(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 f(i),s=I(o);if(!s.length)return JSON.stringify({ok:!1,error:"no non-empty content to append"});let a=await x(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=h(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 f(i),r=e.imagePath.trim(),s=B(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=h(t);if(!i)return JSON.stringify({ok:!1,error:"A valid Lark doc id or URL is required"});let o=await f(i),r=L(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(W);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=h(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 f(i),s=L(e),{data:a}=await p("POST",`/open-apis/drive/v1/files/${r}/comments?file_type=${encodeURIComponent(s)}`,{reply_list:{replies:[{content:{elements:N(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=h(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 f(i),a=L(e),{data:c}=await p("POST",`/open-apis/drive/v1/files/${s}/comments/${encodeURIComponent(o)}/replies?file_type=${encodeURIComponent(a)}`,{content:{elements:N(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,h as parseLarkDocRef,G as wikiWebUrl};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/skills",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Built-in skill definitions for the Zibby agent-workflow framework",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -47,4 +47,4 @@ When user says "check out repo-name" or "clone repo-name":
47
47
  When user just wants to "look at" or "read" files (not clone):
48
48
  - Use github_get_file to read individual files via API`,resolve(){let p=ne();if(!p)return{command:null,args:[],env:{},description:this.description};let o={};for(let t of this.envKeys)process.env[t]&&(o[t]=process.env[t]);return{type:"stdio",command:"node",args:[p,"../dist/github.js","githubSkill"],env:o,description:this.description,alwaysLoad:!0}},async handleToolCall(p,o){try{switch(p){case"github_search_issues":{let t=o.query;if(!t)return JSON.stringify({error:"query is required"});let r=await u(`/search/issues?q=${encodeURIComponent(t)}&per_page=${o.limit||20}`),i=(r.items||[]).map(e=>({number:e.number,title:e.title,state:e.state,repo:e.repository_url?.split("/").slice(-2).join("/"),url:e.html_url,user:e.user?.login,isPR:!!e.pull_request,labels:(e.labels||[]).map(n=>n.name),createdAt:e.created_at}));return JSON.stringify({total:r.total_count,items:i})}case"github_search_code":{let t=o.query;if(!t)return JSON.stringify({error:"query is required"});let r=o.repo?`+repo:${o.repo}`:"",i=o.language?`+language:${o.language}`:"",e=await u(`/search/code?q=${encodeURIComponent(t)}${r}${i}&per_page=${o.limit||15}`),n=(e.items||[]).map(s=>({name:s.name,path:s.path,repo:s.repository?.full_name,url:s.html_url,score:s.score}));return JSON.stringify({total:e.total_count,items:n})}case"github_get_pr":{let{owner:t,repo:r,number:i}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/pulls/${i}`);return JSON.stringify({number:e.number,title:e.title,state:e.state,merged:e.merged,body:e.body?.slice(0,5e3),user:e.user?.login,branch:e.head?.ref,headSha:e.head?.sha,base:e.base?.ref,changedFiles:e.changed_files,additions:e.additions,deletions:e.deletions,createdAt:e.created_at,mergedAt:e.merged_at,url:e.html_url,labels:(e.labels||[]).map(n=>n.name)})}case"github_get_pr_diff":{let{owner:t,repo:r,number:i}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),n=e.length>15e3;return JSON.stringify({number:i,diff:n?e.slice(0,15e3):e,truncated:n,totalLength:e.length})}case"github_list_pr_files":{let{owner:t,repo:r,number:i}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:e.length,files:e.map(n=>({filename:n.filename,status:n.status,additions:n.additions,deletions:n.deletions,patch:n.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:r,number:i}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/pulls/${i}/comments?per_page=50`),n=await u(`/repos/${t}/${r}/issues/${i}/comments?per_page=50`),s=[...e.map(a=>({type:"review",user:a.user?.login,body:a.body?.slice(0,1e3),path:a.path,line:a.line,createdAt:a.created_at})),...n.map(a=>({type:"issue",user:a.user?.login,body:a.body?.slice(0,1e3),createdAt:a.created_at}))].sort((a,g)=>new Date(a.createdAt)-new Date(g.createdAt));return JSON.stringify({total:s.length,comments:s})}case"github_get_review_thread":{let{owner:t,repo:r,number:i,commentId:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let n=await u(`/repos/${t}/${r}/pulls/comments/${e}`),s=n.in_reply_to_id||n.id,a=[];try{a=await u(`/repos/${t}/${r}/pulls/${i}/comments?per_page=100`)}catch{a=[n]}(!Array.isArray(a)||a.length===0)&&(a=[n]);let g=a.filter(h=>h.id===s||h.in_reply_to_id===s).sort((h,b)=>new Date(h.created_at)-new Date(b.created_at)),d=g.length?g:[n],l=d.find(h=>h.id===s)||d[0];return JSON.stringify({rootCommentId:s,path:l.path,line:l.line??l.original_line??null,side:l.side||"RIGHT",diffHunk:typeof l.diff_hunk=="string"?l.diff_hunk.slice(0,3e3):null,commitId:l.commit_id||l.original_commit_id||null,notes:d.map(h=>({id:h.id,user:h.user?.login,body:(h.body||"").slice(0,4e3),createdAt:h.created_at,isRoot:h.id===s,url:h.html_url}))})}case"github_reply_review_thread":{let{owner:t,repo:r,number:i,commentId:e,body:n}=o||{};if(!t||!r||!i||!e||!n)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let s=await u(`/repos/${t}/${r}/pulls/${i}/comments/${e}/replies`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url,inReplyTo:s.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:t,repo:r,number:i,body:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:n.id,url:n.html_url})}case"github_create_review":{let{owner:t,repo:r,number:i,body:e,event:n,comments:s}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=(n||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(a))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${n})`});let g=Array.isArray(s)?s.filter(m=>m&&m.path&&m.body&&(m.line!=null||m.position!=null)).map(m=>{let c={path:m.path,body:String(m.body)};return m.line!=null?(c.line=Number(m.line),c.side=m.side==="LEFT"?"LEFT":"RIGHT"):c.position=Number(m.position),c}):[];if(a!=="APPROVE"&&!e&&g.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let d=new Set,l=null;try{for(let m=1;m<=20;m+=1){let c=await u(`/repos/${t}/${r}/pulls/${i}/comments?per_page=100&page=${m}`);if(!Array.isArray(c)||c.length===0)break;for(let f of c){let $=H(f.body);$&&d.add($)}if(c.length<100)break}for(let m=1;m<=20&&l==null;m+=1){let c=await u(`/repos/${t}/${r}/issues/${i}/comments?per_page=100&page=${m}`);if(!Array.isArray(c)||c.length===0)break;for(let f of c)if(J(f.body)){l=f.id;break}if(c.length<100)break}}catch{}let h=!1,b=!1;if(e){let m=`${String(e)}${x}`;try{l!=null?(await u(`/repos/${t}/${r}/issues/comments/${l}`,{method:"PATCH",body:{body:m}}),h=!0):await u(`/repos/${t}/${r}/issues/${i}/comments`,{method:"POST",body:{body:m}}),b=!0}catch{}}let{toPost:y,skipped:w}=U(g,d),_=y.map(({_fp:m,...c})=>c),S=null;if(_.length>0||a==="APPROVE"||a==="REQUEST_CHANGES"){let m={event:a};_.length>0&&(m.comments=_),_.length===0&&a==="REQUEST_CHANGES"&&(m.body="Changes requested \u2014 see the review summary comment."),S=await u(`/repos/${t}/${r}/pulls/${i}/reviews`,{method:"POST",body:m})}return JSON.stringify({ok:!0,id:S?S.id:void 0,state:S?S.state:void 0,event:a,notePosted:b,summaryUpdated:h,commentsPosted:_.length,inlineSkipped:w||void 0,url:S?S.html_url:void 0})}case"github_list_commits":{let{owner:t,repo:r,branch:i,path:e,limit:n,since:s,until:a,page:g}=o;if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let d=Math.min(Number(n)||20,100),l=`/repos/${t}/${r}/commits?per_page=${d}&page=${Number(g)||1}`;i&&(l+=`&sha=${encodeURIComponent(i)}`),e&&(l+=`&path=${encodeURIComponent(e)}`),s&&(l+=`&since=${encodeURIComponent(s)}`),a&&(l+=`&until=${encodeURIComponent(a)}`);let h=await u(l);return JSON.stringify({total:h.length,page:Number(g)||1,hasMore:h.length>=d,commits:h.map(b=>({sha:b.sha?.slice(0,8),fullSha:b.sha,message:b.commit?.message?.slice(0,300),author:b.commit?.author?.name,authorEmail:b.commit?.author?.email,date:b.commit?.author?.date,url:b.html_url}))})}case"github_get_commit":{let{owner:t,repo:r,sha:i,includePrs:e}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let n=await u(`/repos/${t}/${r}/commits/${i}`),s;if(e)try{let a=await u(`/repos/${t}/${r}/commits/${i}/pulls`);s=(Array.isArray(a)?a:[]).map(g=>({number:g.number,title:g.title,state:g.state,merged:!!g.merged_at,webUrl:g.html_url}))}catch{s=[]}return JSON.stringify({sha:n.sha?.slice(0,8),message:n.commit?.message,author:n.commit?.author?.name,date:n.commit?.author?.date,stats:n.stats,files:(n.files||[]).map(a=>({filename:a.filename,status:a.status,additions:a.additions,deletions:a.deletions,patch:a.patch?.slice(0,3e3)})),...s?{pullRequests:s}:{}})}case"github_get_file":{let{owner:t,repo:r,path:i,ref:e}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and path are required"});let n=`/repos/${t}/${r}/contents/${encodeURIComponent(i)}`;e&&(n+=`?ref=${encodeURIComponent(e)}`);let s=await u(n);if(s.type!=="file")return Array.isArray(s)?JSON.stringify({type:"directory",path:i,entries:s.map(d=>({name:d.name,type:d.type,size:d.size,path:d.path}))}):JSON.stringify({error:`Not a file: ${s.type}`});let a=Buffer.from(s.content||"","base64").toString("utf-8"),g=a.length>2e4;return JSON.stringify({path:s.path,size:s.size,sha:s.sha?.slice(0,8),content:g?a.slice(0,2e4):a,truncated:g})}case"github_get_user":try{let t=await u("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let r=t.repositories[0],i=r.owner.login,e=r.owner.type,n=e==="Organization"?`/orgs/${i}`:`/users/${i}`,s=await u(n);return JSON.stringify({login:s.login,name:s.name||s.login,avatar:s.avatar_url,bio:s.bio||s.description,type:e,isOrg:e==="Organization",publicRepos:s.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(t){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${t.message})`})}case"github_list_orgs":try{let r=(await u("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let n of r)n.owner.type==="Organization"&&(i.has(n.owner.login)||i.set(n.owner.login,{login:n.owner.login,description:null,url:n.owner.url}));let e=Array.from(i.values());return JSON.stringify({count:e.length,orgs:e,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(t){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${t.message}`})}case"github_clone":{let y=function(m){let c=m.replace(/^~(?=$|\/|\\)/,b);return s(c)},{owner:t,repo:r,destination:i}=o;if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let{execSync:e}=await import("child_process"),{join:n,resolve:s}=await import("path"),{existsSync:a,mkdirSync:g}=await import("fs"),{homedir:d,platform:l}=await import("os"),{token:h}=await j("github"),b=d(),w=i?y(i):n(b,"zibby-repos"),_=n(w,r);if(g(w,{recursive:!0}),a(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});let S=`https://x-access-token:${h}@github.com/${t}/${r}.git`;try{e(`git clone ${S} "${_}"`,{stdio:"pipe"});let m=`https://github.com/${t}/${r}.git`;G(e,_,m,h,"github_clone");let c=l()==="win32",f;return c?f=e(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):f=e(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${t}/${r} to ${_}`,contents:f.split(`
49
49
  `).slice(0,30).join(`
50
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(m){let f=String(m.message||m).split(h).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${f}`})}}case"github_search_repos":{let{query:t,limit:r}=o;if(!t)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(i);if(e.error)return JSON.stringify(e);let n=t.toLowerCase(),s=e.repos.filter(a=>a.name.toLowerCase().includes(n)||a.fullName.toLowerCase().includes(n)||a.description&&a.description.toLowerCase().includes(n));return JSON.stringify({query:t,count:s.length,repos:s.slice(0,r||20)})}case"github_list_repos":{let{owner:t,type:r,sort:i,direction:e,limit:n,query:s}=o,a=100,g=n||200,d=[],l=c=>({name:c.name,fullName:c.full_name,private:c.private,description:c.description,language:c.language,defaultBranch:c.default_branch,updatedAt:c.updated_at,stars:c.stargazers_count,url:c.html_url,fullPath:c.full_name,webUrl:c.html_url,visibility:c.visibility||(c.private?"private":"public")}),h=c=>{if(!s)return!0;let f=String(s).toLowerCase();return c.name&&c.name.toLowerCase().includes(f)||c.fullName&&c.fullName.toLowerCase().includes(f)||c.description&&c.description.toLowerCase().includes(f)};if(!t){let c=1,f=!0;for(;f&&d.length<g;){let k=`/installation/repositories?per_page=${a}&page=${c}`,P=(await u(k)).repositories||[];if(P.length===0)break;d=d.concat(P),f=P.length===a,c++}let $=d.map(l).filter(h),N=$.slice(0,g),W=$.length>N.length,T=N.filter(k=>k.private).length,C=N.filter(k=>!k.private).length;return JSON.stringify({count:N.length,repos:N,truncated:W,privateCount:T,publicCount:C,message:`Found ${T} private and ${C} public repos`})}let b=await u(`/orgs/${t}`).then(()=>!0).catch(()=>!1),y=1,w=!0;for(;w&&d.length<g;){let c;b?c=`/orgs/${t}/repos?per_page=${a}&page=${y}&type=${r||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`:c=`/users/${t}/repos?per_page=${a}&page=${y}&type=${r||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`;let f=await u(c),$=Array.isArray(f)?f:[];if($.length===0)break;d=d.concat($),w=$.length===a,y++}let _=d.map(l).filter(h),S=_.slice(0,g),m=_.length>S.length;return JSON.stringify({count:S.length,repos:S,truncated:m})}case"github_create_pr":{let{owner:t,repo:r,head:i,title:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let n=o.base;if(!n)try{n=(await u(`/repos/${t}/${r}`)).default_branch||"main"}catch{n="main"}let s={title:String(e),head:String(i),base:String(n),body:o.body?String(o.body):"",draft:!!o.draft};try{let a=await u(`/repos/${t}/${r}/pulls`,{method:"POST",body:s});return JSON.stringify({success:!0,pr_url:a.html_url,number:a.number,branch:i,base:n,repo:`${t}/${r}`,provider:"github",draft:!!a.draft,state:a.state})}catch(a){let g=String(a.message||a);if(/GitHub API 422/.test(g))return JSON.stringify({success:!1,branch:i,base:n,repo:`${t}/${r}`,provider:"github",skippedReason:g});throw a}}case"github_merge_pr":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=o.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(e))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${e})`});let n={merge_method:e};o.commitTitle&&(n.commit_title=String(o.commitTitle)),o.commitMessage&&(n.commit_message=String(o.commitMessage));try{let s=await u(`/repos/${t}/${r}/pulls/${i}/merge`,{method:"PUT",body:n});return JSON.stringify({success:!0,merged:!0,sha:s.sha,number:i,provider:"github"})}catch(s){let a=String(s.message||s);if(/GitHub API (405|409|404)/.test(a))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:a});throw s}}case"github_create_issue":{let{owner:t,repo:r,title:i,body:e}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and title are required"});let n=await u(`/repos/${t}/${r}/issues`,{method:"POST",body:{title:i,body:e||""}});return JSON.stringify({number:n.number,url:n.html_url,title:n.title})}case"github_list_issues":{let{owner:t,repo:r,state:i,labels:e,since:n,assignee:s,sort:a,direction:g,limit:d}=o||{};if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let l=new URLSearchParams;l.set("state",i||"open"),l.set("per_page",String(d||30)),l.set("sort",a||"updated"),l.set("direction",g||"desc"),e&&l.set("labels",Array.isArray(e)?e.join(","):e),n&&l.set("since",n),s&&l.set("assignee",s);let h=await u(`/repos/${t}/${r}/issues?${l.toString()}`),b=(Array.isArray(h)?h:[]).filter(y=>!y.pull_request).map(y=>({number:y.number,title:y.title,state:y.state,labels:(y.labels||[]).map(w=>typeof w=="string"?w:w.name),assignee:y.assignee?.login||null,assignees:(y.assignees||[]).map(w=>w.login),user:y.user?.login,comments:y.comments,url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at}));return JSON.stringify({count:b.length,issues:b})}case"github_get_issue":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/issues/${i}`);return e.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:e.number,title:e.title,body:e.body||"",state:e.state,stateReason:e.state_reason||null,labels:(e.labels||[]).map(n=>typeof n=="string"?n:n.name),assignee:e.assignee?.login||null,assignees:(e.assignees||[]).map(n=>n.login),user:e.user?.login,milestone:e.milestone?.title||null,comments:e.comments,url:e.html_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:r,number:i,limit:e}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments?per_page=${e||100}`),s=(Array.isArray(n)?n:[]).map(a=>({id:a.id,user:a.user?.login,body:a.body||"",createdAt:a.created_at,updatedAt:a.updated_at,url:a.html_url}));return JSON.stringify({count:s.length,comments:s})}case"github_add_issue_comment":{let{owner:t,repo:r,number:i,body:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments`,{method:"POST",body:{body:e}});return JSON.stringify({ok:!0,id:n.id,url:n.html_url})}case"github_close_issue":{let{owner:t,repo:r,number:i,stateReason:e}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n={state:"closed"};e&&(n.state_reason=e);let s=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:n});return JSON.stringify({ok:!0,number:s.number,state:s.state,stateReason:s.state_reason||null,url:s.html_url})}case"github_reopen_issue":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:e.number,state:e.state,url:e.html_url})}case"github_label_issue":{let{owner:t,repo:r,number:i,labels:e,mode:n}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=Array.isArray(e)?e:e?[e]:[];if(!s.length)return JSON.stringify({error:"labels (string or array) is required"});let a=n||"add";if(a==="set"){let d=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:{labels:s}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}if(a==="remove"){for(let l of s)await u(`/repos/${t}/${r}/issues/${i}/labels/${encodeURIComponent(l)}`,{method:"DELETE"});let d=await u(`/repos/${t}/${r}/issues/${i}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}let g=await u(`/repos/${t}/${r}/issues/${i}/labels`,{method:"POST",body:{labels:s}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(g)?g:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${p}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};var F=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,z=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,ie=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,oe=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,M="in progress",D="blocked";function K(p,o=[]){if(p==="closed")return"done";if(p!=="open")return"unknown";let t=(o||[]).map(String);return t.some(r=>F.test(r))?"blocked":t.some(r=>z.test(r))?"in_progress":"todo"}function v(p={}){let o=p.owner||process.env.GITHUB_OWNER,t=p.repo||process.env.GITHUB_REPO;if(!o||!t)throw new Error("GitHub scope missing: provide {owner, repo} via ctx or env GITHUB_OWNER / GITHUB_REPO.");return{owner:o,repo:t}}function O(p){let o=JSON.parse(p);if(o&&o.error)throw new Error(o.error);return o}function E(p,o={}){let t=p.labels||[],r=p.number,i=o.owner&&o.repo?`${o.owner}/${o.repo}#${r}`:`#${r}`;return{id:String(r),key:i,title:p.title||"",body:p.body||"",state:p.state||null,stateCategory:K(p.state,t),assignee:p.assignee||p.assignees&&p.assignees[0]||null,url:p.url||null,_raw:p}}var se={id:"github",toStateCategory:K,toNeutral:E,IN_PROGRESS_LABEL:M,BLOCKED_LABEL:D,async listCandidates(p={}){let o=p.ctx||{},{owner:t,repo:r}=v(o);return(O(await R.handleToolCall("github_list_issues",{owner:t,repo:r,state:p.state||"open",labels:p.labels,since:p.updatedAfter,limit:p.limit})).issues||[]).map(e=>E(e,{owner:t,repo:r}))},async getTicket(p,o={}){let{owner:t,repo:r}=v(o),i=A(p);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let e=JSON.parse(await R.handleToolCall("github_get_issue",{owner:t,repo:r,number:i}));return e.error?null:E(e,{owner:t,repo:r})},async getComments(p,o={}){let{owner:t,repo:r}=v(o),i=A(p);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);return(O(await R.handleToolCall("github_get_issue_comments",{owner:t,repo:r,number:i})).comments||[]).map(n=>({id:String(n.id),author:n.user||"Unknown",body:n.body||"",createdAt:n.createdAt||null,updatedAt:n.updatedAt||null,_raw:n})).sort((n,s)=>String(s.createdAt).localeCompare(String(n.createdAt)))},async addComment(p,o,t={}){let{owner:r,repo:i}=v(t),e=A(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!o)throw new Error("body is required");let n=O(await R.handleToolCall("github_add_issue_comment",{owner:r,repo:i,number:e,body:o}));return{ok:!!n.ok,id:n.id?String(n.id):null}},async transition(p,o,t={}){let{owner:r,repo:i}=v(t),e=A(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let n=String(o||"");if(ie.test(n)){let s=O(await R.handleToolCall("github_close_issue",{owner:r,repo:i,number:e,stateReason:"completed"}));return{ok:!!s.ok,stateAfter:s.state||"closed",stateCategoryAfter:"done",_raw:s}}if(F.test(n)){await B(r,i,e);let s=O(await R.handleToolCall("github_label_issue",{owner:r,repo:i,number:e,labels:[D],mode:"add"}));return{ok:!!s.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:s}}if(z.test(n)){await B(r,i,e);let s=O(await R.handleToolCall("github_label_issue",{owner:r,repo:i,number:e,labels:[M],mode:"add"}));return{ok:!!s.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:s}}if(oe.test(n)){let s=O(await R.handleToolCall("github_reopen_issue",{owner:r,repo:i,number:e}));return{ok:!!s.ok,stateAfter:s.state||"open",stateCategoryAfter:"todo",_raw:s}}return{ok:!1,error:`GitHub issues have no "${o}" state. Representable targets: open/todo, in progress, blocked, done/closed.`}},async linkPullRequest(p,o,t,r={}){let{owner:i,repo:e}=v(r),n=A(p);if(n==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!o)throw new Error("prUrl is required");let s=`${t?`${t}: `:"Linked PR: "}${o}`;return{ok:!!O(await R.handleToolCall("github_add_issue_comment",{owner:i,repo:e,number:n,body:s})).ok,via:"comment"}}};async function B(p,o,t){await R.handleToolCall("github_reopen_issue",{owner:p,repo:o,number:t})}function A(p){if(p==null)return null;if(typeof p=="number")return p;let o=/(\d+)\s*$/.exec(String(p));return o?Number(o[1]):null}var qe=se;export{qe as default,se as githubAdapter};
50
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(m){let f=String(m.message||m).split(h).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${f}`})}}case"github_search_repos":{let{query:t,limit:r}=o;if(!t)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(i);if(e.error)return JSON.stringify(e);let n=t.toLowerCase(),s=e.repos.filter(a=>a.name.toLowerCase().includes(n)||a.fullName.toLowerCase().includes(n)||a.description&&a.description.toLowerCase().includes(n));return JSON.stringify({query:t,count:s.length,repos:s.slice(0,r||20)})}case"github_list_repos":{let{owner:t,type:r,sort:i,direction:e,limit:n,query:s}=o,a=100,g=n||200,d=[],l=c=>({name:c.name,fullName:c.full_name,private:c.private,description:c.description,language:c.language,defaultBranch:c.default_branch,updatedAt:c.updated_at,stars:c.stargazers_count,url:c.html_url,fullPath:c.full_name,webUrl:c.html_url,visibility:c.visibility||(c.private?"private":"public")}),h=c=>{if(!s)return!0;let f=String(s).toLowerCase();return c.name&&c.name.toLowerCase().includes(f)||c.fullName&&c.fullName.toLowerCase().includes(f)||c.description&&c.description.toLowerCase().includes(f)};if(!t){let c=1,f=!0;for(;f&&d.length<g;){let A=`/installation/repositories?per_page=${a}&page=${c}`,P=(await u(A)).repositories||[];if(P.length===0)break;d=d.concat(P),f=P.length===a,c++}let $=d.map(l).filter(h),N=$.slice(0,g),W=$.length>N.length,T=N.filter(A=>A.private).length,C=N.filter(A=>!A.private).length;return JSON.stringify({count:N.length,repos:N,truncated:W,privateCount:T,publicCount:C,message:`Found ${T} private and ${C} public repos`})}let b=await u(`/orgs/${t}`).then(()=>!0).catch(()=>!1),y=1,w=!0;for(;w&&d.length<g;){let c;b?c=`/orgs/${t}/repos?per_page=${a}&page=${y}&type=${r||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`:c=`/users/${t}/repos?per_page=${a}&page=${y}&type=${r||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`;let f=await u(c),$=Array.isArray(f)?f:[];if($.length===0)break;d=d.concat($),w=$.length===a,y++}let _=d.map(l).filter(h),S=_.slice(0,g),m=_.length>S.length;return JSON.stringify({count:S.length,repos:S,truncated:m})}case"github_create_pr":{let{owner:t,repo:r,head:i,title:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let n=o.base;if(!n)try{n=(await u(`/repos/${t}/${r}`)).default_branch||"main"}catch{n="main"}let s={title:String(e),head:String(i),base:String(n),body:o.body?String(o.body):"",draft:!!o.draft};try{let a=await u(`/repos/${t}/${r}/pulls`,{method:"POST",body:s});return JSON.stringify({success:!0,pr_url:a.html_url,number:a.number,branch:i,base:n,repo:`${t}/${r}`,provider:"github",draft:!!a.draft,state:a.state})}catch(a){let g=String(a.message||a);if(/GitHub API 422/.test(g))return JSON.stringify({success:!1,branch:i,base:n,repo:`${t}/${r}`,provider:"github",skippedReason:g});throw a}}case"github_merge_pr":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=o.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(e))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${e})`});let n={merge_method:e};o.commitTitle&&(n.commit_title=String(o.commitTitle)),o.commitMessage&&(n.commit_message=String(o.commitMessage));try{let s=await u(`/repos/${t}/${r}/pulls/${i}/merge`,{method:"PUT",body:n});return JSON.stringify({success:!0,merged:!0,sha:s.sha,number:i,provider:"github"})}catch(s){let a=String(s.message||s);if(/GitHub API (405|409|404)/.test(a))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:a});throw s}}case"github_create_issue":{let{owner:t,repo:r,title:i,body:e}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and title are required"});let n=await u(`/repos/${t}/${r}/issues`,{method:"POST",body:{title:i,body:e||""}});return JSON.stringify({number:n.number,url:n.html_url,title:n.title})}case"github_list_issues":{let{owner:t,repo:r,state:i,labels:e,since:n,assignee:s,sort:a,direction:g,limit:d}=o||{};if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let l=new URLSearchParams;l.set("state",i||"open"),l.set("per_page",String(d||30)),l.set("sort",a||"updated"),l.set("direction",g||"desc"),e&&l.set("labels",Array.isArray(e)?e.join(","):e),n&&l.set("since",n),s&&l.set("assignee",s);let h=await u(`/repos/${t}/${r}/issues?${l.toString()}`),b=(Array.isArray(h)?h:[]).filter(y=>!y.pull_request).map(y=>({number:y.number,title:y.title,state:y.state,labels:(y.labels||[]).map(w=>typeof w=="string"?w:w.name),assignee:y.assignee?.login||null,assignees:(y.assignees||[]).map(w=>w.login),user:y.user?.login,comments:y.comments,url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at}));return JSON.stringify({count:b.length,issues:b})}case"github_get_issue":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/issues/${i}`);return e.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:e.number,title:e.title,body:e.body||"",state:e.state,stateReason:e.state_reason||null,labels:(e.labels||[]).map(n=>typeof n=="string"?n:n.name),assignee:e.assignee?.login||null,assignees:(e.assignees||[]).map(n=>n.login),user:e.user?.login,milestone:e.milestone?.title||null,comments:e.comments,url:e.html_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:r,number:i,limit:e}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments?per_page=${e||100}`),s=(Array.isArray(n)?n:[]).map(a=>({id:a.id,user:a.user?.login,body:a.body||"",createdAt:a.created_at,updatedAt:a.updated_at,url:a.html_url}));return JSON.stringify({count:s.length,comments:s})}case"github_add_issue_comment":{let{owner:t,repo:r,number:i,body:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments`,{method:"POST",body:{body:e}});return JSON.stringify({ok:!0,id:n.id,url:n.html_url})}case"github_close_issue":{let{owner:t,repo:r,number:i,stateReason:e}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n={state:"closed"};e&&(n.state_reason=e);let s=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:n});return JSON.stringify({ok:!0,number:s.number,state:s.state,stateReason:s.state_reason||null,url:s.html_url})}case"github_reopen_issue":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:e.number,state:e.state,url:e.html_url})}case"github_label_issue":{let{owner:t,repo:r,number:i,labels:e,mode:n}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=Array.isArray(e)?e:e?[e]:[];if(!s.length)return JSON.stringify({error:"labels (string or array) is required"});let a=n||"add";if(a==="set"){let d=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:{labels:s}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}if(a==="remove"){for(let l of s)await u(`/repos/${t}/${r}/issues/${i}/labels/${encodeURIComponent(l)}`,{method:"DELETE"});let d=await u(`/repos/${t}/${r}/issues/${i}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}let g=await u(`/repos/${t}/${r}/issues/${i}/labels`,{method:"POST",body:{labels:s}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(g)?g:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${p}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};var F=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,z=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,ie=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,oe=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,M="in progress",D="blocked";function K(p,o=[]){if(p==="closed")return"done";if(p!=="open")return"unknown";let t=(o||[]).map(String);return t.some(r=>F.test(r))?"blocked":t.some(r=>z.test(r))?"in_progress":"todo"}function v(p={}){let o=p.owner||process.env.GITHUB_OWNER,t=p.repo||process.env.GITHUB_REPO;if(!o||!t)throw new Error("GitHub scope missing: provide {owner, repo} via ctx or env GITHUB_OWNER / GITHUB_REPO.");return{owner:o,repo:t}}function O(p){let o=JSON.parse(p);if(o&&o.error)throw new Error(o.error);return o}function E(p,o={}){let t=p.labels||[],r=p.number,i=o.owner&&o.repo?`${o.owner}/${o.repo}#${r}`:`#${r}`;return{id:String(r),key:i,title:p.title||"",body:p.body||"",state:p.state||null,stateCategory:K(p.state,t),assignee:p.assignee||p.assignees&&p.assignees[0]||null,url:p.url||null,_raw:p}}var se={id:"github",toStateCategory:K,toNeutral:E,IN_PROGRESS_LABEL:M,BLOCKED_LABEL:D,async listCandidates(p={}){let o=p.ctx||{},{owner:t,repo:r}=v(o);return(O(await R.handleToolCall("github_list_issues",{owner:t,repo:r,state:p.state||"open",labels:p.labels,since:p.updatedAfter,limit:p.limit})).issues||[]).map(e=>E(e,{owner:t,repo:r}))},async getTicket(p,o={}){let{owner:t,repo:r}=v(o),i=k(p);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let e=JSON.parse(await R.handleToolCall("github_get_issue",{owner:t,repo:r,number:i}));return e.error?null:E(e,{owner:t,repo:r})},async getComments(p,o={}){let{owner:t,repo:r}=v(o),i=k(p);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);return(O(await R.handleToolCall("github_get_issue_comments",{owner:t,repo:r,number:i})).comments||[]).map(n=>({id:String(n.id),author:n.user||"Unknown",body:n.body||"",createdAt:n.createdAt||null,updatedAt:n.updatedAt||null,_raw:n})).sort((n,s)=>String(s.createdAt).localeCompare(String(n.createdAt)))},async addComment(p,o,t={}){let{owner:r,repo:i}=v(t),e=k(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!o)throw new Error("body is required");let n=O(await R.handleToolCall("github_add_issue_comment",{owner:r,repo:i,number:e,body:o}));return{ok:!!n.ok,id:n.id?String(n.id):null}},async transition(p,o,t={}){let{owner:r,repo:i}=v(t),e=k(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let n=String(o||"");if(ie.test(n)){let s=O(await R.handleToolCall("github_close_issue",{owner:r,repo:i,number:e,stateReason:"completed"}));return{ok:!!s.ok,stateAfter:s.state||"closed",stateCategoryAfter:"done",_raw:s}}if(F.test(n)){await B(r,i,e);let s=O(await R.handleToolCall("github_label_issue",{owner:r,repo:i,number:e,labels:[D],mode:"add"}));return{ok:!!s.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:s}}if(z.test(n)){await B(r,i,e);let s=O(await R.handleToolCall("github_label_issue",{owner:r,repo:i,number:e,labels:[M],mode:"add"}));return{ok:!!s.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:s}}if(oe.test(n)){let s=O(await R.handleToolCall("github_reopen_issue",{owner:r,repo:i,number:e}));return{ok:!!s.ok,stateAfter:s.state||"open",stateCategoryAfter:"todo",_raw:s}}return{ok:!1,error:`GitHub issues have no "${o}" state. Representable targets: open/todo, in progress, blocked, done/closed.`}},async linkPullRequest(p,o,t,r={}){let{owner:i,repo:e}=v(r),n=k(p);if(n==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!o)throw new Error("prUrl is required");let s=`${t?`${t}: `:"Linked PR: "}${o}`;return{ok:!!O(await R.handleToolCall("github_add_issue_comment",{owner:i,repo:e,number:n,body:s})).ok,via:"comment"}}};async function B(p,o,t){await R.handleToolCall("github_reopen_issue",{owner:p,repo:o,number:t})}function k(p){if(p==null)return null;if(typeof p=="number")return p;let o=/(\d+)\s*$/.exec(String(p));return o?Number(o[1]):null}var qe=se;export{qe as default,se as githubAdapter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/skills",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Built-in skill definitions for the Zibby agent-workflow framework",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",