@zibby/skills 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/figma.js CHANGED
@@ -1,4 +1,4 @@
1
- import{existsSync as b}from"fs";import{fileURLToPath as S}from"url";import{dirname as N,resolve as k}from"path";import{resolveIntegrationToken as O}from"@zibby/core/backend-client.js";var h=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),A=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 L(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let e=N(S(import.meta.url)),n=k(e,"..","bin","mcp-skill.mjs");return b(n)?n:null}async function f(e,n={}){let{token:i}=await O("figma"),r=e.startsWith("https://")?e:`https://api.figma.com${e}`,s={"X-Figma-Token":i,Accept:"application/json",...n.body?{"Content-Type":"application/json"}:{}},o=await fetch(r,{method:n.method||"GET",headers:s,body:n.body?JSON.stringify(n.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(`Figma API ${o.status}: ${a.slice(0,300)}`)}return o.json()}function g(e){let n=String(e||"").trim(),i=n.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return i?i[1]:n}function u(e){return e==null?void 0:(Array.isArray(e)?e:String(e).split(",")).map(i=>String(i).trim().replace(/-/g,":")).filter(Boolean).join(",")}function I(e){let n=String(e||"").match(/[?&]node-id=([^&]+)/i);return n?decodeURIComponent(n[1]).replace(/-/g,":"):void 0}var p=e=>typeof e=="number"?Math.round(e*100)/100:e;function _(e){if(!e)return null;let n=r=>Math.round((r??0)*255).toString(16).padStart(2,"0"),i={hex:`#${n(e.r)}${n(e.g)}${n(e.b)}`.toUpperCase()};return e.a!=null&&e.a<1&&(i.opacity=p(e.a)),i}function R(e){return!e||e.visible===!1?null:e.type==="SOLID"?{type:"SOLID",..._(e.color),...e.opacity!=null?{opacity:e.opacity}:{}}:{type:e.type,...e.opacity!=null?{opacity:e.opacity}:{},...e.gradientStops?{stops:e.gradientStops.map(n=>({position:p(n.position),..._(n.color)}))}:{}}}function v(e,n){let i=e.absoluteBoundingBox,r={id:e.id,name:e.name,type:e.type};i&&(r.size={w:p(i.width),h:p(i.height)},r.position={x:p(i.x),y:p(i.y)}),e.opacity!=null&&e.opacity!==1&&(r.opacity=e.opacity),e.cornerRadius!=null&&(r.cornerRadius=e.cornerRadius),Array.isArray(e.rectangleCornerRadii)&&(r.cornerRadii=e.rectangleCornerRadii);let s=(e.fills||[]).map(R).filter(Boolean);s.length&&(r.fills=s);let o=(e.strokes||[]).map(R).filter(Boolean);o.length&&(r.strokes=o,e.strokeWeight!=null&&(r.strokeWeight=e.strokeWeight));let a=(e.effects||[]).filter(t=>t.visible!==!1).map(t=>({type:t.type,...t.radius!=null?{radius:t.radius}:{},...t.offset?{offset:{x:p(t.offset.x),y:p(t.offset.y)}}:{},...t.spread?{spread:t.spread}:{},...t.color?_(t.color):{}}));if(a.length&&(r.effects=a),e.layoutMode&&e.layoutMode!=="NONE"&&(r.autoLayout={direction:e.layoutMode,padding:{l:e.paddingLeft??0,r:e.paddingRight??0,t:e.paddingTop??0,b:e.paddingBottom??0},gap:e.itemSpacing??0,align:{primary:e.primaryAxisAlignItems,counter:e.counterAxisAlignItems}}),e.type==="TEXT"){let t=e.style||{};r.text=e.characters,r.textStyle={fontFamily:t.fontFamily,fontWeight:t.fontWeight,fontSize:t.fontSize,lineHeightPx:t.lineHeightPx!=null?p(t.lineHeightPx):void 0,letterSpacing:t.letterSpacing!=null?p(t.letterSpacing):void 0,align:t.textAlignHorizontal,case:t.textCase}}return n>0&&Array.isArray(e.children)&&e.children.length&&(r.children=e.children.map(t=>v(t,n-1))),r}var F={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:h.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma
1
+ import{existsSync as b}from"fs";import{fileURLToPath as S}from"url";import{dirname as N,resolve as O}from"path";import{resolveIntegrationToken as k}from"@zibby/core/backend-client.js";var h=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),A=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 I(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let e=N(S(import.meta.url)),n=O(e,"..","bin","mcp-skill.mjs");return b(n)?n:null}async function f(e,n={}){let{token:i}=await k("figma"),r=e.startsWith("https://")?e:`https://api.figma.com${e}`,s={"X-Figma-Token":i,Accept:"application/json",...n.body?{"Content-Type":"application/json"}:{}},o=await fetch(r,{method:n.method||"GET",headers:s,body:n.body?JSON.stringify(n.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(`Figma API ${o.status}: ${a.slice(0,300)}`)}return o.json()}function g(e){let n=String(e||"").trim(),i=n.match(/figma\.com\/(?:file|design|board|proto)\/([A-Za-z0-9]+)/i);return i?i[1]:n}function u(e){return e==null?void 0:(Array.isArray(e)?e:String(e).split(",")).map(i=>String(i).trim().replace(/-/g,":")).filter(Boolean).join(",")}function L(e){let n=String(e||"").match(/[?&]node-id=([^&]+)/i);return n?decodeURIComponent(n[1]).replace(/-/g,":"):void 0}var p=e=>typeof e=="number"?Math.round(e*100)/100:e;function _(e){if(!e)return null;let n=r=>Math.round((r??0)*255).toString(16).padStart(2,"0"),i={hex:`#${n(e.r)}${n(e.g)}${n(e.b)}`.toUpperCase()};return e.a!=null&&e.a<1&&(i.opacity=p(e.a)),i}function R(e){return!e||e.visible===!1?null:e.type==="SOLID"?{type:"SOLID",..._(e.color),...e.opacity!=null?{opacity:e.opacity}:{}}:{type:e.type,...e.opacity!=null?{opacity:e.opacity}:{},...e.gradientStops?{stops:e.gradientStops.map(n=>({position:p(n.position),..._(n.color)}))}:{}}}function v(e,n){let i=e.absoluteBoundingBox,r={id:e.id,name:e.name,type:e.type};i&&(r.size={w:p(i.width),h:p(i.height)},r.position={x:p(i.x),y:p(i.y)}),e.opacity!=null&&e.opacity!==1&&(r.opacity=e.opacity),e.cornerRadius!=null&&(r.cornerRadius=e.cornerRadius),Array.isArray(e.rectangleCornerRadii)&&(r.cornerRadii=e.rectangleCornerRadii);let s=(e.fills||[]).map(R).filter(Boolean);s.length&&(r.fills=s);let o=(e.strokes||[]).map(R).filter(Boolean);o.length&&(r.strokes=o,e.strokeWeight!=null&&(r.strokeWeight=e.strokeWeight));let a=(e.effects||[]).filter(t=>t.visible!==!1).map(t=>({type:t.type,...t.radius!=null?{radius:t.radius}:{},...t.offset?{offset:{x:p(t.offset.x),y:p(t.offset.y)}}:{},...t.spread?{spread:t.spread}:{},...t.color?_(t.color):{}}));if(a.length&&(r.effects=a),e.layoutMode&&e.layoutMode!=="NONE"&&(r.autoLayout={direction:e.layoutMode,padding:{l:e.paddingLeft??0,r:e.paddingRight??0,t:e.paddingTop??0,b:e.paddingBottom??0},gap:e.itemSpacing??0,align:{primary:e.primaryAxisAlignItems,counter:e.counterAxisAlignItems}}),e.type==="TEXT"){let t=e.style||{};r.text=e.characters,r.textStyle={fontFamily:t.fontFamily,fontWeight:t.fontWeight,fontSize:t.fontSize,lineHeightPx:t.lineHeightPx!=null?p(t.lineHeightPx):void 0,letterSpacing:t.letterSpacing!=null?p(t.letterSpacing):void 0,align:t.textAlignHorizontal,case:t.textCase}}return n>0&&Array.isArray(e.children)&&e.children.length&&(r.children=e.children.map(t=>v(t,n-1))),r}var F={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:h.FIGMA,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"Figma \u2014 read files, nodes and comments; extract dev-handoff specs (sizes/colors/fonts/auto-layout); list versions and image fills; render frames to PNG/JPG/SVG/PDF; browse team projects/files; and post comments",promptFragment:`## Figma
2
2
  You have access to the user's Figma files via the Figma REST API. Every tool that takes a file accepts EITHER the raw file key OR a full figma.com URL (figma.com/file|design/<key>/...). Node ids accept URL form \`1-23\` or API form \`1:23\` interchangeably. Tools:
3
3
 
4
4
  ### Identity
@@ -29,4 +29,4 @@ You have access to the user's Figma files via the Figma REST API. Every tool tha
29
29
 
30
30
  ### Notes
31
31
  - The file key is NOT the file name \u2014 it's the opaque id segment in the URL (or just paste the URL).
32
- - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes / figma_parse_url output.`,resolve(){let e=L();if(!e)return{command:null,args:[],env:{},description:this.description};let n={};for(let i of this.envKeys)process.env[i]&&(n[i]=process.env[i]);return{type:"stdio",command:"node",args:[e,"../dist/figma.js","figmaSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(e,n){try{switch(e){case"figma_get_me":{let i=await f("/v1/me");return JSON.stringify({id:i.id,handle:i.handle,email:i.email,imgUrl:i.img_url})}case"figma_get_file":{let i=g((n||{}).fileKey),{depth:r}=n||{};if(!i)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=`/v1/files/${encodeURIComponent(i)}`;if(r!=null){let t=Number(r);!Number.isNaN(t)&&t>0&&(s+=`?depth=${t}`)}let o=await f(s),a=(o.document?.children||[]).map(t=>({id:t.id,name:t.name,type:t.type,childCount:Array.isArray(t.children)?t.children.length:0,children:(t.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:o.name,lastModified:o.lastModified,version:o.version,editorType:o.editorType,role:o.role,pages:a})}case"figma_get_nodes":{let i=g((n||{}).fileKey),{ids:r,depth:s}=n||{};if(!i)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let o=u(r);if(!o)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let a=new URLSearchParams;if(a.set("ids",o),s!=null){let d=Number(s);!Number.isNaN(d)&&d>0&&a.set("depth",String(d))}let t=await f(`/v1/files/${encodeURIComponent(i)}/nodes?${a.toString()}`),c={};for(let[d,m]of Object.entries(t.nodes||{}))c[d]=m?.document?{id:m.document.id,name:m.document.name,type:m.document.type,document:m.document}:m;return JSON.stringify({name:t.name,nodes:c})}case"figma_get_node_specs":{let i=g((n||{}).file),{ids:r,depth:s}=n||{};if(!i)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let o=u(r);if(!o)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let a=Number(s);Number.isNaN(a)&&(a=2),a=Math.min(6,Math.max(0,Math.trunc(a)));let t=new URLSearchParams;t.set("ids",o),t.set("depth",String(a));let c=await f(`/v1/files/${encodeURIComponent(i)}/nodes?${t.toString()}`),d={};for(let[m,l]of Object.entries(c.nodes||{}))d[m]=l&&l.document?v(l.document,a):null;return JSON.stringify(d)}case"figma_render_png":{let i=g((n||{}).fileKey??(n||{}).file),{ids:r,scale:s,format:o,svg_include_id:a,version:t}=n||{};if(!i)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let c=u(r);if(!c)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let d=["png","jpg","svg","pdf"].includes(String(o||"").toLowerCase())?String(o).toLowerCase():"png",m=new URLSearchParams;m.set("ids",c),m.set("format",d);let l;(d==="png"||d==="jpg")&&(l=Number(s),(Number.isNaN(l)||l<=0)&&(l=1),l=Math.min(4,Math.max(.01,l)),m.set("scale",String(l))),d==="svg"&&a!=null&&m.set("svg_include_id",String(!!a)),t&&m.set("version",String(t));let y=await f(`/v1/images/${encodeURIComponent(i)}?${m.toString()}`);return y.err?JSON.stringify({error:`Figma render error: ${y.err}`}):JSON.stringify({format:d,...l!=null?{scale:l}:{},images:y.images||{}})}case"figma_get_image_fills":{let i=g((n||{}).file);if(!i)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let r=await f(`/v1/files/${encodeURIComponent(i)}/images`);return JSON.stringify({images:r.meta?.images??r.images??{}})}case"figma_get_file_versions":{let i=g((n||{}).file);if(!i)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let s=((await f(`/v1/files/${encodeURIComponent(i)}/versions`)).versions||[]).map(o=>({id:o.id,label:o.label,description:o.description,createdAt:o.created_at,user:o.user?.handle}));return JSON.stringify({count:s.length,versions:s})}case"figma_get_comments":{let i=g((n||{}).fileKey);if(!i)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=((await f(`/v1/files/${encodeURIComponent(i)}/comments`)).comments||[]).map(o=>({id:o.id,message:o.message,user:o.user?.handle,createdAt:o.created_at,resolvedAt:o.resolved_at||null,parentId:o.parent_id||null}));return JSON.stringify({count:s.length,comments:s})}case"figma_post_comment":{let i=g((n||{}).file),{message:r,comment_id:s,node_id:o,x:a,y:t}=n||{};if(!i)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});if(!r)return JSON.stringify({error:"message is required"});let c={message:r};s&&(c.comment_id=s),o?c.client_meta={node_id:u(o),node_offset:{x:a??0,y:t??0}}:(a!=null||t!=null)&&(c.client_meta={x:a??0,y:t??0});let d=await f(`/v1/files/${encodeURIComponent(i)}/comments`,{method:"POST",body:c});return JSON.stringify({id:d.id,message:d.message,fileKey:i,createdAt:d.created_at,parentId:d.parent_id||null})}case"figma_get_team_projects":{let{team_id:i}=n||{};if(!i)return JSON.stringify({error:"team_id is required"});let r=await f(`/v1/teams/${encodeURIComponent(i)}/projects`);return JSON.stringify({name:r.name,projects:r.projects||[]})}case"figma_get_project_files":{let{project_id:i,branch_data:r}=n||{};if(!i)return JSON.stringify({error:"project_id is required"});let s=new URLSearchParams;r&&s.set("branch_data","true");let o=s.toString(),a=await f(`/v1/projects/${encodeURIComponent(i)}/files${o?`?${o}`:""}`);return JSON.stringify({name:a.name,files:a.files||[]})}case"figma_parse_url":{let{url:i}=n||{};return JSON.stringify({file_key:g(i),node_id:I(i)??null})}default:return JSON.stringify({error:`Unknown tool: ${e}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree. Accepts a file key OR a figma.com URL (figma.com/file|design/<key>/... \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes or figma_get_node_specs to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'A file key OR a figma.com URL (e.g. "aBcD1234" or figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch. Accepts URL form ["1-23"] or API form ["1:23"]. A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_get_node_specs",description:"Dev-Mode-style inspection computed from the REST tree: for the given nodes and their children returns size, position, colors (hex), fonts/text-style, spacing/auto-layout, corner radius, strokes and effects \u2014 a compact spec for reproducing a design in code. Prefer this over figma_get_nodes when your job is to build UI from a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to inspect (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},depth:{type:"number",description:"How many levels of children to walk (0-6, default 2)."}},required:["file","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to an image and return the URLs (a map of nodeId \u2192 URL). Despite the name it renders PNG/JPG/SVG/PDF (default png). Use to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},format:{type:"string",enum:["png","jpg","svg","pdf"],description:"Output format (default png)."},scale:{type:"number",description:"Render scale, 0.01\u20134 (raster formats only; default 1). 2 for retina/hi-dpi."},svg_include_id:{type:"boolean",description:"For SVG: include element ids as attributes."},version:{type:"string",description:"Render a specific file version id (from figma_get_file_versions)."}},required:["fileKey","ids"]}},{name:"figma_get_image_fills",description:"Get a map of imageRef \u2192 download URL for every image fill used in a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_file_versions",description:"List a Figma file's saved version history (version id, label, created_at, user). A version id can be passed to figma_render_png to render a past version.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"}},required:["fileKey"]}},{name:"figma_post_comment",description:"Post a comment on a Figma file (WRITE \u2014 needs a PAT with comment-write scope). Optionally reply to a comment (comment_id), pin it to a node (node_id, with optional x/y offset), or pin to a canvas point (x/y).",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},message:{type:"string",description:"The comment text."},comment_id:{type:"string",description:"Optional: reply to this parent comment id."},node_id:{type:"string",description:'Optional: pin the comment to this node ("1-23" or "1:23").'},x:{type:"number",description:"Optional: x position (node offset if node_id given, else canvas point)."},y:{type:"number",description:"Optional: y position (node offset if node_id given, else canvas point)."}},required:["file","message"]}},{name:"figma_get_team_projects",description:"List the projects in a Figma team. Get team_id from a Figma team URL (\u2026/files/team/<TEAM_ID>/\u2026).",input_schema:{type:"object",properties:{team_id:{type:"string",description:"The Figma team id."}},required:["team_id"]}},{name:"figma_get_project_files",description:"List the files in a Figma project (from figma_get_team_projects). Returns file key, name, thumbnail, last_modified.",input_schema:{type:"object",properties:{project_id:{type:"string",description:"The Figma project id."},branch_data:{type:"boolean",description:"Optional: include branch metadata for each file."}},required:["project_id"]}},{name:"figma_parse_url",description:"Local helper (no API call): extract the file key and node id (colon form) from a figma.com file/design URL. Returns { file_key, node_id }.",input_schema:{type:"object",properties:{url:{type:"string",description:"A full figma.com file/design URL."}},required:["url"]}}]};export{F as figmaSkill,g as fileKeyFrom,I as nodeIdFromUrl,v as nodeSpec,u as normalizeNodeIds};
32
+ - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes / figma_parse_url output.`,resolve(){let e=I();if(!e)return{command:null,args:[],env:{},description:this.description};let n={};for(let i of this.envKeys)process.env[i]&&(n[i]=process.env[i]);return{type:"stdio",command:"node",args:[e,"../dist/figma.js","figmaSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(e,n){try{switch(e){case"figma_get_me":{let i=await f("/v1/me");return JSON.stringify({id:i.id,handle:i.handle,email:i.email,imgUrl:i.img_url})}case"figma_get_file":{let i=g((n||{}).fileKey),{depth:r}=n||{};if(!i)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=`/v1/files/${encodeURIComponent(i)}`;if(r!=null){let t=Number(r);!Number.isNaN(t)&&t>0&&(s+=`?depth=${t}`)}let o=await f(s),a=(o.document?.children||[]).map(t=>({id:t.id,name:t.name,type:t.type,childCount:Array.isArray(t.children)?t.children.length:0,children:(t.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:o.name,lastModified:o.lastModified,version:o.version,editorType:o.editorType,role:o.role,pages:a})}case"figma_get_nodes":{let i=g((n||{}).fileKey),{ids:r,depth:s}=n||{};if(!i)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let o=u(r);if(!o)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let a=new URLSearchParams;if(a.set("ids",o),s!=null){let d=Number(s);!Number.isNaN(d)&&d>0&&a.set("depth",String(d))}let t=await f(`/v1/files/${encodeURIComponent(i)}/nodes?${a.toString()}`),c={};for(let[d,m]of Object.entries(t.nodes||{}))c[d]=m?.document?{id:m.document.id,name:m.document.name,type:m.document.type,document:m.document}:m;return JSON.stringify({name:t.name,nodes:c})}case"figma_get_node_specs":{let i=g((n||{}).file),{ids:r,depth:s}=n||{};if(!i)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let o=u(r);if(!o)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let a=Number(s);Number.isNaN(a)&&(a=2),a=Math.min(6,Math.max(0,Math.trunc(a)));let t=new URLSearchParams;t.set("ids",o),t.set("depth",String(a));let c=await f(`/v1/files/${encodeURIComponent(i)}/nodes?${t.toString()}`),d={};for(let[m,l]of Object.entries(c.nodes||{}))d[m]=l&&l.document?v(l.document,a):null;return JSON.stringify(d)}case"figma_render_png":{let i=g((n||{}).fileKey??(n||{}).file),{ids:r,scale:s,format:o,svg_include_id:a,version:t}=n||{};if(!i)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let c=u(r);if(!c)return JSON.stringify({error:"ids is required (comma-separated or array of node ids; `1-23` or `1:23`)"});let d=["png","jpg","svg","pdf"].includes(String(o||"").toLowerCase())?String(o).toLowerCase():"png",m=new URLSearchParams;m.set("ids",c),m.set("format",d);let l;(d==="png"||d==="jpg")&&(l=Number(s),(Number.isNaN(l)||l<=0)&&(l=1),l=Math.min(4,Math.max(.01,l)),m.set("scale",String(l))),d==="svg"&&a!=null&&m.set("svg_include_id",String(!!a)),t&&m.set("version",String(t));let y=await f(`/v1/images/${encodeURIComponent(i)}?${m.toString()}`);return y.err?JSON.stringify({error:`Figma render error: ${y.err}`}):JSON.stringify({format:d,...l!=null?{scale:l}:{},images:y.images||{}})}case"figma_get_image_fills":{let i=g((n||{}).file);if(!i)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let r=await f(`/v1/files/${encodeURIComponent(i)}/images`);return JSON.stringify({images:r.meta?.images??r.images??{}})}case"figma_get_file_versions":{let i=g((n||{}).file);if(!i)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});let s=((await f(`/v1/files/${encodeURIComponent(i)}/versions`)).versions||[]).map(o=>({id:o.id,label:o.label,description:o.description,createdAt:o.created_at,user:o.user?.handle}));return JSON.stringify({count:s.length,versions:s})}case"figma_get_comments":{let i=g((n||{}).fileKey);if(!i)return JSON.stringify({error:"fileKey is required (a file key or a figma.com URL)"});let s=((await f(`/v1/files/${encodeURIComponent(i)}/comments`)).comments||[]).map(o=>({id:o.id,message:o.message,user:o.user?.handle,createdAt:o.created_at,resolvedAt:o.resolved_at||null,parentId:o.parent_id||null}));return JSON.stringify({count:s.length,comments:s})}case"figma_post_comment":{let i=g((n||{}).file),{message:r,comment_id:s,node_id:o,x:a,y:t}=n||{};if(!i)return JSON.stringify({error:"file is required (a file key or a figma.com URL)"});if(!r)return JSON.stringify({error:"message is required"});let c={message:r};s&&(c.comment_id=s),o?c.client_meta={node_id:u(o),node_offset:{x:a??0,y:t??0}}:(a!=null||t!=null)&&(c.client_meta={x:a??0,y:t??0});let d=await f(`/v1/files/${encodeURIComponent(i)}/comments`,{method:"POST",body:c});return JSON.stringify({id:d.id,message:d.message,fileKey:i,createdAt:d.created_at,parentId:d.parent_id||null})}case"figma_get_team_projects":{let{team_id:i}=n||{};if(!i)return JSON.stringify({error:"team_id is required"});let r=await f(`/v1/teams/${encodeURIComponent(i)}/projects`);return JSON.stringify({name:r.name,projects:r.projects||[]})}case"figma_get_project_files":{let{project_id:i,branch_data:r}=n||{};if(!i)return JSON.stringify({error:"project_id is required"});let s=new URLSearchParams;r&&s.set("branch_data","true");let o=s.toString(),a=await f(`/v1/projects/${encodeURIComponent(i)}/files${o?`?${o}`:""}`);return JSON.stringify({name:a.name,files:a.files||[]})}case"figma_parse_url":{let{url:i}=n||{};return JSON.stringify({file_key:g(i),node_id:L(i)??null})}default:return JSON.stringify({error:`Unknown tool: ${e}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree. Accepts a file key OR a figma.com URL (figma.com/file|design/<key>/... \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes or figma_get_node_specs to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'A file key OR a figma.com URL (e.g. "aBcD1234" or figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch. Accepts URL form ["1-23"] or API form ["1:23"]. A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_get_node_specs",description:"Dev-Mode-style inspection computed from the REST tree: for the given nodes and their children returns size, position, colors (hex), fonts/text-style, spacing/auto-layout, corner radius, strokes and effects \u2014 a compact spec for reproducing a design in code. Prefer this over figma_get_nodes when your job is to build UI from a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to inspect (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},depth:{type:"number",description:"How many levels of children to walk (0-6, default 2)."}},required:["file","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to an image and return the URLs (a map of nodeId \u2192 URL). Despite the name it renders PNG/JPG/SVG/PDF (default png). Use to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (URL form "1-23" or API form "1:23"). A comma-separated string is also accepted.'},format:{type:"string",enum:["png","jpg","svg","pdf"],description:"Output format (default png)."},scale:{type:"number",description:"Render scale, 0.01\u20134 (raster formats only; default 1). 2 for retina/hi-dpi."},svg_include_id:{type:"boolean",description:"For SVG: include element ids as attributes."},version:{type:"string",description:"Render a specific file version id (from figma_get_file_versions)."}},required:["fileKey","ids"]}},{name:"figma_get_image_fills",description:"Get a map of imageRef \u2192 download URL for every image fill used in a Figma file.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_file_versions",description:"List a Figma file's saved version history (version id, label, created_at, user). A version id can be passed to figma_render_png to render a past version.",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"}},required:["file"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"A file key OR a figma.com URL"}},required:["fileKey"]}},{name:"figma_post_comment",description:"Post a comment on a Figma file (WRITE \u2014 needs a PAT with comment-write scope). Optionally reply to a comment (comment_id), pin it to a node (node_id, with optional x/y offset), or pin to a canvas point (x/y).",input_schema:{type:"object",properties:{file:{type:"string",description:"A file key OR a figma.com URL"},message:{type:"string",description:"The comment text."},comment_id:{type:"string",description:"Optional: reply to this parent comment id."},node_id:{type:"string",description:'Optional: pin the comment to this node ("1-23" or "1:23").'},x:{type:"number",description:"Optional: x position (node offset if node_id given, else canvas point)."},y:{type:"number",description:"Optional: y position (node offset if node_id given, else canvas point)."}},required:["file","message"]}},{name:"figma_get_team_projects",description:"List the projects in a Figma team. Get team_id from a Figma team URL (\u2026/files/team/<TEAM_ID>/\u2026).",input_schema:{type:"object",properties:{team_id:{type:"string",description:"The Figma team id."}},required:["team_id"]}},{name:"figma_get_project_files",description:"List the files in a Figma project (from figma_get_team_projects). Returns file key, name, thumbnail, last_modified.",input_schema:{type:"object",properties:{project_id:{type:"string",description:"The Figma project id."},branch_data:{type:"boolean",description:"Optional: include branch metadata for each file."}},required:["project_id"]}},{name:"figma_parse_url",description:"Local helper (no API call): extract the file key and node id (colon form) from a figma.com file/design URL. Returns { file_key, node_id }.",input_schema:{type:"object",properties:{url:{type:"string",description:"A full figma.com file/design URL."}},required:["url"]}}]};export{F as figmaSkill,g as fileKeyFrom,L as nodeIdFromUrl,v as nodeSpec,u as normalizeNodeIds};
@@ -1,7 +1,7 @@
1
- import{existsSync as E,statSync as P,readFileSync as R}from"fs";import{fileURLToPath as D}from"url";import{basename as L,dirname as G,resolve as B}from"path";import{resolveIntegrationToken as $,clearTokenCache as C}from"@zibby/core/backend-client.js";var T=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=G(D(import.meta.url)),e=B(n,"..","bin","mcp-skill.mjs");return E(e)?e:null}var h="https://docs.googleapis.com/v1",x="https://www.googleapis.com/drive/v3",U="https://www.googleapis.com/upload/drive/v3",M=5*1024*1024;function q(){let n=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!n)return null;let e=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:n,email:e}}function J(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function F(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Y="You haven't connected your own Google account \u2014 connect it at https://studio.zibby.dev/integrations (Google Docs). For privacy, I can't use anyone else's Google (including the project owner's) on your behalf.",S=2e4,H=25;function k(n){if(!n||typeof n!="string")return null;let e=n.trim(),t=e.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return t?t[1]:/^[a-zA-Z0-9_-]{20,}$/.test(e)?e:null}async function K(){let n,e=q();if(e)n=e.token;else{if(F()||J())throw new Error(Y);({token:n}=await $("google"))}if(typeof n!="string"||!n)throw new Error(`Invalid google token type: ${typeof n}`);return n}async function p(n,e={}){let t=async()=>{let i=await K(),o=await fetch(n,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(`Google API ${o.status}: ${a.slice(0,300)}`)}let r=await o.text().catch(()=>"");if(!r||!r.trim())return{};try{return JSON.parse(r)}catch{return{raw:r}}};try{return await t()}catch(i){let o=String(i?.message||i||"").toLowerCase();if(!(o.includes("token")||o.includes("401")||o.includes("unauthorized")))throw i;return C("google"),t()}}function z(n){let e=[],t="",i=0;for(;i<n.length;){let o=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(n.slice(i));if(o){e.push({start:t.length,end:t.length+o[1].length,link:o[2]}),t+=o[1],i+=o[0].length;continue}let r=/^\*\*([^*]+)\*\*/.exec(n.slice(i));if(r){e.push({start:t.length,end:t.length+r[1].length,bold:!0}),t+=r[1],i+=r[0].length;continue}let a=/^`([^`]+)`/.exec(n.slice(i));if(a){e.push({start:t.length,end:t.length+a[1].length,code:!0}),t+=a[1],i+=a[0].length;continue}t+=n[i],i+=1}return{text:t,styles:e}}function N(n,e){let t=String(n??"").replace(/\r\n/g,`
1
+ import{existsSync as E,statSync as v,readFileSync as R}from"fs";import{fileURLToPath as D}from"url";import{basename as L,dirname as G,resolve as B}from"path";import{resolveIntegrationToken as C,clearTokenCache as $}from"@zibby/core/backend-client.js";var T=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 U(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=G(D(import.meta.url)),e=B(n,"..","bin","mcp-skill.mjs");return E(e)?e:null}var h="https://docs.googleapis.com/v1",N="https://www.googleapis.com/drive/v3",j="https://www.googleapis.com/upload/drive/v3",M=5*1024*1024;function J(){let n=String(process.env.ZIBBY_INJECTED_GOOGLE_TOKEN||"").trim();if(!n)return null;let e=String(process.env.ZIBBY_INJECTED_GOOGLE_EMAIL||"").trim();return{token:n,email:e}}function q(){return String(process.env.ZIBBY_SENDER_IS_NON_OWNER||"").trim()==="1"}function F(){return String(process.env.ZIBBY_CHAT_STRICT_PERSONAL||"").trim()==="1"}var Y="You haven't connected your own Google account \u2014 connect it at https://studio.zibby.dev/integrations (Google Docs). For privacy, I can't use anyone else's Google (including the project owner's) on your behalf.",S=2e4,H=25;function k(n){if(!n||typeof n!="string")return null;let e=n.trim(),t=e.match(/\/document\/(?:u\/\d+\/)?d\/([a-zA-Z0-9_-]+)/);return t?t[1]:/^[a-zA-Z0-9_-]{20,}$/.test(e)?e:null}async function K(){let n,e=J();if(e)n=e.token;else{if(F()||q())throw new Error(Y);({token:n}=await C("google"))}if(typeof n!="string"||!n)throw new Error(`Invalid google token type: ${typeof n}`);return n}async function p(n,e={}){let t=async()=>{let i=await K(),o=await fetch(n,{method:e.method||"GET",headers:{Authorization:`Bearer ${i}`,Accept:"application/json",...e.rawBody&&e.contentType?{"Content-Type":e.contentType}:e.body?{"Content-Type":"application/json"}:{},...e.headers},body:e.rawBody?e.rawBody:e.body?JSON.stringify(e.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(`Google API ${o.status}: ${a.slice(0,300)}`)}let r=await o.text().catch(()=>"");if(!r||!r.trim())return{};try{return JSON.parse(r)}catch{return{raw:r}}};try{return await t()}catch(i){let o=String(i?.message||i||"").toLowerCase();if(!(o.includes("token")||o.includes("401")||o.includes("unauthorized")))throw i;return $("google"),t()}}function Z(n){let e=[],t="",i=0;for(;i<n.length;){let o=/^\[([^\]]+)\]\(([^)\s]+)\)/.exec(n.slice(i));if(o){e.push({start:t.length,end:t.length+o[1].length,link:o[2]}),t+=o[1],i+=o[0].length;continue}let r=/^\*\*([^*]+)\*\*/.exec(n.slice(i));if(r){e.push({start:t.length,end:t.length+r[1].length,bold:!0}),t+=r[1],i+=r[0].length;continue}let a=/^`([^`]+)`/.exec(n.slice(i));if(a){e.push({start:t.length,end:t.length+a[1].length,code:!0}),t+=a[1],i+=a[0].length;continue}t+=n[i],i+=1}return{text:t,styles:e}}function x(n,e){let t=String(n??"").replace(/\r\n/g,`
2
2
  `);if(!t.trim())return{requests:[],endIndex:e};let i=t.split(`
3
- `),o="",r=[],a=[];for(let s of i){let c=s,I=null,b=null,f=/^(#{1,3})\s+(.*)$/.exec(c),g=/^\s*[-*]\s+(.*)$/.exec(c),m=/^\s*\d+[.)]\s+(.*)$/.exec(c);f?(I=`HEADING_${f[1].length}`,c=f[2]):g?(b="BULLET_DISC_CIRCLE_SQUARE",c=g[1]):m&&(b="NUMBERED_DECIMAL_ALPHA_ROMAN",c=m[1]);let{text:v,styles:A}=z(c),_=e+o.length;for(let w of A)a.push({...w,start:_+w.start,end:_+w.end});o+=`${v}
4
- `,r.push({start:_,end:e+o.length,named:I,bullet:b})}if(!o)return{requests:[],endIndex:e};let u=[{insertText:{location:{index:e},text:o}}];for(let s of r)s.named&&u.push({updateParagraphStyle:{range:{startIndex:s.start,endIndex:s.end},paragraphStyle:{namedStyleType:s.named},fields:"namedStyleType"}});let d=null,l=()=>{d&&(u.push({createParagraphBullets:{range:{startIndex:d.start,endIndex:d.end},bulletPreset:d.preset}}),d=null)};for(let s of r)s.bullet?d&&d.preset===s.bullet?d.end=s.end:(l(),d={start:s.start,end:s.end,preset:s.bullet}):l();l();for(let s of a)s.end<=s.start||(s.bold?u.push({updateTextStyle:{range:{startIndex:s.start,endIndex:s.end},textStyle:{bold:!0},fields:"bold"}}):s.link?u.push({updateTextStyle:{range:{startIndex:s.start,endIndex:s.end},textStyle:{link:{url:s.link}},fields:"link"}}):s.code&&u.push({updateTextStyle:{range:{startIndex:s.start,endIndex:s.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:u,endIndex:e+o.length}}function Z(n){let e="",t=i=>{for(let o of Array.isArray(i)?i:[]){if(e.length>=S)return;if(o.paragraph)for(let r of o.paragraph.elements||[])e+=r?.textRun?.content||"";else if(o.table)for(let r of o.table.tableRows||[])for(let a of r.tableCells||[])t(a.content);else o.tableOfContents&&t(o.tableOfContents.content)}};return t(n?.content),e.slice(0,S)}var y=n=>`https://docs.google.com/document/d/${n}/edit`;function V(n){let e=typeof n=="string"?n.trim():"";if(!e)throw new Error("imagePath is required");if(!E(e)||!P(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>M)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:L(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function W(n,e,t){let i=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${i}\r
3
+ `),o="",r=[],a=[];for(let s of i){let c=s,I=null,_=null,f=/^(#{1,3})\s+(.*)$/.exec(c),g=/^\s*[-*]\s+(.*)$/.exec(c),m=/^\s*\d+[.)]\s+(.*)$/.exec(c);f?(I=`HEADING_${f[1].length}`,c=f[2]):g?(_="BULLET_DISC_CIRCLE_SQUARE",c=g[1]):m&&(_="NUMBERED_DECIMAL_ALPHA_ROMAN",c=m[1]);let{text:A,styles:P}=Z(c),b=e+o.length;for(let w of P)a.push({...w,start:b+w.start,end:b+w.end});o+=`${A}
4
+ `,r.push({start:b,end:e+o.length,named:I,bullet:_})}if(!o)return{requests:[],endIndex:e};let u=[{insertText:{location:{index:e},text:o}}];for(let s of r)s.named&&u.push({updateParagraphStyle:{range:{startIndex:s.start,endIndex:s.end},paragraphStyle:{namedStyleType:s.named},fields:"namedStyleType"}});let d=null,l=()=>{d&&(u.push({createParagraphBullets:{range:{startIndex:d.start,endIndex:d.end},bulletPreset:d.preset}}),d=null)};for(let s of r)s.bullet?d&&d.preset===s.bullet?d.end=s.end:(l(),d={start:s.start,end:s.end,preset:s.bullet}):l();l();for(let s of a)s.end<=s.start||(s.bold?u.push({updateTextStyle:{range:{startIndex:s.start,endIndex:s.end},textStyle:{bold:!0},fields:"bold"}}):s.link?u.push({updateTextStyle:{range:{startIndex:s.start,endIndex:s.end},textStyle:{link:{url:s.link}},fields:"link"}}):s.code&&u.push({updateTextStyle:{range:{startIndex:s.start,endIndex:s.end},textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}}));return{requests:u,endIndex:e+o.length}}function z(n){let e="",t=i=>{for(let o of Array.isArray(i)?i:[]){if(e.length>=S)return;if(o.paragraph)for(let r of o.paragraph.elements||[])e+=r?.textRun?.content||"";else if(o.table)for(let r of o.table.tableRows||[])for(let a of r.tableCells||[])t(a.content);else o.tableOfContents&&t(o.tableOfContents.content)}};return t(n?.content),e.slice(0,S)}var y=n=>`https://docs.google.com/document/d/${n}/edit`;function V(n){let e=typeof n=="string"?n.trim():"";if(!e)throw new Error("imagePath is required");if(!E(e)||!v(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>M)throw new Error(`image is ${(t.length/(1024*1024)).toFixed(1)}MB \u2014 max 5MB (Drive multipart upload cap)`);return{bytes:t,fileName:L(e),mimeType:/\.png$/i.test(e)?"image/png":"image/jpeg"}}function W(n,e,t){let i=`zibby-gdocs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return{rawBody:Buffer.concat([Buffer.from(`--${i}\r
5
5
  Content-Type: application/json; charset=UTF-8\r
6
6
  \r
7
7
  ${JSON.stringify(n)}\r
@@ -18,5 +18,5 @@ Docs access is PER-USER: each teammate connects their OWN Google account (Integr
18
18
  - gdocs_insert_image: append a LOCAL image file (png/jpg, \u22645MB) to the end of a doc \u2014 pass { documentId, imagePath, width?, height? } (width/height in PT, optional). The image is uploaded to the user's Drive and made link-readable (anyone with the link) so Docs can render it. Returns { ok, documentId, fileId, url }.
19
19
  - gdocs_get: read a doc back as plain text (works for app-created/user-picked docs only; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker \u2014 drive.file has no access to un-picked files).
20
20
  - gdocs_list_created: list the Google Docs visible to this app (drive.file \u2192 only docs it created or the user picked).
21
- These tools return { ok:false, error } on failure \u2014 treat an unavailable Google connection as "cannot deliver to Docs" and report it rather than blocking the task.`,resolve(){let n=j();if(!n)return null;let e={};for(let t of["ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[n,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"gdocs_create_doc":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let o=(await p(`${h}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!o)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let r=O(e);if(r&&r.trim()){let{requests:a}=N(r,1);a.length&&await p(`${h}/documents/${o}:batchUpdate`,{method:"POST",body:{requests:a}})}return JSON.stringify({ok:!0,documentId:o,title:t,url:y(o)})}case"gdocs_append":{let t=k(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let i=O(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let r=(await p(`${h}/documents/${t}`))?.body,a=Array.isArray(r?.content)?r.content:[],u=a.length&&a[a.length-1].endIndex||2,d=Math.max(1,u-1),l=[],s=d;d>1&&(l.push({insertText:{location:{index:d},text:`
22
- `}}),s=d+1);let c=N(i,s);return l.push(...c.requests),await p(`${h}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:l}}),JSON.stringify({ok:!0,documentId:t,url:y(t)})}case"gdocs_insert_image":{let t=k(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:i,fileName:o,mimeType:r}=V(e.imagePath),{rawBody:a,contentType:u}=W({name:o,mimeType:r},i,r),l=(await p(`${U}/files?uploadType=multipart&fields=id`,{method:"POST",rawBody:a,contentType:u}))?.id;if(!l)return JSON.stringify({ok:!1,error:"Drive upload returned no file id"});await p(`${x}/files/${l}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let s=await p(`${h}/documents/${t}`),c=Array.isArray(s?.body?.content)?s.body.content:[],I=c.length&&c[c.length-1].endIndex||2,f={location:{index:Math.max(1,I-1)},uri:`https://drive.google.com/uc?export=download&id=${l}`},g=Number(e?.width),m=Number(e?.height);return(Number.isFinite(g)&&g>0||Number.isFinite(m)&&m>0)&&(f.objectSize={...Number.isFinite(g)&&g>0?{width:{magnitude:g,unit:"PT"}}:{},...Number.isFinite(m)&&m>0?{height:{magnitude:m,unit:"PT"}}:{}}),await p(`${h}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:l,url:y(t)})}case"gdocs_get":{let t=k(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let i=await p(`${h}/documents/${t}`),o=Z(i?.body);return JSON.stringify({ok:!0,documentId:t,title:i?.title||"",url:y(t),text:o,...o.length>=S?{truncated:!0}:{}})}case"gdocs_list_created":{let t=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(H),orderBy:"modifiedTime desc"}),i=await p(`${x}/files?${t.toString()}`),o=(Array.isArray(i?.files)?i.files:[]).map(r=>({documentId:r.id,title:r.name,modifiedTime:r.modifiedTime,url:r.webViewLink||y(r.id)}));return JSON.stringify({ok:!0,count:o.length,files:o})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${n}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). The drive.file scope grants access ONLY to docs this app created or the user explicitly picked; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker (drive.file cannot see un-picked files). Returns { ok, documentId, title, url, text }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."}},required:["documentId"]}},{name:"gdocs_list_created",description:"List the Google Docs visible to this integration, newest first (max 25). NOTE: under the drive.file scope this lists ONLY docs the app created or the user explicitly picked \u2014 it is NOT a full Drive search. Returns { ok, count, files:[{ documentId, title, modifiedTime, url }] }.",input_schema:{type:"object",properties:{}}}]};export{Y as NON_OWNER_REFUSAL,F as chatStrictPersonal,Z as extractPlainText,p as googleApi,re as googleDocsSkill,q as injectedGoogleToken,N as markdownToRequests,k as parseDocId,z as parseInlineMarkdown,J as senderIsNonOwner};
21
+ These tools return { ok:false, error } on failure \u2014 treat an unavailable Google connection as "cannot deliver to Docs" and report it rather than blocking the task.`,resolve(){let n=U();if(!n)return null;let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_GOOGLE_EMAIL","ZIBBY_SENDER_IS_NON_OWNER","ZIBBY_CHAT_STRICT_PERSONAL"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[n,"../dist/googleDocs.js","googleDocsSkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(n,e){try{switch(n){case"gdocs_create_doc":{let t=typeof e?.title=="string"&&e.title.trim()?e.title.trim():null;if(!t)return JSON.stringify({ok:!1,error:"title is required"});let o=(await p(`${h}/documents`,{method:"POST",body:{title:t}}))?.documentId;if(!o)return JSON.stringify({ok:!1,error:"Google Docs create returned no documentId"});let r=O(e);if(r&&r.trim()){let{requests:a}=x(r,1);a.length&&await p(`${h}/documents/${o}:batchUpdate`,{method:"POST",body:{requests:a}})}return JSON.stringify({ok:!0,documentId:o,title:t,url:y(o)})}case"gdocs_append":{let t=k(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let i=O(e);if(!i||!i.trim())return JSON.stringify({ok:!1,error:"markdown or text content is required"});let r=(await p(`${h}/documents/${t}`))?.body,a=Array.isArray(r?.content)?r.content:[],u=a.length&&a[a.length-1].endIndex||2,d=Math.max(1,u-1),l=[],s=d;d>1&&(l.push({insertText:{location:{index:d},text:`
22
+ `}}),s=d+1);let c=x(i,s);return l.push(...c.requests),await p(`${h}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:l}}),JSON.stringify({ok:!0,documentId:t,url:y(t)})}case"gdocs_insert_image":{let t=k(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});if(!e?.imagePath||typeof e.imagePath!="string"||!e.imagePath.trim())return JSON.stringify({ok:!1,error:"imagePath is required"});let{bytes:i,fileName:o,mimeType:r}=V(e.imagePath),{rawBody:a,contentType:u}=W({name:o,mimeType:r},i,r),l=(await p(`${j}/files?uploadType=multipart&fields=id`,{method:"POST",rawBody:a,contentType:u}))?.id;if(!l)return JSON.stringify({ok:!1,error:"Drive upload returned no file id"});await p(`${N}/files/${l}/permissions`,{method:"POST",body:{role:"reader",type:"anyone"}});let s=await p(`${h}/documents/${t}`),c=Array.isArray(s?.body?.content)?s.body.content:[],I=c.length&&c[c.length-1].endIndex||2,f={location:{index:Math.max(1,I-1)},uri:`https://drive.google.com/uc?export=download&id=${l}`},g=Number(e?.width),m=Number(e?.height);return(Number.isFinite(g)&&g>0||Number.isFinite(m)&&m>0)&&(f.objectSize={...Number.isFinite(g)&&g>0?{width:{magnitude:g,unit:"PT"}}:{},...Number.isFinite(m)&&m>0?{height:{magnitude:m,unit:"PT"}}:{}}),await p(`${h}/documents/${t}:batchUpdate`,{method:"POST",body:{requests:[{insertInlineImage:f}]}}),JSON.stringify({ok:!0,documentId:t,fileId:l,url:y(t)})}case"gdocs_get":{let t=k(e?.documentId||e?.url||e?.id);if(!t)return JSON.stringify({ok:!1,error:"A valid Google Docs documentId or URL is required"});let i=await p(`${h}/documents/${t}`),o=z(i?.body);return JSON.stringify({ok:!0,documentId:t,title:i?.title||"",url:y(t),text:o,...o.length>=S?{truncated:!0}:{}})}case"gdocs_list_created":{let t=new URLSearchParams({q:"'me' in owners and mimeType='application/vnd.google-apps.document' and trashed=false",fields:"files(id,name,modifiedTime,webViewLink)",pageSize:String(H),orderBy:"modifiedTime desc"}),i=await p(`${N}/files?${t.toString()}`),o=(Array.isArray(i?.files)?i.files:[]).map(r=>({documentId:r.id,title:r.name,modifiedTime:r.modifiedTime,url:r.webViewLink||y(r.id)}));return JSON.stringify({ok:!0,count:o.length,files:o})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${n}`})}}catch(t){return JSON.stringify({ok:!1,error:t.message})}},tools:[{name:"gdocs_create_doc",description:"Create a new Google Doc with a title and optional content (markdown: #/##/### headings, - bullets, 1. numbered lists, **bold**, [links](url), `code`; or plain text). Returns { ok, documentId, url } \u2014 share the url with the user.",input_schema:{type:"object",properties:{title:{type:"string",description:"Document title."},markdown:{type:"string",description:"Document body as markdown (preferred)."},text:{type:"string",description:"Document body as plain text (used when markdown is absent)."}},required:["title"]}},{name:"gdocs_append",description:"Append markdown/text content to the END of an existing Google Doc. Only works on docs this app created or the user explicitly picked (drive.file scope). Accepts a documentId or a full docs.google.com URL. Returns { ok, documentId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},markdown:{type:"string",description:"Content to append, as markdown (preferred)."},text:{type:"string",description:"Content to append, as plain text (used when markdown is absent)."}},required:["documentId"]}},{name:"gdocs_insert_image",description:"Append a LOCAL image file (png/jpg, max 5MB) to the END of an existing Google Doc. The image is uploaded to the user's Drive, made link-readable (role reader / type anyone \u2014 required: the Docs API only renders publicly fetchable image URIs, <2KB URI length, image <50MB and <25 megapixels), then inserted inline. Optional width/height in points (PT). Returns { ok, documentId, fileId, url }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."},imagePath:{type:"string",description:"Local filesystem path to a .png or .jpg/.jpeg image (max 5MB)."},width:{type:"number",description:"Optional display width in points (PT)."},height:{type:"number",description:"Optional display height in points (PT)."}},required:["documentId","imagePath"]}},{name:"gdocs_get",description:"Read a Google Doc back as plain text (truncated to ~20k chars). The drive.file scope grants access ONLY to docs this app created or the user explicitly picked; to read an arbitrary pre-existing doc the user must PICK it once first via the Google Picker (drive.file cannot see un-picked files). Returns { ok, documentId, title, url, text }.",input_schema:{type:"object",properties:{documentId:{type:"string",description:"Google Docs documentId OR a full https://docs.google.com/document/d/... URL."}},required:["documentId"]}},{name:"gdocs_list_created",description:"List the Google Docs visible to this integration, newest first (max 25). NOTE: under the drive.file scope this lists ONLY docs the app created or the user explicitly picked \u2014 it is NOT a full Drive search. Returns { ok, count, files:[{ documentId, title, modifiedTime, url }] }.",input_schema:{type:"object",properties:{}}}]};export{Y as NON_OWNER_REFUSAL,F as chatStrictPersonal,z as extractPlainText,p as googleApi,re as googleDocsSkill,J as injectedGoogleToken,x as markdownToRequests,k as parseDocId,Z as parseInlineMarkdown,q as senderIsNonOwner};
package/dist/hubspot.js CHANGED
@@ -1 +1 @@
1
- import{existsSync as h}from"fs";import{fileURLToPath as g}from"url";import{dirname as f,resolve as _}from"path";import{resolveIntegrationToken as T}from"@zibby/core/backend-client.js";var y=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",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"}),S=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 i=f(g(import.meta.url)),n=_(i,"..","bin","mcp-skill.mjs");return h(n)?n:null}async function p(i,n={}){let{token:e}=await T("hubspot");if(!e)throw new Error("HubSpot not connected \u2014 Connect HubSpot in Integrations.");let t=i.startsWith("https://")?i:`https://api.hubapi.com${i}`,r={Authorization:`Bearer ${e}`,Accept:"application/json",...n.body?{"Content-Type":"application/json"}:{}},o=await fetch(t,{method:n.method||"GET",headers:r,body:n.body?JSON.stringify(n.body):void 0});if(!o.ok){let a=await o.text().catch(()=>""),c=o.status===401||o.status===403?" \u2014 token invalid/expired or missing the required Private App scope for this object":"";throw new Error(`HubSpot API ${o.status}${c}: ${a.slice(0,300)}`)}let s=await o.text().catch(()=>"");if(!s)return{};try{return JSON.parse(s)}catch{return{raw:s}}}function d(i){return typeof i!="string"?null:i.trim()||null}function m(i,n={}){let e=new URLSearchParams;if(i!=null){let r=Array.isArray(i)?i.join(","):String(i);r&&e.set("properties",r)}for(let[r,o]of Object.entries(n))o!=null&&o!==""&&e.set(r,String(o));let t=e.toString();return t?`?${t}`:""}var u="The CRM object type \u2014 one of the common values `contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions` (customer feedback: NPS/CSAT/CES), or any custom object name/id.",P={id:"hubspot",serverName:"hubspot",allowedTools:["mcp__hubspot__*"],requiresIntegration:y.HUBSPOT,envKeys:[],description:"HubSpot CRM \u2014 search/read/create/update contacts, companies, deals, tickets, notes and feedback submissions via the HubSpot REST API.",promptFragment:"## HubSpot CRM\nYou have access to the user's HubSpot CRM via the HubSpot REST API (OAuth \u2014 the user connects HubSpot in Integrations; the token is resolved and auto-refreshed for you). The connected app grants the CRM scopes for the objects you touch.\n\nHubSpot's object model is **uniform** \u2014 nearly every tool takes an `objectType` (`contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions`, or a custom object). Records are `{ id, properties }`; you set/read named properties.\n\n**Before you create/update/search, call `hubspot_list_properties` to learn the valid property names for that object type** (they're not guessable). `feedback_submissions` is where NPS/CSAT/CES customer-feedback survey responses live.\n\n### Identity\n- hubspot_whoami: Confirm the token works \u2014 returns the portal (hub) id, account type, time zone, UI domain.\n\n### Schema\n- hubspot_list_properties: List the defined properties (name, label, type, fieldType) for an objectType. Do this first so you use real property names.\n\n### Read\n- hubspot_search: Search an objectType by full-text `query` OR structured `filters` (array of {propertyName, operator, value}). Returns { total, results:[{id, properties}] }.\n- hubspot_get_object: Fetch one record by id (optionally selecting specific properties).\n- hubspot_list_objects: Page through all records of an objectType (limit + after cursor).\n\n### Write\n- hubspot_create_object: Create a record from a `properties` object.\n- hubspot_update_object: Patch a record's `properties` by id.\n- hubspot_create_note: Convenience \u2014 log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket.\n- hubspot_associate: Associate two records (fromType/fromId \u2194 toType/toId) with the default association type.",resolve(){let i=j();if(!i)return{command:null,args:[],env:{},description:this.description};let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);return{type:"stdio",command:"node",args:[i,"../dist/hubspot.js","hubspotSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(i,n){try{let e=n||{};switch(i){case"hubspot_whoami":{let t=await p("/account-info/v3/details");return JSON.stringify({portalId:t.portalId,accountType:t.accountType,timeZone:t.timeZone,uiDomain:t.uiDomain,companyCurrency:t.companyCurrency})}case"hubspot_list_properties":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required (e.g. contacts, companies, deals, tickets, feedback_submissions)"});let o=((await p(`/crm/v3/properties/${encodeURIComponent(t)}`)).results||[]).map(s=>({name:s.name,label:s.label,type:s.type,fieldType:s.fieldType}));return JSON.stringify({objectType:t,count:o.length,properties:o})}case"hubspot_search":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});let o={limit:Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20};e.query&&(o.query=String(e.query)),Array.isArray(e.filters)&&e.filters.length&&(o.filterGroups=[{filters:e.filters}]),e.properties!=null&&(o.properties=Array.isArray(e.properties)?e.properties:String(e.properties).split(",").map(a=>a.trim()).filter(Boolean));let s=await p(`/crm/v3/objects/${encodeURIComponent(t)}/search`,{method:"POST",body:o});return JSON.stringify({total:s.total??(s.results?s.results.length:0),results:(s.results||[]).map(a=>({id:a.id,properties:a.properties}))})}case"hubspot_get_object":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});let r=m(e.properties,{associations:e.associations}),o=await p(`/crm/v3/objects/${encodeURIComponent(t)}/${encodeURIComponent(e.id)}${r}`);return JSON.stringify({id:o.id,properties:o.properties,...o.associations?{associations:o.associations}:{}})}case"hubspot_list_objects":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});let r=Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20,o=m(e.properties,{limit:r,after:e.after}),s=await p(`/crm/v3/objects/${encodeURIComponent(t)}${o}`);return JSON.stringify({results:(s.results||[]).map(a=>({id:a.id,properties:a.properties})),paging:s.paging||null})}case"hubspot_create_object":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value } \u2014 call hubspot_list_properties first for valid names)"});let r=await p(`/crm/v3/objects/${encodeURIComponent(t)}`,{method:"POST",body:{properties:e.properties}});return JSON.stringify({id:r.id,properties:r.properties})}case"hubspot_update_object":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value })"});let r=await p(`/crm/v3/objects/${encodeURIComponent(t)}/${encodeURIComponent(e.id)}`,{method:"PATCH",body:{properties:e.properties}});return JSON.stringify({id:r.id,properties:r.properties})}case"hubspot_create_note":{if(!e.body||typeof e.body!="string")return JSON.stringify({error:"body is required (the note text)"});let t=typeof e.timestamp=="string"&&e.timestamp?e.timestamp:null;if(!t)try{t=new Date().toISOString()}catch{t=null}if(!t)return JSON.stringify({error:"timestamp is required (pass an ISO 8601 string, e.g. 2026-01-01T00:00:00.000Z)"});let r=await p("/crm/v3/objects/notes",{method:"POST",body:{properties:{hs_note_body:e.body,hs_timestamp:t}}}),o=r.id,s=[["contacts",e.contactId],["companies",e.companyId],["deals",e.dealId],["tickets",e.ticketId]].filter(([,c])=>c!=null&&c!==""),a=[];for(let[c,l]of s)try{await p(`/crm/v4/objects/notes/${encodeURIComponent(o)}/associations/default/${c}/${encodeURIComponent(l)}`,{method:"PUT"}),a.push({toType:c,toId:String(l)})}catch(b){a.push({toType:c,toId:String(l),error:b.message})}return JSON.stringify({id:o,properties:r.properties,associatedTo:a})}case"hubspot_associate":{let t=d(e.fromType),r=d(e.toType);return!t||!e.fromId||!r||!e.toId?JSON.stringify({error:"fromType, fromId, toType and toId are all required"}):(await p(`/crm/v4/objects/${encodeURIComponent(t)}/${encodeURIComponent(e.fromId)}/associations/default/${encodeURIComponent(r)}/${encodeURIComponent(e.toId)}`,{method:"PUT"}),JSON.stringify({ok:!0}))}default:return JSON.stringify({error:`Unknown tool: ${i}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"hubspot_whoami",description:"Confirm the HubSpot token works: returns the portal (hub) id, account type, time zone and UI domain.",input_schema:{type:"object",properties:{}}},{name:"hubspot_list_properties",description:"List the defined properties (name, label, type, fieldType) for a CRM object type. Call this FIRST so you use valid property names when creating/updating/searching.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u}},required:["objectType"]}},{name:"hubspot_search",description:"Search a CRM object type. Pass a full-text `query` OR structured `filters` (array of {propertyName, operator, value}, e.g. operator EQ/CONTAINS_TOKEN/GT/\u2026). Returns { total, results:[{id, properties}] }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},query:{type:"string",description:"Optional full-text search string."},filters:{type:"array",description:"Optional structured filters (ANDed). Each: { propertyName, operator, value }. Operators: EQ, NEQ, LT, LTE, GT, GTE, CONTAINS_TOKEN, HAS_PROPERTY, IN, \u2026",items:{type:"object",properties:{propertyName:{type:"string"},operator:{type:"string"},value:{type:"string"}}}},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each result."},limit:{type:"number",description:"Max results (default 20)."}},required:["objectType"]}},{name:"hubspot_get_object",description:"Fetch one CRM record by id. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},id:{type:"string",description:"The record id."},properties:{type:"array",items:{type:"string"},description:"Optional: specific property names to return."},associations:{type:"string",description:'Optional: comma-separated object types to also return associations for (e.g. "companies,deals").'}},required:["objectType","id"]}},{name:"hubspot_list_objects",description:"Page through records of a CRM object type. Returns { results, paging } \u2014 pass paging.next.after back as `after` for the next page.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each record."},limit:{type:"number",description:"Page size (default 20)."},after:{type:"string",description:"Optional paging cursor from a previous response (paging.next.after)."}},required:["objectType"]}},{name:"hubspot_create_object",description:"Create a CRM record. Pass `properties` as an object of { propertyName: value } (call hubspot_list_properties first for valid names). Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},properties:{type:"object",description:"Object of { propertyName: value } to set on the new record."}},required:["objectType","properties"]}},{name:"hubspot_update_object",description:"Update (PATCH) a CRM record by id. Pass `properties` as an object of { propertyName: value }. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},id:{type:"string",description:"The record id to update."},properties:{type:"object",description:"Object of { propertyName: value } to change."}},required:["objectType","id","properties"]}},{name:"hubspot_create_note",description:"Log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket. Returns { id, associatedTo }.",input_schema:{type:"object",properties:{body:{type:"string",description:"The note text (stored as hs_note_body)."},contactId:{type:"string",description:"Optional: associate the note to this contact id."},companyId:{type:"string",description:"Optional: associate the note to this company id."},dealId:{type:"string",description:"Optional: associate the note to this deal id."},ticketId:{type:"string",description:"Optional: associate the note to this ticket id."},timestamp:{type:"string",description:"Optional ISO 8601 timestamp for the note (defaults to now)."}},required:["body"]}},{name:"hubspot_associate",description:"Associate two CRM records with the default association type (e.g. a contact to a company). Returns { ok:true }.",input_schema:{type:"object",properties:{fromType:{type:"string",description:"Source object type (e.g. contacts)."},fromId:{type:"string",description:"Source record id."},toType:{type:"string",description:"Target object type (e.g. companies)."},toId:{type:"string",description:"Target record id."}},required:["fromType","fromId","toType","toId"]}}]};export{P as hubspotSkill};
1
+ import{existsSync as h}from"fs";import{fileURLToPath as g}from"url";import{dirname as f,resolve as _}from"path";import{resolveIntegrationToken as T}from"@zibby/core/backend-client.js";var y=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",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"}),I=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},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 i=f(g(import.meta.url)),n=_(i,"..","bin","mcp-skill.mjs");return h(n)?n:null}async function p(i,n={}){let{token:e}=await T("hubspot");if(!e)throw new Error("HubSpot not connected \u2014 Connect HubSpot in Integrations.");let t=i.startsWith("https://")?i:`https://api.hubapi.com${i}`,r={Authorization:`Bearer ${e}`,Accept:"application/json",...n.body?{"Content-Type":"application/json"}:{}},o=await fetch(t,{method:n.method||"GET",headers:r,body:n.body?JSON.stringify(n.body):void 0});if(!o.ok){let a=await o.text().catch(()=>""),c=o.status===401||o.status===403?" \u2014 token invalid/expired or missing the required Private App scope for this object":"";throw new Error(`HubSpot API ${o.status}${c}: ${a.slice(0,300)}`)}let s=await o.text().catch(()=>"");if(!s)return{};try{return JSON.parse(s)}catch{return{raw:s}}}function d(i){return typeof i!="string"?null:i.trim()||null}function m(i,n={}){let e=new URLSearchParams;if(i!=null){let r=Array.isArray(i)?i.join(","):String(i);r&&e.set("properties",r)}for(let[r,o]of Object.entries(n))o!=null&&o!==""&&e.set(r,String(o));let t=e.toString();return t?`?${t}`:""}var u="The CRM object type \u2014 one of the common values `contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions` (customer feedback: NPS/CSAT/CES), or any custom object name/id.",k={id:"hubspot",serverName:"hubspot",allowedTools:["mcp__hubspot__*"],requiresIntegration:y.HUBSPOT,envKeys:["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"HubSpot CRM \u2014 search/read/create/update contacts, companies, deals, tickets, notes and feedback submissions via the HubSpot REST API.",promptFragment:"## HubSpot CRM\nYou have access to the user's HubSpot CRM via the HubSpot REST API (OAuth \u2014 the user connects HubSpot in Integrations; the token is resolved and auto-refreshed for you). The connected app grants the CRM scopes for the objects you touch.\n\nHubSpot's object model is **uniform** \u2014 nearly every tool takes an `objectType` (`contacts`, `companies`, `deals`, `tickets`, `notes`, `tasks`, `feedback_submissions`, or a custom object). Records are `{ id, properties }`; you set/read named properties.\n\n**Before you create/update/search, call `hubspot_list_properties` to learn the valid property names for that object type** (they're not guessable). `feedback_submissions` is where NPS/CSAT/CES customer-feedback survey responses live.\n\n### Identity\n- hubspot_whoami: Confirm the token works \u2014 returns the portal (hub) id, account type, time zone, UI domain.\n\n### Schema\n- hubspot_list_properties: List the defined properties (name, label, type, fieldType) for an objectType. Do this first so you use real property names.\n\n### Read\n- hubspot_search: Search an objectType by full-text `query` OR structured `filters` (array of {propertyName, operator, value}). Returns { total, results:[{id, properties}] }.\n- hubspot_get_object: Fetch one record by id (optionally selecting specific properties).\n- hubspot_list_objects: Page through all records of an objectType (limit + after cursor).\n\n### Write\n- hubspot_create_object: Create a record from a `properties` object.\n- hubspot_update_object: Patch a record's `properties` by id.\n- hubspot_create_note: Convenience \u2014 log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket.\n- hubspot_associate: Associate two records (fromType/fromId \u2194 toType/toId) with the default association type.",resolve(){let i=j();if(!i)return{command:null,args:[],env:{},description:this.description};let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);return{type:"stdio",command:"node",args:[i,"../dist/hubspot.js","hubspotSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(i,n){try{let e=n||{};switch(i){case"hubspot_whoami":{let t=await p("/account-info/v3/details");return JSON.stringify({portalId:t.portalId,accountType:t.accountType,timeZone:t.timeZone,uiDomain:t.uiDomain,companyCurrency:t.companyCurrency})}case"hubspot_list_properties":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required (e.g. contacts, companies, deals, tickets, feedback_submissions)"});let o=((await p(`/crm/v3/properties/${encodeURIComponent(t)}`)).results||[]).map(s=>({name:s.name,label:s.label,type:s.type,fieldType:s.fieldType}));return JSON.stringify({objectType:t,count:o.length,properties:o})}case"hubspot_search":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});let o={limit:Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20};e.query&&(o.query=String(e.query)),Array.isArray(e.filters)&&e.filters.length&&(o.filterGroups=[{filters:e.filters}]),e.properties!=null&&(o.properties=Array.isArray(e.properties)?e.properties:String(e.properties).split(",").map(a=>a.trim()).filter(Boolean));let s=await p(`/crm/v3/objects/${encodeURIComponent(t)}/search`,{method:"POST",body:o});return JSON.stringify({total:s.total??(s.results?s.results.length:0),results:(s.results||[]).map(a=>({id:a.id,properties:a.properties}))})}case"hubspot_get_object":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});let r=m(e.properties,{associations:e.associations}),o=await p(`/crm/v3/objects/${encodeURIComponent(t)}/${encodeURIComponent(e.id)}${r}`);return JSON.stringify({id:o.id,properties:o.properties,...o.associations?{associations:o.associations}:{}})}case"hubspot_list_objects":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});let r=Number.isFinite(Number(e.limit))&&Number(e.limit)>0?Math.trunc(Number(e.limit)):20,o=m(e.properties,{limit:r,after:e.after}),s=await p(`/crm/v3/objects/${encodeURIComponent(t)}${o}`);return JSON.stringify({results:(s.results||[]).map(a=>({id:a.id,properties:a.properties})),paging:s.paging||null})}case"hubspot_create_object":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value } \u2014 call hubspot_list_properties first for valid names)"});let r=await p(`/crm/v3/objects/${encodeURIComponent(t)}`,{method:"POST",body:{properties:e.properties}});return JSON.stringify({id:r.id,properties:r.properties})}case"hubspot_update_object":{let t=d(e.objectType);if(!t)return JSON.stringify({error:"objectType is required"});if(!e.id)return JSON.stringify({error:"id is required"});if(!e.properties||typeof e.properties!="object"||Array.isArray(e.properties))return JSON.stringify({error:"properties is required (an object of { propertyName: value })"});let r=await p(`/crm/v3/objects/${encodeURIComponent(t)}/${encodeURIComponent(e.id)}`,{method:"PATCH",body:{properties:e.properties}});return JSON.stringify({id:r.id,properties:r.properties})}case"hubspot_create_note":{if(!e.body||typeof e.body!="string")return JSON.stringify({error:"body is required (the note text)"});let t=typeof e.timestamp=="string"&&e.timestamp?e.timestamp:null;if(!t)try{t=new Date().toISOString()}catch{t=null}if(!t)return JSON.stringify({error:"timestamp is required (pass an ISO 8601 string, e.g. 2026-01-01T00:00:00.000Z)"});let r=await p("/crm/v3/objects/notes",{method:"POST",body:{properties:{hs_note_body:e.body,hs_timestamp:t}}}),o=r.id,s=[["contacts",e.contactId],["companies",e.companyId],["deals",e.dealId],["tickets",e.ticketId]].filter(([,c])=>c!=null&&c!==""),a=[];for(let[c,l]of s)try{await p(`/crm/v4/objects/notes/${encodeURIComponent(o)}/associations/default/${c}/${encodeURIComponent(l)}`,{method:"PUT"}),a.push({toType:c,toId:String(l)})}catch(b){a.push({toType:c,toId:String(l),error:b.message})}return JSON.stringify({id:o,properties:r.properties,associatedTo:a})}case"hubspot_associate":{let t=d(e.fromType),r=d(e.toType);return!t||!e.fromId||!r||!e.toId?JSON.stringify({error:"fromType, fromId, toType and toId are all required"}):(await p(`/crm/v4/objects/${encodeURIComponent(t)}/${encodeURIComponent(e.fromId)}/associations/default/${encodeURIComponent(r)}/${encodeURIComponent(e.toId)}`,{method:"PUT"}),JSON.stringify({ok:!0}))}default:return JSON.stringify({error:`Unknown tool: ${i}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"hubspot_whoami",description:"Confirm the HubSpot token works: returns the portal (hub) id, account type, time zone and UI domain.",input_schema:{type:"object",properties:{}}},{name:"hubspot_list_properties",description:"List the defined properties (name, label, type, fieldType) for a CRM object type. Call this FIRST so you use valid property names when creating/updating/searching.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u}},required:["objectType"]}},{name:"hubspot_search",description:"Search a CRM object type. Pass a full-text `query` OR structured `filters` (array of {propertyName, operator, value}, e.g. operator EQ/CONTAINS_TOKEN/GT/\u2026). Returns { total, results:[{id, properties}] }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},query:{type:"string",description:"Optional full-text search string."},filters:{type:"array",description:"Optional structured filters (ANDed). Each: { propertyName, operator, value }. Operators: EQ, NEQ, LT, LTE, GT, GTE, CONTAINS_TOKEN, HAS_PROPERTY, IN, \u2026",items:{type:"object",properties:{propertyName:{type:"string"},operator:{type:"string"},value:{type:"string"}}}},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each result."},limit:{type:"number",description:"Max results (default 20)."}},required:["objectType"]}},{name:"hubspot_get_object",description:"Fetch one CRM record by id. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},id:{type:"string",description:"The record id."},properties:{type:"array",items:{type:"string"},description:"Optional: specific property names to return."},associations:{type:"string",description:'Optional: comma-separated object types to also return associations for (e.g. "companies,deals").'}},required:["objectType","id"]}},{name:"hubspot_list_objects",description:"Page through records of a CRM object type. Returns { results, paging } \u2014 pass paging.next.after back as `after` for the next page.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},properties:{type:"array",items:{type:"string"},description:"Optional: property names to return on each record."},limit:{type:"number",description:"Page size (default 20)."},after:{type:"string",description:"Optional paging cursor from a previous response (paging.next.after)."}},required:["objectType"]}},{name:"hubspot_create_object",description:"Create a CRM record. Pass `properties` as an object of { propertyName: value } (call hubspot_list_properties first for valid names). Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},properties:{type:"object",description:"Object of { propertyName: value } to set on the new record."}},required:["objectType","properties"]}},{name:"hubspot_update_object",description:"Update (PATCH) a CRM record by id. Pass `properties` as an object of { propertyName: value }. Returns { id, properties }.",input_schema:{type:"object",properties:{objectType:{type:"string",description:u},id:{type:"string",description:"The record id to update."},properties:{type:"object",description:"Object of { propertyName: value } to change."}},required:["objectType","id","properties"]}},{name:"hubspot_create_note",description:"Log a note (hs_note_body) and optionally associate it to a contact/company/deal/ticket. Returns { id, associatedTo }.",input_schema:{type:"object",properties:{body:{type:"string",description:"The note text (stored as hs_note_body)."},contactId:{type:"string",description:"Optional: associate the note to this contact id."},companyId:{type:"string",description:"Optional: associate the note to this company id."},dealId:{type:"string",description:"Optional: associate the note to this deal id."},ticketId:{type:"string",description:"Optional: associate the note to this ticket id."},timestamp:{type:"string",description:"Optional ISO 8601 timestamp for the note (defaults to now)."}},required:["body"]}},{name:"hubspot_associate",description:"Associate two CRM records with the default association type (e.g. a contact to a company). Returns { ok:true }.",input_schema:{type:"object",properties:{fromType:{type:"string",description:"Source object type (e.g. contacts)."},fromId:{type:"string",description:"Source record id."},toType:{type:"string",description:"Target object type (e.g. companies)."},toId:{type:"string",description:"Target record id."}},required:["fromType","fromId","toType","toId"]}}]};export{k as hubspotSkill};