@buildbase/sdk 0.0.60 → 0.0.62

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +95 -0
  3. package/dist/css/styles.css +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.ts +84 -0
  6. package/dist/index.mjs +1 -1
  7. package/dist/mcp/index.cjs +1 -1
  8. package/dist/mcp/index.d.ts +23 -0
  9. package/dist/mcp/index.mjs +1 -1
  10. package/dist/react/chunks/SettingsDialog-CKwldz7y.mjs +2 -0
  11. package/dist/react/chunks/{SettingsDialog-DzcwBYsg.cjs → SettingsDialog-D4FCwpN7.cjs} +1 -1
  12. package/dist/react/chunks/SubscriptionDialog-DJmrU0r1.cjs +2 -0
  13. package/dist/react/chunks/SubscriptionDialog-DoWnS_JD.mjs +2 -0
  14. package/dist/react/chunks/react-Be1VMiVO.mjs +2 -0
  15. package/dist/react/chunks/react-ClieHJPH.cjs +2 -0
  16. package/dist/react/index.cjs +1 -1
  17. package/dist/react/index.d.ts +186 -26
  18. package/dist/react/index.mjs +1 -1
  19. package/dist/tracking/index.cjs +2 -0
  20. package/dist/tracking/index.d.ts +657 -0
  21. package/dist/tracking/index.mjs +2 -0
  22. package/package.json +12 -2
  23. package/dist/react/chunks/SettingsDialog-4yk6t4tT.mjs +0 -2
  24. package/dist/react/chunks/SubscriptionDialog-COw79gAi.cjs +0 -2
  25. package/dist/react/chunks/SubscriptionDialog-DLM_WA84.mjs +0 -2
  26. package/dist/react/chunks/react-D6q1fjoE.cjs +0 -2
  27. package/dist/react/chunks/react-DX2YGh4O.mjs +0 -2
  28. /package/dist/react/chunks/{ar-DHxjPtfZ.mjs → ar-CHTRXlXt.mjs} +0 -0
  29. /package/dist/react/chunks/{ar-D7uaSur2.cjs → ar-DPJVNHJV.cjs} +0 -0
  30. /package/dist/react/chunks/{de-D_xfGk1N.mjs → de-CdPeKWZ2.mjs} +0 -0
  31. /package/dist/react/chunks/{de-CBzx6NJq.cjs → de-DPd09yf-.cjs} +0 -0
  32. /package/dist/react/chunks/{es-D4-Dv2t5.mjs → es-BWGnjJKJ.mjs} +0 -0
  33. /package/dist/react/chunks/{es-WVRwuj-e.cjs → es-WdOYGt6G.cjs} +0 -0
  34. /package/dist/react/chunks/{fr-DurP7qkZ.mjs → fr-Big5DFPB.mjs} +0 -0
  35. /package/dist/react/chunks/{fr-CEpK52jT.cjs → fr-LIbCvYeh.cjs} +0 -0
  36. /package/dist/react/chunks/{hi-CVqVRSoy.cjs → hi-BoCY3pFe.cjs} +0 -0
  37. /package/dist/react/chunks/{hi-7roM83DB.mjs → hi-jArNRknR.mjs} +0 -0
  38. /package/dist/react/chunks/{ja-DT8x4SW1.mjs → ja-Cwdz0hCu.mjs} +0 -0
  39. /package/dist/react/chunks/{ja-BrDXec_v.cjs → ja-E0jqCiVq.cjs} +0 -0
  40. /package/dist/react/chunks/{zh-CH1Z55Je.mjs → zh-glRKcdia.mjs} +0 -0
  41. /package/dist/react/chunks/{zh-CdCzcD53.cjs → zh-tU-AqFYI.cjs} +0 -0
@@ -1 +1 @@
1
- import{z as e}from"zod";function t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function r(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4==0?"":"=".repeat(4-t.length%4),n=atob(t+r),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return s}const n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),s=(e,t)=>e>>>t|e<<32-t;function o(e){let t=1779033703,r=3144134277,o=1013904242,i=2773480762,a=1359893119,c=2600822924,u=528734635,l=1541459225;const p=e.length,d=p+1,h=d+(56-d%64+64)%64+8,g=new Uint8Array(h);g.set(e,0),g[p]=128;const m=8*p,f=Math.floor(m/4294967296),w=m>>>0;g[h-8]=f>>>24&255,g[h-7]=f>>>16&255,g[h-6]=f>>>8&255,g[h-5]=255&f,g[h-4]=w>>>24&255,g[h-3]=w>>>16&255,g[h-2]=w>>>8&255,g[h-1]=255&w;const y=new Uint32Array(64);for(let e=0;e<h;e+=64){for(let t=0;t<16;t++){const r=e+4*t;y[t]=g[r]<<24|g[r+1]<<16|g[r+2]<<8|g[r+3]}for(let e=16;e<64;e++){const t=s(y[e-15],7)^s(y[e-15],18)^y[e-15]>>>3,r=s(y[e-2],17)^s(y[e-2],19)^y[e-2]>>>10;y[e]=y[e-16]+t+y[e-7]+r>>>0}let p=t,d=r,h=o,m=i,f=a,w=c,b=u,k=l;for(let e=0;e<64;e++){const t=k+(s(f,6)^s(f,11)^s(f,25))+(f&w^~f&b)+n[e]+y[e]>>>0,r=p&d^p&h^d&h;k=b,b=w,w=f,f=m+t>>>0,m=h,h=d,d=p,p=t+((s(p,2)^s(p,13)^s(p,22))+r>>>0)>>>0}t=t+p>>>0,r=r+d>>>0,o=o+h>>>0,i=i+m>>>0,a=a+f>>>0,c=c+w>>>0,u=u+b>>>0,l=l+k>>>0}const b=new Uint8Array(32),k=[t,r,o,i,a,c,u,l];for(let e=0;e<8;e++)b[4*e]=k[e]>>>24&255,b[4*e+1]=k[e]>>>16&255,b[4*e+2]=k[e]>>>8&255,b[4*e+3]=255&k[e];return b}function i(e){return(new TextEncoder).encode(e)}function a(e,t){let r=e;r.length>64&&(r=o(r));const n=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<r.length?r[e]:0;n[e]=54^t,s[e]=92^t}const i=o(c(n,t));return o(c(s,i))}function c(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}class u extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function l(e){const t=JSON.parse((new TextDecoder).decode(r(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function p(e,t,n={}){const s=n.clockToleranceSec??60,o=n.requireExp??!0;if(!e||!t)throw new u("invalid_token","Missing token or client secret");const c=e.split(".");if(3!==c.length)throw new u("invalid_token","Malformed JWT");const[p,d,h]=c;let g,m;try{g=l(p),m=l(d)}catch{throw new u("invalid_token","Unreadable JWT segments")}if("HS256"!==g.alg)throw new u("invalid_algorithm",`Unexpected JWT alg: ${String(g.alg)}`);const f=a(i(t),i(`${p}.${d}`));let w;try{w=r(h)}catch{throw new u("invalid_signature","Unreadable JWT signature")}if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(f,w))throw new u("invalid_signature","JWT signature verification failed");!function(e){for(const t of["iss","sub","jti"])if(void 0!==e[t]&&"string"!=typeof e[t])throw new u("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const r=e[t];if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)))throw new u("invalid_token",`JWT ${t} claim must be a finite number`)}const t=e.aud;if(!(void 0===t||"string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new u("invalid_token","JWT aud claim must be a string or string array")}(m);const y=Math.floor(Date.now()/1e3);if(o&&"number"!=typeof m.exp)throw new u("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof m.exp&&y>m.exp+s)throw new u("token_expired","JWT has expired");if("number"==typeof m.nbf&&y+s<m.nbf)throw new u("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&m.iss!==n.issuer)throw new u("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=m.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new u("invalid_audience","JWT audience mismatch")}return m}function d(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function h(e){return t(i(JSON.stringify(e)))}function g(e,r,n){if(!r)throw new u("invalid_secret","Missing signing secret");const s=Math.floor(Date.now()/1e3),o={iat:s,exp:s+(n?.expiresInSec??3600),...e},c=`${h({alg:"HS256",typ:"JWT"})}.${h(o)}`;return`${c}.${t(a(i(r),i(c)))}`}function m(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function f(e){const t=[`Bearer resource_metadata="${m(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${m(e.error)}"`),e.errorDescription&&t.push(`error_description="${m(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const w=e.string().optional().describe("Workspace id. Omit to use the workspace bound to your token.");function y(e,t){const r=e.workspaceId??t.workspaceId;if(!r)throw new Error("workspaceId is required — call list_workspaces to find one.");return r}const b={readOnlyHint:!0},k=[{name:"list_workspaces",description:"List the authenticated user's workspaces (id, name, roles).",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.workspace.list()},{name:"get_workspace",description:"Get one workspace: name, members, feature flags, quota snapshot.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.workspace.get(y(e,t))},{name:"get_user_profile",description:"Get the authenticated user's profile.",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.users.getProfile()},{name:"list_workspace_users",description:"List the members of a workspace with their roles.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.users.list(y(e,t))},{name:"get_subscription",description:"Get a workspace's subscription: plan, status, interval, seats.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.subscription.get(y(e,t))},{name:"get_plans",description:"Get the plan group available to a workspace (plans, prices, quotas).",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.plans.getGroup(y(e,t))},{name:"list_invoices",description:"List a workspace's invoices (newest first).",inputSchema:e.object({workspaceId:w,limit:e.number().int().min(1).max(100).optional().describe("Max invoices to return."),startingAfter:e.string().optional().describe("Invoice id to paginate after.")}),annotations:b,execute:(e,t)=>t.bb.invoices.list(y(e,t),e.limit,e.startingAfter)},{name:"get_quota_usage",description:"Get usage vs. limit for one quota in a workspace.",inputSchema:e.object({workspaceId:w,quotaSlug:e.string().describe('The quota slug, e.g. "api-calls".')}),annotations:b,execute:(e,t)=>t.bb.usage.getQuota(y(e,t),e.quotaSlug)},{name:"get_all_quota_usage",description:"Get usage vs. limit for every quota in a workspace.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.usage.getAll(y(e,t))},{name:"get_credit_balance",description:"Get a workspace's prepaid credit balance.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.credits.getBalance(y(e,t))},{name:"list_credit_transactions",description:"Get a workspace's credit transaction history (paginated).",inputSchema:e.object({workspaceId:w,limit:e.number().int().min(1).max(100).optional(),page:e.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getTransactions(y(e,t),{...void 0!==e.limit?{limit:e.limit}:{},...void 0!==e.page?{page:e.page}:{}})},{name:"check_feature_flag",description:"Check whether a feature flag is enabled for a workspace.",inputSchema:e.object({workspaceId:w,key:e.string().describe("The feature slug.")}),annotations:b,execute:async(e,t)=>{const r=y(e,t),n=await t.bb.workspace.get(r),s=n.features?.[e.key];if(void 0!==s)return{key:e.key,enabled:s,source:"workspace"};const o=(await t.bb.features.list()).find(t=>t.slug===e.key);if(!o)throw new Error(`Unknown feature flag: ${e.key}`);return{key:e.key,enabled:o.defaultValue,source:"default"}}},{name:"check_permission",description:"Check whether a user has permission(s) in a workspace.",inputSchema:e.object({workspaceId:w,permission:e.union([e.string(),e.array(e.string())]).describe("A permission (or list — all must hold), platform or app-defined."),userId:e.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const n=await t.bb.permissions.check(y(e,t),r,e.permission);return{userId:r,permission:e.permission,allowed:n}}},{name:"resolve_permissions",description:"List every permission a user holds in a workspace.",inputSchema:e.object({workspaceId:w,userId:e.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const n=await t.bb.permissions.resolve(y(e,t),r);return{userId:r,permissions:Array.from(n)}}},{name:"get_invoice",description:"Get one invoice by id.",inputSchema:e.object({workspaceId:w,invoiceId:e.string().describe("The invoice id.")}),annotations:b,execute:(e,t)=>t.bb.invoices.get(y(e,t),e.invoiceId)},{name:"get_plan_versions",description:"List the plan-group versions available to a workspace.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.plans.getVersions(y(e,t))},{name:"get_public_plans",description:"Get a public plan group by slug (no workspace / auth needed).",inputSchema:e.object({slug:e.string().describe("The plan-group slug.")}),annotations:b,execute:(e,t)=>t.bb.plans.getPublic(e.slug)},{name:"get_plan_version",description:"Get one public plan-group version by id (no auth needed).",inputSchema:e.object({groupVersionId:e.string().describe("The plan-group version id.")}),annotations:b,execute:(e,t)=>t.bb.plans.getVersion(e.groupVersionId)},{name:"get_usage_logs",description:"Get a workspace's usage log entries (paginated, filterable).",inputSchema:e.object({workspaceId:w,quotaSlug:e.string().optional(),from:e.string().optional().describe("ISO date lower bound."),to:e.string().optional().describe("ISO date upper bound."),source:e.string().optional(),page:e.number().int().min(1).optional(),limit:e.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.usage.getLogs(y(e,t),n)}},{name:"get_settings",description:"Get the organization settings.",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.settings.get()},{name:"get_credit_packages",description:"List the credit packages a workspace can purchase.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.credits.getPackages(y(e,t))},{name:"get_credit_buckets",description:"Get a workspace's credit buckets (paginated).",inputSchema:e.object({workspaceId:w,status:e.string().optional(),source:e.string().optional(),page:e.number().int().min(1).optional(),limit:e.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.credits.getBuckets(y(e,t),n)}},{name:"get_expiring_credits",description:"Get credits expiring within N days (default 7).",inputSchema:e.object({workspaceId:w,days:e.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getExpiring(y(e,t),e.days)},{name:"get_public_credit_packages",description:"List credit packages publicly (no workspace / auth needed).",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.credits.getPublicPackages()}],S=[{name:"record_usage",description:"Record quota usage for a workspace (metered billing).",inputSchema:e.object({workspaceId:w,quotaSlug:e.string().describe("The quota slug to record against."),quantity:e.number().positive().describe("Amount of usage to record."),idempotencyKey:e.string().optional().describe("Dedupe key for safe retries."),metadata:e.record(e.string(),e.unknown()).optional()}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},execute:(e,t)=>t.bb.usage.record(y(e,t),{quotaSlug:e.quotaSlug,quantity:e.quantity,source:"mcp",...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{},...e.metadata?{metadata:e.metadata}:{}})},{name:"consume_credits",description:"Consume prepaid credits from a workspace's balance.",inputSchema:e.object({workspaceId:w,amount:e.number().positive().describe("Credits to consume."),description:e.string().optional().describe("What the credits were spent on."),idempotencyKey:e.string().optional().describe("Dedupe key for safe retries.")}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.credits.consume(y(e,t),{amount:e.amount,...e.description?{description:e.description}:{},...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{}})},{name:"send_notification",description:"Send a notification event to a workspace user (or all members when userId is omitted).",inputSchema:e.object({workspaceId:w,event:e.string().describe('The event slug, e.g. "comment_added".'),userId:e.string().optional().describe("Recipient. Omit to notify all members."),message:e.string().optional().describe("Message body (used for push).")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.notification.send(y(e,t),e.event,e.userId,e.message?{message:e.message}:void 0)},{name:"record_usage_batch",description:"Record multiple usage entries in one call (max 100 items).",inputSchema:e.object({workspaceId:w,items:e.array(e.object({quotaSlug:e.string(),quantity:e.number().positive(),idempotencyKey:e.string().optional(),metadata:e.record(e.string(),e.unknown()).optional()})).min(1).max(100)}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.usage.recordBatch(y(e,t),{items:e.items.map(e=>({...e,source:"mcp"}))})},{name:"create_workspace",description:"Create a new workspace.",inputSchema:e.object({name:e.string().describe("Workspace name."),image:e.string().optional().describe("Image URL.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.workspace.create({name:e.name,...e.image?{image:e.image}:{}})},{name:"update_workspace",description:"Update a workspace's editable fields (name, image).",inputSchema:e.object({workspaceId:w,name:e.string().min(1).optional().describe("New workspace name."),image:e.string().optional().describe("New image URL.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};return void 0!==e.name&&(r.name=e.name),void 0!==e.image&&(r.image=e.image),t.bb.workspace.update(y(e,t),r)}},{name:"delete_workspace",description:"Delete a workspace. Irreversible.",inputSchema:e.object({workspaceId:w}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.workspace.delete(y(e,t))},{name:"invite_workspace_user",description:"Invite a user to a workspace with a role.",inputSchema:e.object({workspaceId:w,email:e.string().describe("Invitee email."),role:e.string().describe("Role to grant.")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.users.invite(y(e,t),e.email,e.role)},{name:"remove_workspace_user",description:"Remove a user from a workspace. Irreversible.",inputSchema:e.object({workspaceId:w,userId:e.string().describe("The user to remove.")}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.users.remove(y(e,t),e.userId)},{name:"update_workspace_user_role",description:"Change a workspace member's role.",inputSchema:e.object({workspaceId:w,userId:e.string(),role:e.string().describe("The new role.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.users.updateRole(y(e,t),e.userId,e.role)},{name:"update_user_profile",description:"Update the authenticated user's own profile (name, image, country, timezone, language, currency).",inputSchema:e.object({name:e.string().min(1).optional(),image:e.string().optional().describe("Profile image URL."),country:e.string().optional().describe("ISO country code."),timezone:e.string().optional().describe("IANA timezone."),language:e.string().optional().describe("Language code."),currency:e.string().optional().describe("Currency code.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};for(const t of["name","image","country","timezone","language","currency"]){const n=e[t];void 0!==n&&(r[t]=n)}return t.bb.users.updateProfile(r)}},{name:"update_feature_flag",description:"Set a feature flag on/off for a workspace.",inputSchema:e.object({workspaceId:w,key:e.string().describe("The feature slug."),value:e.boolean().describe("Enabled?")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.features.update(y(e,t),e.key,e.value)},{name:"create_subscription_checkout",description:"Create a Stripe checkout session to subscribe a workspace to a plan.",inputSchema:e.object({workspaceId:w,planVersionId:e.string(),billingInterval:e.string().optional(),currency:e.string().optional(),successUrl:e.string().optional(),cancelUrl:e.string().optional()}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.subscription.checkout(y(e,t),n)}},{name:"update_subscription",description:"Change a workspace's subscription plan.",inputSchema:e.object({workspaceId:w,planVersionId:e.string(),billingInterval:e.string().optional(),successUrl:e.string().optional(),cancelUrl:e.string().optional()}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.subscription.update(y(e,t),n)}},{name:"cancel_subscription",description:"Cancel a workspace's subscription.",inputSchema:e.object({workspaceId:w}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.subscription.cancel(y(e,t))},{name:"resume_subscription",description:"Resume a workspace's canceled subscription.",inputSchema:e.object({workspaceId:w}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.subscription.resume(y(e,t))},{name:"get_billing_portal_url",description:"Get a Stripe billing-portal URL for a workspace.",inputSchema:e.object({workspaceId:w,returnUrl:e.string().optional()}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.subscription.getBillingPortalUrl(y(e,t),e.returnUrl)},{name:"purchase_credits",description:"Create a Stripe checkout session to buy a credit package.",inputSchema:e.object({workspaceId:w,creditPackageId:e.string(),currency:e.string().optional(),successUrl:e.string().describe("Redirect URL on success."),cancelUrl:e.string().describe("Redirect URL on cancel.")}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.credits.purchase(y(e,t),n)}}],v=new Map([...k,...S].map(e=>[e.name,e]));function E(e){if(!1===e)return[];if("readonly"===e)return[...k];if("all"===e)return[...k,...S];const t=e.include?e.include.map(e=>{const t=v.get(e);if(!t)throw new Error(`Unknown built-in MCP tool: ${e}`);return t}):[...k],r=new Set(e.exclude??[]);return t.filter(e=>!r.has(e.name))}const _=e=>({type:"text",text:e}),I=(e,t)=>({type:"image",data:e,mimeType:t}),T=(e,t)=>({type:"audio",data:e,mimeType:t}),x=(e,t,r)=>({type:"resource_link",uri:e,name:t,...r}),P=e=>({type:"resource",resource:e}),U=e=>{if("object"!=typeof e||null===e)return!1;const t=e;switch(t.type){case"text":return"string"==typeof t.text;case"image":case"audio":return"string"==typeof t.data&&"string"==typeof t.mimeType;case"resource_link":return"string"==typeof t.uri&&"string"==typeof t.name;case"resource":{const e=t.resource;return"object"==typeof e&&null!==e&&"string"==typeof e.uri&&("string"==typeof e.text||"string"==typeof e.blob)}default:return!1}},$=e=>e,C=e=>e,A=e=>e,O=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],R=O[0],j="application/json",J=/^[a-zA-Z0-9_-]{1,128}$/,W=-32002,N=-32700,F=-32600,M=-32601,q=-32602,B=-32603;function L(e,t){const r=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===r)return e[t]}function H(e,t){return{status:e,headers:{"Content-Type":j},body:JSON.stringify(t)}}function D(e,t){return H(200,{jsonrpc:"2.0",id:e??null,result:t})}function G(e,t,r,n=200,s){return H(n,{jsonrpc:"2.0",id:e??null,error:{code:t,message:r,...void 0!==s?{data:s}:{}}})}function K(e){return"object"==typeof e&&null!==e&&"function"==typeof e.safeParse}function z(e){return e instanceof Error?e.message:"string"==typeof e?e:JSON.stringify(e)}function V(t){const r=t.serverInfo??{name:"buildbase-mcp",version:"1.0.0"};t.auth&&!t.auth.resourceMetadataUrl&&console.warn("[buildbase/mcp] auth is enabled but `auth.resourceMetadataUrl` is unset — 401 responses will carry no WWW-Authenticate/resource_metadata pointer, so MCP clients cannot discover your authorization server. Set it to your /.well-known/oauth-protected-resource URL.");const n=e=>e.trim().toLowerCase().replace(/\/+$/,""),s=t.allowedOrigins?new Set(t.allowedOrigins.map(n)):null,o=e=>!!e&&!!s&&s.has(n(e)),i=t.builtinTools??(!!t.buildbase&&"readonly"),a=t.maxRequestBytes??1048576;if(!1!==i&&!t.buildbase)throw new Error("builtinTools require a `buildbase` client — pass one to createMcpHandler, or set builtinTools: false.");const c=new Map;for(const e of E(i))c.set(e.name,e);const u=new Set;for(const e of t.tools??[]){if(!J.test(e.name))throw new Error(`Invalid MCP tool name: "${e.name}" (want ${String(J)})`);if(u.has(e.name))throw new Error(`Duplicate MCP tool name: "${e.name}"`);u.add(e.name),c.set(e.name,e)}if(t.builtinResources&&!t.buildbase)throw new Error("builtinResources requires a `buildbase` client — pass one to createMcpHandler.");const l=new Map,p=[];t.builtinResources&&(l.set("buildbase://profile",{uri:"buildbase://profile",name:"profile",title:"Your profile",description:"The authenticated user's BuildBase profile.",mimeType:"application/json",read:e=>e.bb.users.getProfile()}),l.set("buildbase://workspaces",{uri:"buildbase://workspaces",name:"workspaces",title:"Your workspaces",description:"The authenticated user's workspaces (id, name, roles).",mimeType:"application/json",read:e=>e.bb.workspace.list()}),p.push({uriTemplate:"buildbase://workspace/{workspaceId}",name:"workspace",title:"One workspace",description:"A single workspace: name, members, feature flags, quota snapshot.",mimeType:"application/json",read:(e,t,r)=>r.bb.workspace.get(e.workspaceId)}));for(const e of t.resources??[])l.set(e.uri,e);p.push(...t.resourceTemplates??[]);const h=new Map;for(const e of t.prompts??[]){if(!J.test(e.name))throw new Error(`Invalid MCP prompt name: "${e.name}" (want ${String(J)})`);if(h.has(e.name))throw new Error(`Duplicate MCP prompt name: "${e.name}"`);h.set(e.name,e)}const g=l.size>0||p.length>0,m=h.size>0,w=(e,t)=>{const r=new Set(t?.scopes??[]);return(e??[]).every(e=>r.has(e))};function y(e,r){const n=e?.sessionId??"";return{bb:t.buildbase?n?t.buildbase.withSession(n):v:S,auth:e??{sessionId:""},workspaceId:e?.workspaceId,custom:r}}function b(e,t){const r=[],n=e.replace(/[.*+?^$()|[\]\\]/g,e=>"\\"+e).replace(/\{([a-zA-Z0-9_]+)\}/g,(e,t)=>(r.push(t),"([^/]+)")),s=new RegExp(`^${n}$`).exec(t);if(!s)return null;const o={};return r.forEach((e,t)=>{try{o[e]=decodeURIComponent(s[t+1])}catch{o[e]=s[t+1]}}),o}function k(e,t,r){if("string"==typeof r)return{uri:e,mimeType:t??"text/plain",text:r};if(r&&"object"==typeof r){const n=r;if("string"==typeof n.text)return{uri:e,mimeType:"string"==typeof n.mimeType?n.mimeType:t??"text/plain",text:n.text};if("string"==typeof n.blob)return{uri:e,mimeType:"string"==typeof n.mimeType?n.mimeType:t??"application/octet-stream",blob:n.blob}}return{uri:e,mimeType:t??"application/json",text:JSON.stringify(r,null,2)}}const S=new Proxy({},{get(e,t){if("string"==typeof t)throw new Error(`No \`buildbase\` client configured — pass one to createMcpHandler to use bb.${t} in tools.`)}}),v=new Proxy({},{get(e,t){if("string"==typeof t)throw new Error(`This tool needs an authenticated BuildBase session, but the token carried none (bb.${t}). Re-authenticate.`)}}),I=new Map;function T(t){const r=I.get(t.name);if(r)return r;let n;try{n=K(t.inputSchema)?e.toJSONSchema(t.inputSchema,{target:"draft-2020-12"}):t.inputSchema}catch(e){P(e,{method:"tools/list",tool:t.name}),n={type:"object",additionalProperties:!0}}return I.set(t.name,n),n}function x(e){const t=new Set(e?.scopes??[]);return Array.from(c.values()).filter(e=>(e.requiredScopes??[]).every(e=>t.has(e)))}function P(e,r){try{t.onError?.(e instanceof Error?e:new Error(z(e)),r)}catch{}}function $(){if(t.auth&&t.auth.resourceMetadataUrl){const e=f({resourceMetadataUrl:t.auth.resourceMetadataUrl});return{status:e.status,headers:e.headers,body:e.body}}return H(401,{error:"unauthorized"})}const C=Array.isArray(t.cors)?new Set(t.cors.map(n)):null;async function A(e){const i=function(e){if(!1===t.cors)return{};const r=L(e.headers,"origin");let i;return i=C?r&&C.has(n(r))?r:null:s?o(r)?r:null:"*",i?{"Access-Control-Allow-Origin":i,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Protocol-Version, Mcp-Session-Id, Last-Event-ID","Access-Control-Expose-Headers":"MCP-Protocol-Version, Mcp-Session-Id, WWW-Authenticate","Access-Control-Max-Age":"86400",..."*"!==i?{Vary:"Origin"}:{}}:{}}(e);if("OPTIONS"===e.method.toUpperCase())return{status:204,headers:i,body:""};const c=await async function(e){const n=e.method.toUpperCase();if(s){const t=L(e.headers,"origin");if(t&&!o(t))return H(403,{error:"origin_not_allowed"})}if("POST"!==n)return{status:405,headers:{"Content-Type":j,Allow:"POST, OPTIONS"},body:JSON.stringify({error:"method_not_allowed"})};if(a>0&&"string"==typeof e.body&&e.body.length>a)return H(413,{error:"payload_too_large"});let i=null;if(!1!==t.auth){const r=d(L(e.headers,"authorization"));if(!r)return $();try{i=await t.auth.verify(r,e)}catch(e){P(e,{method:"auth"}),i=null}if(!i)return $()}if(t.rateLimit){let r;try{r=await t.rateLimit(i,e)}catch(e){P(e,{method:"rateLimit"}),r=!1}if(!("boolean"==typeof r?r:r.ok)){const e="object"==typeof r?r.retryAfter:void 0;return{status:429,headers:{"Content-Type":j,...void 0!==e?{"Retry-After":String(e)}:{}},body:JSON.stringify({error:"rate_limited"})}}}let c=e.body;if("string"==typeof e.body)try{c=JSON.parse(e.body)}catch{return G(null,N,"Invalid JSON",400)}if(Array.isArray(c))return G(null,F,"Batch requests are not supported",400);if("object"!=typeof c||null===c)return G(null,F,"Expected a JSON-RPC request object",400);const u=c,f=u.id,S="string"==typeof u.method?u.method:null;if(!S)return G(f,F,"Missing method",400);if(null==f)return{status:202,headers:{"Content-Type":j},body:""};const v=u.params??{};switch(S){case"initialize":{const e=v.protocolVersion;return D(f,{protocolVersion:"string"==typeof e&&O.includes(e)?e:R,capabilities:{tools:{listChanged:!1},...g?{resources:{}}:{},...m?{prompts:{}}:{}},serverInfo:r,...t.instructions?{instructions:t.instructions}:{}})}case"ping":return D(f,{});case"tools/list":return D(f,{tools:x(i).map(e=>({name:e.name,description:e.description,inputSchema:T(e),...e.annotations?{annotations:e.annotations}:{},...e.icons?{icons:e.icons}:{}}))});case"tools/call":{const r="string"==typeof v.name?v.name:"",n=x(i).find(e=>e.name===r);if(!n)return G(f,q,`Unknown tool: ${r||"(missing name)"}`);let s,o=v.arguments??{};if(K(n.inputSchema)){const e=n.inputSchema.safeParse(o);if(!e.success){const t=e.error.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ");return D(f,{content:[{type:"text",text:`Invalid arguments for ${r}: ${t}`}],isError:!0})}o=e.data}if(t.context)try{s=await t.context(i,e)}catch(e){return P(e,{method:S,tool:r}),G(f,B,"Context initialization failed")}const a=y(i,s);try{const e=await n.execute(o,a);if("object"==typeof(E=e)&&null!==E&&Array.isArray(E.content)&&E.content.length>0&&E.content.every(U))return D(f,{content:e.content,...void 0!==e.structuredContent?{structuredContent:e.structuredContent}:{},isError:e.isError??!1});const t="object"==typeof e&&null!==e&&!Array.isArray(e);return D(f,{content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e,null,2)}],...t?{structuredContent:e}:{},isError:!1})}catch(e){P(e,{method:S,tool:r});const n=e instanceof Error?e:new Error(z(e));return D(f,{content:[{type:"text",text:t.formatToolError?t.formatToolError(n,{tool:r}):n.message}],isError:!0})}}case"resources/list":if(!g)break;return D(f,{resources:Array.from(l.values()).filter(e=>w(e.requiredScopes,i)).map(e=>({uri:e.uri,name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.mimeType?{mimeType:e.mimeType}:{},...e.icons?{icons:e.icons}:{}}))});case"resources/templates/list":if(!g)break;return D(f,{resourceTemplates:p.filter(e=>w(e.requiredScopes,i)).map(e=>({uriTemplate:e.uriTemplate,name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.mimeType?{mimeType:e.mimeType}:{},...e.icons?{icons:e.icons}:{}}))});case"resources/read":{if(!g)break;if("string"!=typeof v.uri||""===v.uri)return G(f,q,"Missing required parameter: uri");const r=v.uri;let n,s=null;const o=l.get(r);if(o){if(!w(o.requiredScopes,i))return G(f,W,"Resource not found",200,{uri:r});n=o.mimeType,s=async e=>o.read(e)}else for(const e of p){if(!w(e.requiredScopes,i))continue;const t=b(e.uriTemplate,r);if(t){n=e.mimeType,s=async n=>e.read(t,r,n);break}}if(!s)return G(f,W,"Resource not found",200,{uri:r});let a;if(t.context)try{a=await t.context(i,e)}catch(e){return P(e,{method:S}),G(f,B,"Context initialization failed")}try{const e=await s(y(i,a));return D(f,{contents:[k(r,n,e)]})}catch(e){return P(e,{method:S}),G(f,B,"Resource read failed",200,{uri:r})}}case"prompts/list":if(!m)break;return D(f,{prompts:Array.from(h.values()).filter(e=>w(e.requiredScopes,i)).map(e=>({name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.arguments?{arguments:e.arguments}:{},...e.icons?{icons:e.icons}:{}}))});case"prompts/get":{if(!m)break;const r="string"==typeof v.name?v.name:"",n=h.get(r);if(!n||!w(n.requiredScopes,i))return G(f,q,`Unknown prompt: ${r||"(missing name)"}`);const s="object"==typeof v.arguments&&null!==v.arguments?v.arguments:{},o={};for(const[e,t]of Object.entries(s))"string"==typeof t&&(o[e]=t);const a=(n.arguments??[]).filter(e=>e.required&&!(e.name in o)).map(e=>e.name);if(a.length)return G(f,q,`Missing required arguments: ${a.join(", ")}`);let c;if(t.context)try{c=await t.context(i,e)}catch(e){return P(e,{method:S}),G(f,B,"Context initialization failed")}try{const e=await n.get(o,y(i,c)),t="string"==typeof e?{messages:[{role:"user",content:_(e)}]}:Array.isArray(e)?{messages:e}:e,r=t.description??n.description;return D(f,{...r?{description:r}:{},messages:t.messages})}catch(e){return P(e,{method:S}),G(f,B,"Prompt rendering failed")}}}var E;return G(f,M,`Method not found: ${S}`)}(e);return Object.keys(i).length?{...c,headers:{...c.headers,...i}}:c}return{handle:A,fetch:async function(e){const t={};if(e.headers.forEach((e,r)=>{t[r]=e}),a>0){const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>a)return new Response(JSON.stringify({error:"payload_too_large"}),{status:413,headers:{"Content-Type":j}})}const r="POST"===e.method.toUpperCase()?await e.text():void 0,n=await A({method:e.method,headers:t,body:r});return new Response(""===n.body?null:n.body,{status:n.status,headers:n.headers})},listTools:()=>Array.from(c.values()).map(e=>({name:e.name,description:e.description,...e.annotations?{annotations:e.annotations}:{}})),serverCard:e=>({name:r.name,version:r.version,endpoint:e.endpoint,transport:"streamable-http",capabilities:{tools:{listChanged:!1},...g?{resources:{}}:{},...m?{prompts:{}}:{}},...e.description?{description:e.description}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{}})}}function Q(e){return e}const Y=12,Z=16;function X(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("WebCrypto is unavailable in this runtime — agent-auth session encryption requires globalThis.crypto.subtle (Node 18+, Bun, Deno, edge, browsers).");return e.subtle}const ee=new Map;function te(e){let t=ee.get(e);return t||(t=(async()=>{const t=await X().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return X().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),ee.set(e,t)),t}function re(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(r){const n=globalThis.crypto.getRandomValues(new Uint8Array(Y)),s=await te(e),o=new Uint8Array(await X().encrypt({name:"AES-GCM",iv:n},s,(new TextEncoder).encode(r))),i=o.subarray(o.length-Z),a=o.subarray(0,o.length-Z),c=new Uint8Array(28+a.length);return c.set(n,0),c.set(i,Y),c.set(a,28),t(c)},async decryptSessionRef(t){try{const n=r(t);if(n.length<=28)return null;const s=n.slice(0,Y),o=n.subarray(Y,28),i=n.subarray(28),a=new Uint8Array(i.length+Z);a.set(i,0),a.set(o,i.length);const c=await te(e),u=await X().decrypt({name:"AES-GCM",iv:s},c,a);return(new TextDecoder).decode(u)}catch{return null}}}}async function ne(e){const{claims:t,secret:r}=e,n=e.expiresInSec??3600,s=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,o=t.sessionId?await re(r).encryptSessionRef(t.sessionId):void 0;return{token:g({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...o?{sid:o}:{},...e.extraClaims},r,{expiresInSec:n}),expiresIn:n}}function se(e,t,r){const n=globalThis.process?.env;"1"===n?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${r}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function oe(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const r=re(t),n=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let s=e.resourceMetadataUrl;if(!s&&n.length)try{const e=new URL(n[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");s=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:s,verify:async s=>{let o;try{o=p(s,t,{...e.verify})}catch{return null}if(n.length){const t=o.aud?Array.isArray(o.aud)?o.aud:[o.aud]:[];if(!t.length&&e.requireAudience)return se(t,n,"token carries no aud claim"),null;if(t.length&&!t.some(e=>n.includes(e)))return se(t,n,"aud does not include this resource"),null}const i="string"==typeof o.sid?await r.decryptSessionRef(o.sid):null,a=Array.isArray(o.scope)?o.scope.filter(e=>"string"==typeof e):"string"==typeof o.scope?o.scope.split(" ").filter(Boolean):void 0;return{sessionId:i??"",userId:"string"==typeof o.userId?o.userId:"string"==typeof o.sub?o.sub:void 0,workspaceId:"string"==typeof o.workspaceId?o.workspaceId:void 0,scopes:a,claims:o}}}}const ie=300,ae="/.well-known/oauth-protected-resource",ce="/.well-known/agent-skills",ue="/.well-known/api-catalog",le="/.well-known/mcp/server-card.json",pe="/.well-known/agent-card.json",de="application/json",he="application/linkset+json",ge="text/markdown; charset=utf-8",me="text/plain; charset=utf-8",fe="application/xml; charset=utf-8",we=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ye(e){return e.replace(/\/+$/,"")}function be(e){return`public, max-age=${e}, s-maxage=${e}`}function ke(e){return"sha256:"+function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(o(i(e)))}const Se=new Map;async function ve(e,t,r,n){if(!n||n<=0)return e(t,r);const s=new AbortController,o=setTimeout(()=>s.abort(),n);try{return await e(t,{...r,signal:s.signal})}finally{clearTimeout(o)}}async function Ee(e){const t=e.cacheTtlSeconds??ie,r=`${ye(e.serverUrl)}::${e.orgId}`,n=Se.get(r);if(n&&n.expiresAt>Date.now())return n.value;const s=e.fetch??fetch,o=`${ye(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const t=await ve(s,o,{headers:{Accept:de}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(i=e)}}catch{}return Se.set(r,{value:i,expiresAt:Date.now()+1e3*t}),i}const _e=new Map;function Ie(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const r="/"===t?"":t.replace(/\/+$/,"");return ae+r}function Te(e){return e.path??`${ce}/${e.name}/SKILL.md`}function xe(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:me,body:t.join("\n")+"\n",cacheControl:be(e.cacheTtlSeconds??ie)}}function Pe(e){return e.endsWith(".json")||e.includes(".well-known/")?de:e.endsWith(".md")?ge:e.endsWith(".xml")?fe:me}function Ue(e){const t=e??{tools:!0},r={tools:!1,resources:!1,prompts:!1};for(const[e,n]of Object.entries(t))r[e]=!1!==n&&null!=n;return r}function $e(e,t){return{status:200,contentType:de,body:JSON.stringify(e,null,2),cacheControl:be(t.cacheTtlSeconds??ie)}}function Ce(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Ae(e,t){const r=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Ce(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&r.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])r.push(`Allow: ${Ce(t)}`);for(const t of e.disallow??[])r.push(`Disallow: ${Ce(t)}`);return void 0!==e.crawlDelay&&r.push(`Crawl-delay: ${Ce(e.crawlDelay)}`),r.join("\n")}function Oe(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function Re(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function je(e){const t=ye(e.siteUrl),r=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&r.push(`<${t}${pe}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const n=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;r.push(`<${n}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&r.push(`<${t}${ue}>; rel="api-catalog"; type="${he}"`),e.mcpServerCard&&r.push(`<${t}${le}>; rel="mcp-server"; type="application/json"`),r.join(", ")}async function Je(e,t){const r=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===r){return function(e,t){const r=ye(e.siteUrl),n={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:ae};return t.authorizationServer?.metadataUrl&&(n.oauth_authorization_server=t.authorizationServer.metadataUrl,n.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(n.auth="/auth.md"),e.skills?.length&&(n.agent_skills=`${ce}/index.json`),e.apiCatalog?.length&&(n.api_catalog=ue),e.mcpServerCard&&(n.mcp_server_card=le),!1!==e.a2aCard&&(n.a2a_agent_card=pe),e.llmsFullTxt&&(n.llms_full_txt="/llms-full.txt"),$e({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:r,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:r},capabilities:n,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}(t,await Ee(t))}if(r===pe)return function(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},r=ye(e.siteUrl),n=t.serviceUrl??r,s=t.transportProtocol??"http",o=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return $e({protocolVersion:"0.3.0",name:t.name??e.site.name,version:t.version??"1.0.0",description:t.description??e.site.description??`${e.site.name} — agent-accessible web application.`,url:n,preferredTransport:s,supportedInterfaces:[{serviceUrl:n,transportProtocol:s}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:r},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:o,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}(t);if("/.well-known/http-message-signatures-directory"===r)return function(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:be(e.cacheTtlSeconds??ie)}:null}(t);if("/.well-known/security.txt"===r)return xe(t);if(r===`${ce}/index.json`)return function(e){const t=e.skills??[];if(!t.length)return null;const r=ye(e.siteUrl);return $e({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${r}${Te(e)}`,digest:ke(e.content)}))},e)}(t);if(r.startsWith(`${ce}/`)&&r.endsWith("SKILL.md"))return function(e,t){const r=(t.skills??[]).find(t=>Te(t)===e);return r?{status:200,contentType:"text/markdown; charset=utf-8",body:r.content,cacheControl:be(t.cacheTtlSeconds??ie)}:null}(r,t);if("/.well-known/oauth-authorization-server"===r||"/.well-known/openid-configuration"===r){const e=(await Ee(t)).authorizationServer;if(!e?.metadataUrl)return null;const r=await async function(e,t){const r=t.cacheTtlSeconds??ie,n=_e.get(e);if(n&&n.expiresAt>Date.now())return n.value;const s=t.fetch??fetch;let o=null;try{const r=await ve(s,e,{headers:{Accept:de}},t.fetchTimeoutMs??5e3);if(r.ok){const e=await r.json();e&&"object"==typeof e&&(o=e)}}catch{}return _e.set(e,{value:o,expiresAt:Date.now()+1e3*r}),o}(e.metadataUrl,t);return $e(r?r:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(r===ue)return function(e){const t=e.apiCatalog??[];if(!t.length)return null;const r=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:he,body:JSON.stringify({linkset:r},null,2),cacheControl:be(e.cacheTtlSeconds??ie)}}(t);if(r===le)return function(e){const t=e.mcpServerCard;return t?$e({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-11-25",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:Ue(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}(t);if("/.well-known/mcp.json"===r)return function(e){const t=e.mcpServerCard;if(!t)return null;const r=ye(e.siteUrl);let n;try{n={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${Ie(t.endpoint)}`}}catch{}return $e({$schema:"https://modelcontextprotocol.io/schemas/mcp-discovery/v1.0",version:"1.0",servers:[{name:t.name,...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},version:t.version,capabilities:Ue(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${r}${le}`,...n?{authentication:n}:{}}]},e)}(t);if(r.startsWith(ae)){const e=await Ee(t);return function(e,t,r){const n=t.protectedResources??[];if(!n.length)return null;const s=e.replace(/\/+$/,"")||ae,o=r??`${ye(t.serverUrl)}/org/${t.orgId}`,i=t.scopes?.map(e=>e.name),a=n.map(e=>{const r=e.resource??ye(t.siteUrl),n=e.scopes??i;return{path:Ie(r),metadata:{resource:r,authorization_servers:[o],bearer_methods_supported:e.bearerMethods??["header"],...n?.length?{scopes_supported:n}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=a.find(e=>e.path===s);return c?$e(c.metadata,t):s===ae&&1===a.length?$e(a[0].metadata,t):null}(r,t,e.authorizationServer?.issuer)}return null}async function We(e,t){const r=e.replace(/\/+$/,"")||e,n=function(e,t){const r=t.extraPaths?.[e];if(void 0===r)return null;const n="string"==typeof r?{body:r}:r;return{status:n.status??200,contentType:n.contentType??Pe(e),body:n.body,cacheControl:n.cacheControl??be(t.cacheTtlSeconds??ie)}}(r,t);return n||("/robots.txt"===r?function(e){const t=e.robots??{},r=ye(e.siteUrl),n=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",o="allow"===s?[{userAgent:[...we],allow:["/"]}]:"deny"===s?[{userAgent:[...we],disallow:["/"]}]:s,i=t.sitemaps??(e.sitemap?[`${r}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${r}/llms.txt and ${r}/.well-known/agent.json`,...n.map((e,r)=>Ae(e,0===r?t.contentSignals:void 0)),...o.map(e=>Ae(e)),...i.length?[i.map(e=>`Sitemap: ${Ce(e)}`).join("\n")]:[]];return{status:200,contentType:me,body:a.join("\n\n")+"\n",cacheControl:be(e.cacheTtlSeconds??ie)}}(t):"/llms-full.txt"===r?function(e){return e.llmsFullTxt?{status:200,contentType:me,body:e.llmsFullTxt,cacheControl:be(e.cacheTtlSeconds??ie)}:null}(t):"/sitemap.xml"===r?function(e){const t=e.sitemap?.urls;if(!t?.length)return null;const r=ye(e.siteUrl),n='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+t.map(e=>{const t="string"==typeof e?{loc:e}:e;return` <url>\n${[` <loc>${Re(/^https?:\/\//.test(t.loc)?t.loc:`${r}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${Re(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${Re(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Oe(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:fe,body:n,cacheControl:be(e.cacheTtlSeconds??ie)}}(t):"/llms.txt"===r?function(e){return e.llmsTxt?{status:200,contentType:me,body:e.llmsTxt,cacheControl:be(e.cacheTtlSeconds??ie)}:null}(t):"/auth.md"===r?function(e,t){const r=be(e.cacheTtlSeconds??ie);if(e.authMd)return{status:200,contentType:ge,body:e.authMd,cacheControl:r};const n=t.authorizationServer;if(!n)return null;const s=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${n.issuer}\`\n- Metadata (RFC 8414): ${n.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, supported grant types / PKCE methods, and — when the app allows it — the dynamic client \`registration_endpoint\` (RFC 7591).\n\n## Protected resources (RFC 9728)\nSee \`/.well-known/oauth-protected-resource\`, which lists the resource, its supported scopes, and the authorization server(s) that can issue tokens for it.\n\n## How an agent authenticates\n1. Discover this document and \`/.well-known/oauth-protected-resource\`.\n2. Fetch the authorization-server metadata for the endpoints.\n3. Register a client (dynamic registration) or use a pre-issued client_id.\n4. Run the authorization-code flow with PKCE (S256), requesting the scopes and target \`resource\`.\n5. Exchange the code for an access token and call the API with \`Authorization: Bearer <token>\`.\n\nDocumentation: ${e.site.documentationUrl??e.siteUrl}\n`;return{status:200,contentType:ge,body:s,cacheControl:r}}(t,await Ee(t)):"/security.txt"===r?xe(t):r.startsWith("/.well-known")?Je(r,t):null)}let Ne=!0;function Fe(e,...t){Ne&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}async function Me(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function qe(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await Me(e);r=t.message||t.error||r}catch{r=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(r)}try{return await Me(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class Be extends Error{constructor(e,t,r,n){super(e),this.code=t,this.context=r,this.originalError=n,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,Be)}}const Le=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(Ne=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new Be("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),n=r instanceof Be?r:new Be(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&Fe(`[SDK Error] ${t.component||"Unknown"}:`,{message:n.message,code:n.code,context:n.context,originalError:n.originalError,stack:n.stack}),this.config.onError)try{this.config.onError(n,t)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(n,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function He(e,t={}){Le.handleError(e,t)}function De(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return He(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}const Ge="saas-session-id",Ke="saas-device-id";function ze(){return function(){if("undefined"==typeof window)return null;try{return De(Ge)}catch(e){return He(e,{component:"auth-utils",action:"getSessionId",metadata:{key:Ge}}),null}}()}function Ve(){const e=ze(),t={};e&&(t["x-session-id"]=e);const r=function(){if("undefined"==typeof window)return null;try{return De(Ke)??null}catch(e){return He(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:Ke}}),null}}();return r&&(t["x-device-id"]=r),t}const Qe=new WeakSet,Ye=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ze="SDK is not ready (missing serverUrl, version, or orgId)";class Xe{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(Ze);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(Ze)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:Ve()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){Qe.has(e)||(Qe.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((r,n)=>{const s=()=>{clearTimeout(o),n(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const o=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,r){const n=(t.method??"GET").toUpperCase(),s=r??e,o=this.buildHeaders(t),i={...t,headers:o},a=Ye.has(n);let c,u;if(this._timeout>0){u=new AbortController;const e=u;c=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const n=new AbortController,s=e=>{n.signal.aborted||n.abort(e.reason)};for(const r of[e,t]){if(r.aborted){s(r);break}r.addEventListener("abort",()=>s(r),{once:!0})}return n.signal}(t.signal,e.signal):e.signal}const l=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${n} ${s}`);return this.reportError(e,{method:n,path:s}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const r=this._fetch.bind(globalThis),s=await r(e,i);if(this._debug&&console.log(`[BuildBase] ${n} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await Xe.delay(e,i.signal),p(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await Xe.delay(e,i.signal)}catch(e){throw l(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:n,path:s}),e}};try{return await p(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await qe(n,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},r="Request failed"){const n=await this.fetchResponse(e,t);return n.ok||await this.throwResponseError(n,r),this.unwrapResponse(n,r)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw new Error(r)}apiPath(e,...t){return e.reduce((e,r,n)=>e+r+(n<t.length?encodeURIComponent(String(t[n])):""),"")}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return void 0!==r.data?r.data:r}return r}}class et extends Xe{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,r){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}class tt extends Xe{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class rt extends Xe{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class nt extends Xe{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class st extends Xe{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class ot extends Xe{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}async updateWorkspace(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:r},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to invite member")}async removeUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:r},"Failed to remove user")}async updateUser(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r),signal:n},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:r},"Failed to update workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}}),signal:n},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,r){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:r},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create checkout session")}async selectFreePlan(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:r},"Failed to select free plan")}async updateSubscription(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:r},"Failed to update subscription")}async createBillingPortalSession(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:r})}async listInvoices(e,t=10,r,n){const s=new URLSearchParams;return s.append("limit",t.toString()),r&&s.append("starting_after",r),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:n},"Failed to fetch invoices")}async getInvoice(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:r},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record usage")}async recordUsageBatch(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:r},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,r){const n=new URLSearchParams;t?.quotaSlug&&n.append("quotaSlug",t.quotaSlug),t?.from&&n.append("from",t.from),t?.to&&n.append("to",t.to),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),o=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch usage logs")}async sendNotification(e,t,r,n,s){const o={event:t};return r&&(o.userId=r),n&&(o.data=n),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(o),signal:s},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,r){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:r},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,r){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:r});if(!n.ok){if(402===n.status){const e=await n.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(n,"Failed to consume credits")}return this.unwrapResponse(n,"Failed to consume credits")}async purchaseCredits(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const r=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t,r){const n=new URLSearchParams;t?.type&&n.append("type",t.type),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),o=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,r){const n=new URLSearchParams;t?.status&&n.append("status",t.status),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),o=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,r){const n=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+n,{signal:r},"Failed to fetch expiring credits")}}const it={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view"},at=Object.values(it),ct={admin:at.filter(e=>e!==it.WORKSPACE_DELETE),member:[it.WORKSPACE_SETTINGS_VIEW,it.WORKSPACE_MEMBERS_VIEW,it.WORKSPACE_FEATURES_VIEW,it.WORKSPACE_BILLING_VIEW,it.WORKSPACE_USAGE_VIEW],viewer:[it.WORKSPACE_SETTINGS_VIEW,it.WORKSPACE_MEMBERS_VIEW]};function ut(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function lt(e){const{userId:t,workspace:r,settings:n,appPermissions:s}=e;if(!r||!t)return new Set;if(function(e,t){if(!t)return!1;const r=(n=e.createdBy)?"string"==typeof n?n:"object"==typeof n&&"_id"in n&&"string"==typeof n._id?n._id:null:null;var n;return null!==r&&r===t}(r,t)){const e=new Set(at);if(s)for(const t of ut(s))e.add(t);if(r.permissions)for(const t of ut(r.permissions))e.add(t);if(n?.workspace?.permissions)for(const t of ut(n.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}(r,t);if(!o)return new Set;const i=r.permissions,a=n?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!i&&o in i,p=!!a&&o in a,d=o in ct;let h;if(l)h=c(i[o]);else if(p)h=c(a[o]);else if(d)h=ct[o];else{const e=n?.workspace?.defaultRole;h=e&&e in ct?ct[e]:[]}const g=new Set(h),m=l?u(i[o]):[],f=s?.[o]?u(s[o]):[],w=l?m:f;for(const e of w)g.add(e);return function(e,t,r){if(!r?.workspace)return;const{canInviteMembers:n}=r.workspace;(!1===n||"admin-only"===n&&"admin"!==t)&&e.delete(it.WORKSPACE_MEMBERS_INVITE)}(g,o,n),g}function pt(e){const{serverUrl:t,orgId:r,version:n="v1",getSessionId:s,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!r)throw new Error("BuildBase: orgId is required");const p={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},d=e=>{const s={serverUrl:t,version:n,orgId:r,sessionId:e,...p};return{workspace:new ot(s),user:new st(s),settings:new nt(s),push:new tt(s),devices:new et(s),sessions:new rt(s)}},h=new ot({serverUrl:t,version:n,orgId:r,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,r)=>(await e()).workspace.updateWorkspace(t,r),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,r,n)=>(await e()).workspace.addUser(t,{email:r,role:n}),remove:async(t,r)=>(await e()).workspace.removeUser(t,r),updateRole:async(t,r,n)=>(await e()).workspace.updateUser(t,r,{role:n}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,r)=>(await e()).workspace.createCheckoutSession(t,r),update:async(t,r)=>(await e()).workspace.updateSubscription(t,r),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,r)=>(await e()).workspace.createBillingPortalSession(t,r)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,r,n)=>(await e()).workspace.listInvoices(t,r,n),get:async(t,r)=>(await e()).workspace.getInvoice(t,r)},usage:{record:async(t,r)=>(await e()).workspace.recordUsage(t,r),recordBatch:async(t,r)=>(await e()).workspace.recordUsageBatch(t,r),getQuota:async(t,r)=>(await e()).workspace.getQuotaUsageStatus(t,r),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,r)=>(await e()).workspace.getUsageLogs(t,r)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,r,n)=>(await e()).workspace.updateFeature(t,r,n)},notification:{send:async(t,r,n,s)=>(await e()).workspace.sendNotification(t,r,n,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,r)=>(await e()).workspace.consumeCredits(t,r),purchase:async(t,r)=>(await e()).workspace.purchaseCredits(t,r),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,r)=>(await e()).workspace.getCreditTransactions(t,r),getBuckets:async(t,r)=>(await e()).workspace.getCreditBuckets(t,r),getExpiring:async(t,r)=>(await e()).workspace.getExpiringCredits(t,r),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,r,n)=>{const s=await e(),[o,i,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return function(e,t){const r=lt(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)}(n,{userId:r,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,r)=>{const n=await e(),[s,o,i]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return lt({userId:r,workspaceRole:a?.role??null,workspace:s,settings:o})}},devices:{list:async()=>(await e()).devices.list(),rename:async(t,r)=>(await e()).devices.rename(t,r),signOut:async t=>(await e()).devices.signOut(t),forget:async t=>(await e()).devices.forget(t)},sessions:{list:async()=>(await e()).sessions.list(),revoke:async t=>(await e()).sessions.revoke(t)}}),m=g(async()=>d(await(async()=>{if(!s)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await s();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!s)return null;const e=await s();return e?{sessionId:e}:null},withSession:e=>{const t=d(e);return g(async()=>t)},client:{forSession:d},...m}}function dt(e){const t=ye(e.siteUrl),r=e.mcp?.path??"/api/mcp",n=`${t}${r.startsWith("/")?r:`/${r}`}`,s=e.mcp?.serverInfo??{name:e.site.name,version:"1.0.0"},o=`${t}/mcp`,i=Array.from(new Set([o,n])),a=e.mcp?.auth??(e.secret?oe({secret:e.secret,resource:i,resourceMetadataUrl:`${t}/.well-known/oauth-protected-resource/mcp`,requireAudience:!0}):void 0);if(void 0===a)throw new Error("createAgentStack: pass `secret` (the app token-signing secret) to derive auth, or set `mcp.auth` yourself (`false` disables auth — local development only).");const c=V({buildbase:e.mcp?.buildbase??pt({serverUrl:e.serverUrl,orgId:e.orgId}),serverInfo:s,auth:a,tools:e.mcp?.tools,builtinTools:e.mcp?.builtinTools??"readonly",...e.mcp?.handler}),u={serverUrl:e.serverUrl,orgId:e.orgId,siteUrl:e.siteUrl,site:e.site,mcpServerCard:c.serverCard({endpoint:n,...e.site.description?{description:e.site.description}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}),...e.scopes?{scopes:e.scopes}:{},protectedResources:i.map(t=>({resource:t,...e.mcp?.scopes?.length?{scopes:e.mcp.scopes}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}})).concat([{resource:t,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}]),apiCatalog:[{anchor:n,title:`${e.site.name} MCP server`,serviceDesc:`${t}/.well-known/mcp/server-card.json`}],...e.discovery},l={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, OPTIONS"};const p=e=>c.fetch(e);return{mcp:c,mcpEndpoint:n,config:u,linkHeader:je(u),resolvePath:e=>We(e,u),serveAgentPath:async function(e){if("OPTIONS"===e.method.toUpperCase())return new Response(null,{status:204,headers:l});const t=await We(new URL(e.url).pathname,u);return t?new Response(t.body,{status:t.status,headers:{"Content-Type":t.contentType,"Cache-Control":t.cacheControl,...t.vary?{Vary:t.vary}:{},...l}}):new Response(JSON.stringify({error:"not_found"}),{status:404,headers:{"Content-Type":"application/json",...l}})},routes:{GET:p,POST:p,DELETE:p,OPTIONS:p}}}export{u as AppBridgeError,f as bearerChallenge,oe as buildbaseAuth,v as builtinMcpTools,dt as createAgentStack,V as createMcpHandler,re as createSessionRefCrypto,A as defineMcpPrompt,$ as defineMcpResource,C as defineMcpResourceTemplate,Q as defineMcpTool,d as extractBearerToken,T as mcpAudio,P as mcpEmbeddedResource,I as mcpImage,x as mcpResourceLink,_ as mcpText,ne as mintAgentToken,E as selectBuiltinTools,g as signClientJwt,p as verifyClientJwt};
1
+ import{z as e}from"zod";function t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function r(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4==0?"":"=".repeat(4-t.length%4),n=atob(t+r),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return s}const n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),s=(e,t)=>e>>>t|e<<32-t;function o(e){let t=1779033703,r=3144134277,o=1013904242,i=2773480762,a=1359893119,c=2600822924,u=528734635,l=1541459225;const p=e.length,d=p+1,h=d+(56-d%64+64)%64+8,g=new Uint8Array(h);g.set(e,0),g[p]=128;const m=8*p,f=Math.floor(m/4294967296),w=m>>>0;g[h-8]=f>>>24&255,g[h-7]=f>>>16&255,g[h-6]=f>>>8&255,g[h-5]=255&f,g[h-4]=w>>>24&255,g[h-3]=w>>>16&255,g[h-2]=w>>>8&255,g[h-1]=255&w;const y=new Uint32Array(64);for(let e=0;e<h;e+=64){for(let t=0;t<16;t++){const r=e+4*t;y[t]=g[r]<<24|g[r+1]<<16|g[r+2]<<8|g[r+3]}for(let e=16;e<64;e++){const t=s(y[e-15],7)^s(y[e-15],18)^y[e-15]>>>3,r=s(y[e-2],17)^s(y[e-2],19)^y[e-2]>>>10;y[e]=y[e-16]+t+y[e-7]+r>>>0}let p=t,d=r,h=o,m=i,f=a,w=c,b=u,k=l;for(let e=0;e<64;e++){const t=k+(s(f,6)^s(f,11)^s(f,25))+(f&w^~f&b)+n[e]+y[e]>>>0,r=p&d^p&h^d&h;k=b,b=w,w=f,f=m+t>>>0,m=h,h=d,d=p,p=t+((s(p,2)^s(p,13)^s(p,22))+r>>>0)>>>0}t=t+p>>>0,r=r+d>>>0,o=o+h>>>0,i=i+m>>>0,a=a+f>>>0,c=c+w>>>0,u=u+b>>>0,l=l+k>>>0}const b=new Uint8Array(32),k=[t,r,o,i,a,c,u,l];for(let e=0;e<8;e++)b[4*e]=k[e]>>>24&255,b[4*e+1]=k[e]>>>16&255,b[4*e+2]=k[e]>>>8&255,b[4*e+3]=255&k[e];return b}function i(e){return(new TextEncoder).encode(e)}function a(e,t){let r=e;r.length>64&&(r=o(r));const n=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<r.length?r[e]:0;n[e]=54^t,s[e]=92^t}const i=o(c(n,t));return o(c(s,i))}function c(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}class u extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function l(e){const t=JSON.parse((new TextDecoder).decode(r(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function p(e,t,n={}){const s=n.clockToleranceSec??60,o=n.requireExp??!0;if(!e||!t)throw new u("invalid_token","Missing token or client secret");const c=e.split(".");if(3!==c.length)throw new u("invalid_token","Malformed JWT");const[p,d,h]=c;let g,m;try{g=l(p),m=l(d)}catch{throw new u("invalid_token","Unreadable JWT segments")}if("HS256"!==g.alg)throw new u("invalid_algorithm",`Unexpected JWT alg: ${String(g.alg)}`);const f=a(i(t),i(`${p}.${d}`));let w;try{w=r(h)}catch{throw new u("invalid_signature","Unreadable JWT signature")}if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(f,w))throw new u("invalid_signature","JWT signature verification failed");!function(e){for(const t of["iss","sub","jti"])if(void 0!==e[t]&&"string"!=typeof e[t])throw new u("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const r=e[t];if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)))throw new u("invalid_token",`JWT ${t} claim must be a finite number`)}const t=e.aud;if(!(void 0===t||"string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new u("invalid_token","JWT aud claim must be a string or string array")}(m);const y=Math.floor(Date.now()/1e3);if(o&&"number"!=typeof m.exp)throw new u("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof m.exp&&y>m.exp+s)throw new u("token_expired","JWT has expired");if("number"==typeof m.nbf&&y+s<m.nbf)throw new u("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&m.iss!==n.issuer)throw new u("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=m.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new u("invalid_audience","JWT audience mismatch")}return m}function d(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function h(e){return t(i(JSON.stringify(e)))}function g(e,r,n){if(!r)throw new u("invalid_secret","Missing signing secret");const s=Math.floor(Date.now()/1e3),o={iat:s,exp:s+(n?.expiresInSec??3600),...e},c=`${h({alg:"HS256",typ:"JWT"})}.${h(o)}`;return`${c}.${t(a(i(r),i(c)))}`}function m(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function f(e){const t=[`Bearer resource_metadata="${m(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${m(e.error)}"`),e.errorDescription&&t.push(`error_description="${m(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const w=e.string().optional().describe("Workspace id. Omit to use the workspace bound to your token.");function y(e,t){const r=e.workspaceId??t.workspaceId;if(!r)throw new Error("workspaceId is required — call list_workspaces to find one.");return r}const b={readOnlyHint:!0},k=[{name:"list_workspaces",description:"List the authenticated user's workspaces (id, name, roles).",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.workspace.list()},{name:"get_workspace",description:"Get one workspace: name, members, feature flags, quota snapshot.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.workspace.get(y(e,t))},{name:"get_user_profile",description:"Get the authenticated user's profile.",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.users.getProfile()},{name:"list_workspace_users",description:"List the members of a workspace with their roles.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.users.list(y(e,t))},{name:"get_subscription",description:"Get a workspace's subscription: plan, status, interval, seats.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.subscription.get(y(e,t))},{name:"get_plans",description:"Get the plan group available to a workspace (plans, prices, quotas).",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.plans.getGroup(y(e,t))},{name:"list_invoices",description:"List a workspace's invoices (newest first).",inputSchema:e.object({workspaceId:w,limit:e.number().int().min(1).max(100).optional().describe("Max invoices to return."),startingAfter:e.string().optional().describe("Invoice id to paginate after.")}),annotations:b,execute:(e,t)=>t.bb.invoices.list(y(e,t),e.limit,e.startingAfter)},{name:"get_quota_usage",description:"Get usage vs. limit for one quota in a workspace.",inputSchema:e.object({workspaceId:w,quotaSlug:e.string().describe('The quota slug, e.g. "api-calls".')}),annotations:b,execute:(e,t)=>t.bb.usage.getQuota(y(e,t),e.quotaSlug)},{name:"get_all_quota_usage",description:"Get usage vs. limit for every quota in a workspace.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.usage.getAll(y(e,t))},{name:"get_credit_balance",description:"Get a workspace's prepaid credit balance.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.credits.getBalance(y(e,t))},{name:"list_credit_transactions",description:"Get a workspace's credit transaction history (paginated).",inputSchema:e.object({workspaceId:w,limit:e.number().int().min(1).max(100).optional(),page:e.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getTransactions(y(e,t),{...void 0!==e.limit?{limit:e.limit}:{},...void 0!==e.page?{page:e.page}:{}})},{name:"check_feature_flag",description:"Check whether a feature flag is enabled for a workspace.",inputSchema:e.object({workspaceId:w,key:e.string().describe("The feature slug.")}),annotations:b,execute:async(e,t)=>{const r=y(e,t),n=await t.bb.workspace.get(r),s=n.features?.[e.key];if(void 0!==s)return{key:e.key,enabled:s,source:"workspace"};const o=(await t.bb.features.list()).find(t=>t.slug===e.key);if(!o)throw new Error(`Unknown feature flag: ${e.key}`);return{key:e.key,enabled:o.defaultValue,source:"default"}}},{name:"check_permission",description:"Check whether a user has permission(s) in a workspace.",inputSchema:e.object({workspaceId:w,permission:e.union([e.string(),e.array(e.string())]).describe("A permission (or list — all must hold), platform or app-defined."),userId:e.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const n=await t.bb.permissions.check(y(e,t),r,e.permission);return{userId:r,permission:e.permission,allowed:n}}},{name:"resolve_permissions",description:"List every permission a user holds in a workspace.",inputSchema:e.object({workspaceId:w,userId:e.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const n=await t.bb.permissions.resolve(y(e,t),r);return{userId:r,permissions:Array.from(n)}}},{name:"get_invoice",description:"Get one invoice by id.",inputSchema:e.object({workspaceId:w,invoiceId:e.string().describe("The invoice id.")}),annotations:b,execute:(e,t)=>t.bb.invoices.get(y(e,t),e.invoiceId)},{name:"get_plan_versions",description:"List the plan-group versions available to a workspace.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.plans.getVersions(y(e,t))},{name:"get_public_plans",description:"Get a public plan group by slug (no workspace / auth needed).",inputSchema:e.object({slug:e.string().describe("The plan-group slug.")}),annotations:b,execute:(e,t)=>t.bb.plans.getPublic(e.slug)},{name:"get_plan_version",description:"Get one public plan-group version by id (no auth needed).",inputSchema:e.object({groupVersionId:e.string().describe("The plan-group version id.")}),annotations:b,execute:(e,t)=>t.bb.plans.getVersion(e.groupVersionId)},{name:"get_usage_logs",description:"Get a workspace's usage log entries (paginated, filterable).",inputSchema:e.object({workspaceId:w,quotaSlug:e.string().optional(),from:e.string().optional().describe("ISO date lower bound."),to:e.string().optional().describe("ISO date upper bound."),source:e.string().optional(),page:e.number().int().min(1).optional(),limit:e.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.usage.getLogs(y(e,t),n)}},{name:"get_settings",description:"Get the organization settings.",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.settings.get()},{name:"get_credit_packages",description:"List the credit packages a workspace can purchase.",inputSchema:e.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.credits.getPackages(y(e,t))},{name:"get_credit_buckets",description:"Get a workspace's credit buckets (paginated).",inputSchema:e.object({workspaceId:w,status:e.string().optional(),source:e.string().optional(),page:e.number().int().min(1).optional(),limit:e.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.credits.getBuckets(y(e,t),n)}},{name:"get_expiring_credits",description:"Get credits expiring within N days (default 7).",inputSchema:e.object({workspaceId:w,days:e.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getExpiring(y(e,t),e.days)},{name:"get_public_credit_packages",description:"List credit packages publicly (no workspace / auth needed).",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.credits.getPublicPackages()}],S=[{name:"record_usage",description:"Record quota usage for a workspace (metered billing).",inputSchema:e.object({workspaceId:w,quotaSlug:e.string().describe("The quota slug to record against."),quantity:e.number().positive().describe("Amount of usage to record."),idempotencyKey:e.string().optional().describe("Dedupe key for safe retries."),metadata:e.record(e.string(),e.unknown()).optional()}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},execute:(e,t)=>t.bb.usage.record(y(e,t),{quotaSlug:e.quotaSlug,quantity:e.quantity,source:"mcp",...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{},...e.metadata?{metadata:e.metadata}:{}})},{name:"consume_credits",description:"Consume prepaid credits from a workspace's balance.",inputSchema:e.object({workspaceId:w,amount:e.number().positive().describe("Credits to consume."),description:e.string().optional().describe("What the credits were spent on."),idempotencyKey:e.string().optional().describe("Dedupe key for safe retries.")}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.credits.consume(y(e,t),{amount:e.amount,...e.description?{description:e.description}:{},...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{}})},{name:"send_notification",description:"Send a notification event to a workspace user (or all members when userId is omitted).",inputSchema:e.object({workspaceId:w,event:e.string().describe('The event slug, e.g. "comment_added".'),userId:e.string().optional().describe("Recipient. Omit to notify all members."),message:e.string().optional().describe("Message body (used for push).")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.notification.send(y(e,t),e.event,e.userId,e.message?{message:e.message}:void 0)},{name:"record_usage_batch",description:"Record multiple usage entries in one call (max 100 items).",inputSchema:e.object({workspaceId:w,items:e.array(e.object({quotaSlug:e.string(),quantity:e.number().positive(),idempotencyKey:e.string().optional(),metadata:e.record(e.string(),e.unknown()).optional()})).min(1).max(100)}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.usage.recordBatch(y(e,t),{items:e.items.map(e=>({...e,source:"mcp"}))})},{name:"create_workspace",description:"Create a new workspace.",inputSchema:e.object({name:e.string().describe("Workspace name."),image:e.string().optional().describe("Image URL.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.workspace.create({name:e.name,...e.image?{image:e.image}:{}})},{name:"update_workspace",description:"Update a workspace's editable fields (name, image).",inputSchema:e.object({workspaceId:w,name:e.string().min(1).optional().describe("New workspace name."),image:e.string().optional().describe("New image URL.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};return void 0!==e.name&&(r.name=e.name),void 0!==e.image&&(r.image=e.image),t.bb.workspace.update(y(e,t),r)}},{name:"delete_workspace",description:"Delete a workspace. Irreversible.",inputSchema:e.object({workspaceId:w}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.workspace.delete(y(e,t))},{name:"invite_workspace_user",description:"Invite a user to a workspace with a role.",inputSchema:e.object({workspaceId:w,email:e.string().describe("Invitee email."),role:e.string().describe("Role to grant.")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.users.invite(y(e,t),e.email,e.role)},{name:"remove_workspace_user",description:"Remove a user from a workspace. Irreversible.",inputSchema:e.object({workspaceId:w,userId:e.string().describe("The user to remove.")}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.users.remove(y(e,t),e.userId)},{name:"update_workspace_user_role",description:"Change a workspace member's role.",inputSchema:e.object({workspaceId:w,userId:e.string(),role:e.string().describe("The new role.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.users.updateRole(y(e,t),e.userId,e.role)},{name:"update_user_profile",description:"Update the authenticated user's own profile (name, image, country, timezone, language, currency).",inputSchema:e.object({name:e.string().min(1).optional(),image:e.string().optional().describe("Profile image URL."),country:e.string().optional().describe("ISO country code."),timezone:e.string().optional().describe("IANA timezone."),language:e.string().optional().describe("Language code."),currency:e.string().optional().describe("Currency code.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};for(const t of["name","image","country","timezone","language","currency"]){const n=e[t];void 0!==n&&(r[t]=n)}return t.bb.users.updateProfile(r)}},{name:"update_feature_flag",description:"Set a feature flag on/off for a workspace.",inputSchema:e.object({workspaceId:w,key:e.string().describe("The feature slug."),value:e.boolean().describe("Enabled?")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.features.update(y(e,t),e.key,e.value)},{name:"create_subscription_checkout",description:"Create a Stripe checkout session to subscribe a workspace to a plan.",inputSchema:e.object({workspaceId:w,planVersionId:e.string(),billingInterval:e.string().optional(),currency:e.string().optional(),successUrl:e.string().optional(),cancelUrl:e.string().optional()}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.subscription.checkout(y(e,t),n)}},{name:"update_subscription",description:"Change a workspace's subscription plan.",inputSchema:e.object({workspaceId:w,planVersionId:e.string(),billingInterval:e.string().optional(),successUrl:e.string().optional(),cancelUrl:e.string().optional()}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.subscription.update(y(e,t),n)}},{name:"cancel_subscription",description:"Cancel a workspace's subscription.",inputSchema:e.object({workspaceId:w}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.subscription.cancel(y(e,t))},{name:"resume_subscription",description:"Resume a workspace's canceled subscription.",inputSchema:e.object({workspaceId:w}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.subscription.resume(y(e,t))},{name:"get_billing_portal_url",description:"Get a Stripe billing-portal URL for a workspace.",inputSchema:e.object({workspaceId:w,returnUrl:e.string().optional()}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.subscription.getBillingPortalUrl(y(e,t),e.returnUrl)},{name:"purchase_credits",description:"Create a Stripe checkout session to buy a credit package.",inputSchema:e.object({workspaceId:w,creditPackageId:e.string(),currency:e.string().optional(),successUrl:e.string().describe("Redirect URL on success."),cancelUrl:e.string().describe("Redirect URL on cancel.")}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.credits.purchase(y(e,t),n)}}],v=new Map([...k,...S].map(e=>[e.name,e]));function E(e){if(!1===e)return[];if("readonly"===e)return[...k];if("all"===e)return[...k,...S];const t=e.include?e.include.map(e=>{const t=v.get(e);if(!t)throw new Error(`Unknown built-in MCP tool: ${e}`);return t}):[...k],r=new Set(e.exclude??[]);return t.filter(e=>!r.has(e.name))}const _=e=>({type:"text",text:e}),I=(e,t)=>({type:"image",data:e,mimeType:t}),T=(e,t)=>({type:"audio",data:e,mimeType:t}),x=(e,t,r)=>({type:"resource_link",uri:e,name:t,...r}),P=e=>({type:"resource",resource:e}),U=e=>{if("object"!=typeof e||null===e)return!1;const t=e;switch(t.type){case"text":return"string"==typeof t.text;case"image":case"audio":return"string"==typeof t.data&&"string"==typeof t.mimeType;case"resource_link":return"string"==typeof t.uri&&"string"==typeof t.name;case"resource":{const e=t.resource;return"object"==typeof e&&null!==e&&"string"==typeof e.uri&&("string"==typeof e.text||"string"==typeof e.blob)}default:return!1}},$=e=>e,C=e=>e,A=e=>e,O=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],R=O[0],j="application/json",J=/^[a-zA-Z0-9_-]{1,128}$/,W=-32002,N=-32700,F=-32600,M=-32601,q=-32602,B=-32603;function L(e,t){const r=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===r)return e[t]}function H(e,t){return{status:e,headers:{"Content-Type":j},body:JSON.stringify(t)}}function D(e,t){return H(200,{jsonrpc:"2.0",id:e??null,result:t})}function G(e,t,r,n=200,s){return H(n,{jsonrpc:"2.0",id:e??null,error:{code:t,message:r,...void 0!==s?{data:s}:{}}})}function K(e){return"object"==typeof e&&null!==e&&"function"==typeof e.safeParse}function z(e){return e instanceof Error?e.message:"string"==typeof e?e:JSON.stringify(e)}function V(t){const r=t.serverInfo??{name:"buildbase-mcp",version:"1.0.0"};t.auth&&!t.auth.resourceMetadataUrl&&console.warn("[buildbase/mcp] auth is enabled but `auth.resourceMetadataUrl` is unset — 401 responses will carry no WWW-Authenticate/resource_metadata pointer, so MCP clients cannot discover your authorization server. Set it to your /.well-known/oauth-protected-resource URL.");const n=e=>e.trim().toLowerCase().replace(/\/+$/,""),s=t.allowedOrigins?new Set(t.allowedOrigins.map(n)):null,o=e=>!!e&&!!s&&s.has(n(e)),i=t.builtinTools??(!!t.buildbase&&"readonly"),a=t.maxRequestBytes??1048576;if(!1!==i&&!t.buildbase)throw new Error("builtinTools require a `buildbase` client — pass one to createMcpHandler, or set builtinTools: false.");const c=new Map;for(const e of E(i))c.set(e.name,e);const u=new Set;for(const e of t.tools??[]){if(!J.test(e.name))throw new Error(`Invalid MCP tool name: "${e.name}" (want ${String(J)})`);if(u.has(e.name))throw new Error(`Duplicate MCP tool name: "${e.name}"`);u.add(e.name),c.set(e.name,e)}if(t.builtinResources&&!t.buildbase)throw new Error("builtinResources requires a `buildbase` client — pass one to createMcpHandler.");const l=new Map,p=[];t.builtinResources&&(l.set("buildbase://profile",{uri:"buildbase://profile",name:"profile",title:"Your profile",description:"The authenticated user's BuildBase profile.",mimeType:"application/json",read:e=>e.bb.users.getProfile()}),l.set("buildbase://workspaces",{uri:"buildbase://workspaces",name:"workspaces",title:"Your workspaces",description:"The authenticated user's workspaces (id, name, roles).",mimeType:"application/json",read:e=>e.bb.workspace.list()}),p.push({uriTemplate:"buildbase://workspace/{workspaceId}",name:"workspace",title:"One workspace",description:"A single workspace: name, members, feature flags, quota snapshot.",mimeType:"application/json",read:(e,t,r)=>r.bb.workspace.get(e.workspaceId)}));for(const e of t.resources??[])l.set(e.uri,e);p.push(...t.resourceTemplates??[]);const h=new Map;for(const e of t.prompts??[]){if(!J.test(e.name))throw new Error(`Invalid MCP prompt name: "${e.name}" (want ${String(J)})`);if(h.has(e.name))throw new Error(`Duplicate MCP prompt name: "${e.name}"`);h.set(e.name,e)}const g=l.size>0||p.length>0,m=h.size>0,w=(e,t)=>{const r=new Set(t?.scopes??[]);return(e??[]).every(e=>r.has(e))};function y(e,r){const n=e?.sessionId??"";return{bb:t.buildbase?n?t.buildbase.withSession(n):v:S,auth:e??{sessionId:""},workspaceId:e?.workspaceId,custom:r}}function b(e,t){const r=[],n=e.replace(/[.*+?^$()|[\]\\]/g,e=>"\\"+e).replace(/\{([a-zA-Z0-9_]+)\}/g,(e,t)=>(r.push(t),"([^/]+)")),s=new RegExp(`^${n}$`).exec(t);if(!s)return null;const o={};return r.forEach((e,t)=>{try{o[e]=decodeURIComponent(s[t+1])}catch{o[e]=s[t+1]}}),o}function k(e,t,r){if("string"==typeof r)return{uri:e,mimeType:t??"text/plain",text:r};if(r&&"object"==typeof r){const n=r;if("string"==typeof n.text)return{uri:e,mimeType:"string"==typeof n.mimeType?n.mimeType:t??"text/plain",text:n.text};if("string"==typeof n.blob)return{uri:e,mimeType:"string"==typeof n.mimeType?n.mimeType:t??"application/octet-stream",blob:n.blob}}return{uri:e,mimeType:t??"application/json",text:JSON.stringify(r,null,2)}}const S=new Proxy({},{get(e,t){if("string"==typeof t)throw new Error(`No \`buildbase\` client configured — pass one to createMcpHandler to use bb.${t} in tools.`)}}),v=new Proxy({},{get(e,t){if("string"==typeof t)throw new Error(`This tool needs an authenticated BuildBase session, but the token carried none (bb.${t}). Re-authenticate.`)}}),I=new Map;function T(t){const r=I.get(t.name);if(r)return r;let n;try{n=K(t.inputSchema)?e.toJSONSchema(t.inputSchema,{target:"draft-2020-12"}):t.inputSchema}catch(e){P(e,{method:"tools/list",tool:t.name}),n={type:"object",additionalProperties:!0}}return I.set(t.name,n),n}function x(e){const t=new Set(e?.scopes??[]);return Array.from(c.values()).filter(e=>(e.requiredScopes??[]).every(e=>t.has(e)))}function P(e,r){try{t.onError?.(e instanceof Error?e:new Error(z(e)),r)}catch{}}function $(){if(t.auth&&t.auth.resourceMetadataUrl){const e=f({resourceMetadataUrl:t.auth.resourceMetadataUrl});return{status:e.status,headers:e.headers,body:e.body}}return H(401,{error:"unauthorized"})}const C=Array.isArray(t.cors)?new Set(t.cors.map(n)):null;async function A(e){const i=function(e){if(!1===t.cors)return{};const r=L(e.headers,"origin");let i;return i=C?r&&C.has(n(r))?r:null:s?o(r)?r:null:"*",i?{"Access-Control-Allow-Origin":i,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Protocol-Version, Mcp-Session-Id, Last-Event-ID","Access-Control-Expose-Headers":"MCP-Protocol-Version, Mcp-Session-Id, WWW-Authenticate","Access-Control-Max-Age":"86400",..."*"!==i?{Vary:"Origin"}:{}}:{}}(e);if("OPTIONS"===e.method.toUpperCase())return{status:204,headers:i,body:""};const c=await async function(e){const n=e.method.toUpperCase();if(s){const t=L(e.headers,"origin");if(t&&!o(t))return H(403,{error:"origin_not_allowed"})}if("POST"!==n)return{status:405,headers:{"Content-Type":j,Allow:"POST, OPTIONS"},body:JSON.stringify({error:"method_not_allowed"})};if(a>0&&"string"==typeof e.body&&e.body.length>a)return H(413,{error:"payload_too_large"});let i=null;if(!1!==t.auth){const r=d(L(e.headers,"authorization"));if(!r)return $();try{i=await t.auth.verify(r,e)}catch(e){P(e,{method:"auth"}),i=null}if(!i)return $()}if(t.rateLimit){let r;try{r=await t.rateLimit(i,e)}catch(e){P(e,{method:"rateLimit"}),r=!1}if(!("boolean"==typeof r?r:r.ok)){const e="object"==typeof r?r.retryAfter:void 0;return{status:429,headers:{"Content-Type":j,...void 0!==e?{"Retry-After":String(e)}:{}},body:JSON.stringify({error:"rate_limited"})}}}let c=e.body;if("string"==typeof e.body)try{c=JSON.parse(e.body)}catch{return G(null,N,"Invalid JSON",400)}if(Array.isArray(c))return G(null,F,"Batch requests are not supported",400);if("object"!=typeof c||null===c)return G(null,F,"Expected a JSON-RPC request object",400);const u=c,f=u.id,S="string"==typeof u.method?u.method:null;if(!S)return G(f,F,"Missing method",400);if(null==f)return{status:202,headers:{"Content-Type":j},body:""};const v=u.params??{};switch(S){case"initialize":{const e=v.protocolVersion;return D(f,{protocolVersion:"string"==typeof e&&O.includes(e)?e:R,capabilities:{tools:{listChanged:!1},...g?{resources:{}}:{},...m?{prompts:{}}:{}},serverInfo:r,...t.instructions?{instructions:t.instructions}:{}})}case"ping":return D(f,{});case"tools/list":return D(f,{tools:x(i).map(e=>({name:e.name,description:e.description,inputSchema:T(e),...e.annotations?{annotations:e.annotations}:{},...e.icons?{icons:e.icons}:{}}))});case"tools/call":{const r="string"==typeof v.name?v.name:"",n=x(i).find(e=>e.name===r);if(!n)return G(f,q,`Unknown tool: ${r||"(missing name)"}`);let s,o=v.arguments??{};if(K(n.inputSchema)){const e=n.inputSchema.safeParse(o);if(!e.success){const t=e.error.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ");return D(f,{content:[{type:"text",text:`Invalid arguments for ${r}: ${t}`}],isError:!0})}o=e.data}if(t.context)try{s=await t.context(i,e)}catch(e){return P(e,{method:S,tool:r}),G(f,B,"Context initialization failed")}const a=y(i,s);try{const e=await n.execute(o,a);if("object"==typeof(E=e)&&null!==E&&Array.isArray(E.content)&&E.content.length>0&&E.content.every(U))return D(f,{content:e.content,...void 0!==e.structuredContent?{structuredContent:e.structuredContent}:{},isError:e.isError??!1});const t="object"==typeof e&&null!==e&&!Array.isArray(e);return D(f,{content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e,null,2)}],...t?{structuredContent:e}:{},isError:!1})}catch(e){P(e,{method:S,tool:r});const n=e instanceof Error?e:new Error(z(e));return D(f,{content:[{type:"text",text:t.formatToolError?t.formatToolError(n,{tool:r}):n.message}],isError:!0})}}case"resources/list":if(!g)break;return D(f,{resources:Array.from(l.values()).filter(e=>w(e.requiredScopes,i)).map(e=>({uri:e.uri,name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.mimeType?{mimeType:e.mimeType}:{},...e.icons?{icons:e.icons}:{}}))});case"resources/templates/list":if(!g)break;return D(f,{resourceTemplates:p.filter(e=>w(e.requiredScopes,i)).map(e=>({uriTemplate:e.uriTemplate,name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.mimeType?{mimeType:e.mimeType}:{},...e.icons?{icons:e.icons}:{}}))});case"resources/read":{if(!g)break;if("string"!=typeof v.uri||""===v.uri)return G(f,q,"Missing required parameter: uri");const r=v.uri;let n,s=null;const o=l.get(r);if(o){if(!w(o.requiredScopes,i))return G(f,W,"Resource not found",200,{uri:r});n=o.mimeType,s=async e=>o.read(e)}else for(const e of p){if(!w(e.requiredScopes,i))continue;const t=b(e.uriTemplate,r);if(t){n=e.mimeType,s=async n=>e.read(t,r,n);break}}if(!s)return G(f,W,"Resource not found",200,{uri:r});let a;if(t.context)try{a=await t.context(i,e)}catch(e){return P(e,{method:S}),G(f,B,"Context initialization failed")}try{const e=await s(y(i,a));return D(f,{contents:[k(r,n,e)]})}catch(e){return P(e,{method:S}),G(f,B,"Resource read failed",200,{uri:r})}}case"prompts/list":if(!m)break;return D(f,{prompts:Array.from(h.values()).filter(e=>w(e.requiredScopes,i)).map(e=>({name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.arguments?{arguments:e.arguments}:{},...e.icons?{icons:e.icons}:{}}))});case"prompts/get":{if(!m)break;const r="string"==typeof v.name?v.name:"",n=h.get(r);if(!n||!w(n.requiredScopes,i))return G(f,q,`Unknown prompt: ${r||"(missing name)"}`);const s="object"==typeof v.arguments&&null!==v.arguments?v.arguments:{},o={};for(const[e,t]of Object.entries(s))"string"==typeof t&&(o[e]=t);const a=(n.arguments??[]).filter(e=>e.required&&!(e.name in o)).map(e=>e.name);if(a.length)return G(f,q,`Missing required arguments: ${a.join(", ")}`);let c;if(t.context)try{c=await t.context(i,e)}catch(e){return P(e,{method:S}),G(f,B,"Context initialization failed")}try{const e=await n.get(o,y(i,c)),t="string"==typeof e?{messages:[{role:"user",content:_(e)}]}:Array.isArray(e)?{messages:e}:e,r=t.description??n.description;return D(f,{...r?{description:r}:{},messages:t.messages})}catch(e){return P(e,{method:S}),G(f,B,"Prompt rendering failed")}}}var E;return G(f,M,`Method not found: ${S}`)}(e);return Object.keys(i).length?{...c,headers:{...c.headers,...i}}:c}return{handle:A,fetch:async function(e){const t={};if(e.headers.forEach((e,r)=>{t[r]=e}),a>0){const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>a)return new Response(JSON.stringify({error:"payload_too_large"}),{status:413,headers:{"Content-Type":j}})}const r="POST"===e.method.toUpperCase()?await e.text():void 0,n=await A({method:e.method,headers:t,body:r});return new Response(""===n.body?null:n.body,{status:n.status,headers:n.headers})},listTools:()=>Array.from(c.values()).map(e=>({name:e.name,description:e.description,...e.annotations?{annotations:e.annotations}:{}})),serverCard:e=>({name:r.name,version:r.version,endpoint:e.endpoint,transport:"streamable-http",capabilities:{tools:{listChanged:!1},...g?{resources:{}}:{},...m?{prompts:{}}:{}},...e.description?{description:e.description}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{}})}}function Q(e){return e}const Y=12,Z=16;function X(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("WebCrypto is unavailable in this runtime — agent-auth session encryption requires globalThis.crypto.subtle (Node 18+, Bun, Deno, edge, browsers).");return e.subtle}const ee=new Map;function te(e){let t=ee.get(e);return t||(t=(async()=>{const t=await X().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return X().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),ee.set(e,t)),t}function re(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(r){const n=globalThis.crypto.getRandomValues(new Uint8Array(Y)),s=await te(e),o=new Uint8Array(await X().encrypt({name:"AES-GCM",iv:n},s,(new TextEncoder).encode(r))),i=o.subarray(o.length-Z),a=o.subarray(0,o.length-Z),c=new Uint8Array(28+a.length);return c.set(n,0),c.set(i,Y),c.set(a,28),t(c)},async decryptSessionRef(t){try{const n=r(t);if(n.length<=28)return null;const s=n.slice(0,Y),o=n.subarray(Y,28),i=n.subarray(28),a=new Uint8Array(i.length+Z);a.set(i,0),a.set(o,i.length);const c=await te(e),u=await X().decrypt({name:"AES-GCM",iv:s},c,a);return(new TextDecoder).decode(u)}catch{return null}}}}async function ne(e){const{claims:t,secret:r}=e,n=e.expiresInSec??3600,s=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,o=t.sessionId?await re(r).encryptSessionRef(t.sessionId):void 0;return{token:g({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...o?{sid:o}:{},...e.extraClaims},r,{expiresInSec:n}),expiresIn:n}}function se(e,t,r){const n=globalThis.process?.env;"1"===n?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${r}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function oe(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const r=re(t),n=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let s=e.resourceMetadataUrl;if(!s&&n.length)try{const e=new URL(n[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");s=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:s,verify:async s=>{let o;try{o=p(s,t,{...e.verify})}catch{return null}if(n.length){const t=o.aud?Array.isArray(o.aud)?o.aud:[o.aud]:[];if(!t.length&&e.requireAudience)return se(t,n,"token carries no aud claim"),null;if(t.length&&!t.some(e=>n.includes(e)))return se(t,n,"aud does not include this resource"),null}const i="string"==typeof o.sid?await r.decryptSessionRef(o.sid):null,a=Array.isArray(o.scope)?o.scope.filter(e=>"string"==typeof e):"string"==typeof o.scope?o.scope.split(" ").filter(Boolean):void 0;return{sessionId:i??"",userId:"string"==typeof o.userId?o.userId:"string"==typeof o.sub?o.sub:void 0,workspaceId:"string"==typeof o.workspaceId?o.workspaceId:void 0,scopes:a,claims:o}}}}const ie=300,ae="/.well-known/oauth-protected-resource",ce="/.well-known/agent-skills",ue="/.well-known/api-catalog",le="/.well-known/mcp/server-card.json",pe="/.well-known/agent-card.json",de="application/json",he="application/linkset+json",ge="text/markdown; charset=utf-8",me="text/plain; charset=utf-8",fe="application/xml; charset=utf-8",we=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ye(e){return e.replace(/\/+$/,"")}function be(e){return`public, max-age=${e}, s-maxage=${e}`}function ke(e){return"sha256:"+function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(o(i(e)))}const Se=new Map;async function ve(e,t,r,n){if(!n||n<=0)return e(t,r);const s=new AbortController,o=setTimeout(()=>s.abort(),n);try{return await e(t,{...r,signal:s.signal})}finally{clearTimeout(o)}}async function Ee(e){const t=e.cacheTtlSeconds??ie,r=`${ye(e.serverUrl)}::${e.orgId}`,n=Se.get(r);if(n&&n.expiresAt>Date.now())return n.value;const s=e.fetch??fetch,o=`${ye(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const t=await ve(s,o,{headers:{Accept:de}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(i=e)}}catch{}return Se.set(r,{value:i,expiresAt:Date.now()+1e3*t}),i}const _e=new Map;function Ie(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const r="/"===t?"":t.replace(/\/+$/,"");return ae+r}function Te(e){return e.path??`${ce}/${e.name}/SKILL.md`}function xe(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:me,body:t.join("\n")+"\n",cacheControl:be(e.cacheTtlSeconds??ie)}}function Pe(e){return e.endsWith(".json")||e.includes(".well-known/")?de:e.endsWith(".md")?ge:e.endsWith(".xml")?fe:me}function Ue(e){const t=e??{tools:!0},r={tools:!1,resources:!1,prompts:!1};for(const[e,n]of Object.entries(t))r[e]=!1!==n&&null!=n;return r}function $e(e,t){return{status:200,contentType:de,body:JSON.stringify(e,null,2),cacheControl:be(t.cacheTtlSeconds??ie)}}function Ce(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Ae(e,t){const r=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Ce(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&r.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])r.push(`Allow: ${Ce(t)}`);for(const t of e.disallow??[])r.push(`Disallow: ${Ce(t)}`);return void 0!==e.crawlDelay&&r.push(`Crawl-delay: ${Ce(e.crawlDelay)}`),r.join("\n")}function Oe(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function Re(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function je(e){const t=ye(e.siteUrl),r=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&r.push(`<${t}${pe}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const n=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;r.push(`<${n}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&r.push(`<${t}${ue}>; rel="api-catalog"; type="${he}"`),e.mcpServerCard&&r.push(`<${t}${le}>; rel="mcp-server"; type="application/json"`),r.join(", ")}async function Je(e,t){const r=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===r){return function(e,t){const r=ye(e.siteUrl),n={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:ae};return t.authorizationServer?.metadataUrl&&(n.oauth_authorization_server=t.authorizationServer.metadataUrl,n.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(n.auth="/auth.md"),e.skills?.length&&(n.agent_skills=`${ce}/index.json`),e.apiCatalog?.length&&(n.api_catalog=ue),e.mcpServerCard&&(n.mcp_server_card=le),!1!==e.a2aCard&&(n.a2a_agent_card=pe),e.llmsFullTxt&&(n.llms_full_txt="/llms-full.txt"),$e({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:r,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:r},capabilities:n,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}(t,await Ee(t))}if(r===pe)return function(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},r=ye(e.siteUrl),n=t.serviceUrl??r,s=t.transportProtocol??"http",o=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return $e({protocolVersion:"0.3.0",name:t.name??e.site.name,version:t.version??"1.0.0",description:t.description??e.site.description??`${e.site.name} — agent-accessible web application.`,url:n,preferredTransport:s,supportedInterfaces:[{serviceUrl:n,transportProtocol:s}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:r},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:o,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}(t);if("/.well-known/http-message-signatures-directory"===r)return function(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:be(e.cacheTtlSeconds??ie)}:null}(t);if("/.well-known/security.txt"===r)return xe(t);if(r===`${ce}/index.json`)return function(e){const t=e.skills??[];if(!t.length)return null;const r=ye(e.siteUrl);return $e({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${r}${Te(e)}`,digest:ke(e.content)}))},e)}(t);if(r.startsWith(`${ce}/`)&&r.endsWith("SKILL.md"))return function(e,t){const r=(t.skills??[]).find(t=>Te(t)===e);return r?{status:200,contentType:"text/markdown; charset=utf-8",body:r.content,cacheControl:be(t.cacheTtlSeconds??ie)}:null}(r,t);if("/.well-known/oauth-authorization-server"===r||"/.well-known/openid-configuration"===r){const e=(await Ee(t)).authorizationServer;if(!e?.metadataUrl)return null;const r=await async function(e,t){const r=t.cacheTtlSeconds??ie,n=_e.get(e);if(n&&n.expiresAt>Date.now())return n.value;const s=t.fetch??fetch;let o=null;try{const r=await ve(s,e,{headers:{Accept:de}},t.fetchTimeoutMs??5e3);if(r.ok){const e=await r.json();e&&"object"==typeof e&&(o=e)}}catch{}return _e.set(e,{value:o,expiresAt:Date.now()+1e3*r}),o}(e.metadataUrl,t);return $e(r?r:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(r===ue)return function(e){const t=e.apiCatalog??[];if(!t.length)return null;const r=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:he,body:JSON.stringify({linkset:r},null,2),cacheControl:be(e.cacheTtlSeconds??ie)}}(t);if(r===le)return function(e){const t=e.mcpServerCard;return t?$e({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-11-25",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:Ue(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}(t);if("/.well-known/mcp.json"===r)return function(e){const t=e.mcpServerCard;if(!t)return null;const r=ye(e.siteUrl);let n;try{n={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${Ie(t.endpoint)}`}}catch{}return $e({$schema:"https://modelcontextprotocol.io/schemas/mcp-discovery/v1.0",version:"1.0",servers:[{name:t.name,...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},version:t.version,capabilities:Ue(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${r}${le}`,...n?{authentication:n}:{}}]},e)}(t);if(r.startsWith(ae)){const e=await Ee(t);return function(e,t,r){const n=t.protectedResources??[];if(!n.length)return null;const s=e.replace(/\/+$/,"")||ae,o=r??`${ye(t.serverUrl)}/org/${t.orgId}`,i=t.scopes?.map(e=>e.name),a=n.map(e=>{const r=e.resource??ye(t.siteUrl),n=e.scopes??i;return{path:Ie(r),metadata:{resource:r,authorization_servers:[o],bearer_methods_supported:e.bearerMethods??["header"],...n?.length?{scopes_supported:n}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=a.find(e=>e.path===s);return c?$e(c.metadata,t):s===ae&&1===a.length?$e(a[0].metadata,t):null}(r,t,e.authorizationServer?.issuer)}return null}async function We(e,t){const r=e.replace(/\/+$/,"")||e,n=function(e,t){const r=t.extraPaths?.[e];if(void 0===r)return null;const n="string"==typeof r?{body:r}:r;return{status:n.status??200,contentType:n.contentType??Pe(e),body:n.body,cacheControl:n.cacheControl??be(t.cacheTtlSeconds??ie)}}(r,t);return n||("/robots.txt"===r?function(e){const t=e.robots??{},r=ye(e.siteUrl),n=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",o="allow"===s?[{userAgent:[...we],allow:["/"]}]:"deny"===s?[{userAgent:[...we],disallow:["/"]}]:s,i=t.sitemaps??(e.sitemap?[`${r}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${r}/llms.txt and ${r}/.well-known/agent.json`,...n.map((e,r)=>Ae(e,0===r?t.contentSignals:void 0)),...o.map(e=>Ae(e)),...i.length?[i.map(e=>`Sitemap: ${Ce(e)}`).join("\n")]:[]];return{status:200,contentType:me,body:a.join("\n\n")+"\n",cacheControl:be(e.cacheTtlSeconds??ie)}}(t):"/llms-full.txt"===r?function(e){return e.llmsFullTxt?{status:200,contentType:me,body:e.llmsFullTxt,cacheControl:be(e.cacheTtlSeconds??ie)}:null}(t):"/sitemap.xml"===r?function(e){const t=e.sitemap?.urls;if(!t?.length)return null;const r=ye(e.siteUrl),n='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+t.map(e=>{const t="string"==typeof e?{loc:e}:e;return` <url>\n${[` <loc>${Re(/^https?:\/\//.test(t.loc)?t.loc:`${r}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${Re(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${Re(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Oe(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:fe,body:n,cacheControl:be(e.cacheTtlSeconds??ie)}}(t):"/llms.txt"===r?function(e){return e.llmsTxt?{status:200,contentType:me,body:e.llmsTxt,cacheControl:be(e.cacheTtlSeconds??ie)}:null}(t):"/auth.md"===r?function(e,t){const r=be(e.cacheTtlSeconds??ie);if(e.authMd)return{status:200,contentType:ge,body:e.authMd,cacheControl:r};const n=t.authorizationServer;if(!n)return null;const s=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${n.issuer}\`\n- Metadata (RFC 8414): ${n.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, supported grant types / PKCE methods, and — when the app allows it — the dynamic client \`registration_endpoint\` (RFC 7591).\n\n## Protected resources (RFC 9728)\nSee \`/.well-known/oauth-protected-resource\`, which lists the resource, its supported scopes, and the authorization server(s) that can issue tokens for it.\n\n## How an agent authenticates\n1. Discover this document and \`/.well-known/oauth-protected-resource\`.\n2. Fetch the authorization-server metadata for the endpoints.\n3. Register a client (dynamic registration) or use a pre-issued client_id.\n4. Run the authorization-code flow with PKCE (S256), requesting the scopes and target \`resource\`.\n5. Exchange the code for an access token and call the API with \`Authorization: Bearer <token>\`.\n\nDocumentation: ${e.site.documentationUrl??e.siteUrl}\n`;return{status:200,contentType:ge,body:s,cacheControl:r}}(t,await Ee(t)):"/security.txt"===r?xe(t):r.startsWith("/.well-known")?Je(r,t):null)}let Ne=!0;function Fe(e,...t){Ne&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function Me(e,...t){console.error(e,...t)}async function qe(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function Be(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await qe(e);r=t.message||t.error||r}catch{r=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(r)}try{return await qe(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class Le extends Error{constructor(e,t,r,n){super(e),this.code=t,this.context=r,this.originalError=n,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,Le)}}const He=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(Ne=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new Le("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),n=r instanceof Le?r:new Le(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&Fe(`[SDK Error] ${t.component||"Unknown"}:`,{message:n.message,code:n.code,context:n.context,originalError:n.originalError,stack:n.stack}),this.config.onError)try{this.config.onError(n,t)}catch(e){Me("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(n,t)}catch(e){Me("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(n,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function De(e,t={}){He.handleError(e,t)}function Ge(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return De(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}const Ke="saas-session-id",ze="saas-device-id";function Ve(){return function(){if("undefined"==typeof window)return null;try{return Ge(Ke)}catch(e){return De(e,{component:"auth-utils",action:"getSessionId",metadata:{key:Ke}}),null}}()}function Qe(){const e=Ve(),t={};e&&(t["x-session-id"]=e);const r=function(){if("undefined"==typeof window)return null;try{return Ge(ze)??null}catch(e){return De(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:ze}}),null}}();return r&&(t["x-device-id"]=r),t}const Ye=new WeakSet,Ze=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Xe="SDK is not ready (missing serverUrl, version, or orgId)";class et{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(Xe);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(Xe)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:Qe()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){Ye.has(e)||(Ye.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((r,n)=>{const s=()=>{clearTimeout(o),n(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const o=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,r){const n=(t.method??"GET").toUpperCase(),s=r??e,o=this.buildHeaders(t),i={...t,headers:o},a=Ze.has(n);let c,u;if(this._timeout>0){u=new AbortController;const e=u;c=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const n=new AbortController,s=e=>{n.signal.aborted||n.abort(e.reason)};for(const r of[e,t]){if(r.aborted){s(r);break}r.addEventListener("abort",()=>s(r),{once:!0})}return n.signal}(t.signal,e.signal):e.signal}const l=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${n} ${s}`);return this.reportError(e,{method:n,path:s}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const r=this._fetch.bind(globalThis),s=await r(e,i);if(this._debug&&console.log(`[BuildBase] ${n} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await et.delay(e,i.signal),p(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await et.delay(e,i.signal)}catch(e){throw l(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:n,path:s}),e}};try{return await p(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await Be(n,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},r="Request failed"){const n=await this.fetchResponse(e,t);return n.ok||await this.throwResponseError(n,r),this.unwrapResponse(n,r)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw Object.assign(new Error(r),{status:e.status})}apiPath(e,...t){return e.reduce((e,r,n)=>e+r+(n<t.length?encodeURIComponent(String(t[n])):""),"")}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return void 0!==r.data?r.data:r}return r}}class tt extends et{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,r){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}class rt extends et{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class nt extends et{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class st extends et{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class ot extends et{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class it extends et{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}async updateWorkspace(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:r},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to invite member")}async removeUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:r},"Failed to remove user")}async updateUser(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r),signal:n},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:r},"Failed to update workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}}),signal:n},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,r){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:r},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create checkout session")}async selectFreePlan(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:r},"Failed to select free plan")}async updateSubscription(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:r},"Failed to update subscription")}async createBillingPortalSession(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:r})}async listInvoices(e,t=10,r,n){const s=new URLSearchParams;return s.append("limit",t.toString()),r&&s.append("starting_after",r),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:n},"Failed to fetch invoices")}async getInvoice(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:r},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record usage")}async recordUsageBatch(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:r},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,r){const n=new URLSearchParams;t?.quotaSlug&&n.append("quotaSlug",t.quotaSlug),t?.from&&n.append("from",t.from),t?.to&&n.append("to",t.to),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),o=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch usage logs")}async sendNotification(e,t,r,n,s){const o={event:t};return r&&(o.userId=r),n&&(o.data=n),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(o),signal:s},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,r){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:r},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,r){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:r});if(!n.ok){if(402===n.status){const e=await n.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(n,"Failed to consume credits")}return this.unwrapResponse(n,"Failed to consume credits")}async purchaseCredits(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const r=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t,r){const n=new URLSearchParams;t?.type&&n.append("type",t.type),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),o=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,r){const n=new URLSearchParams;t?.status&&n.append("status",t.status),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),o=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,r){const n=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+n,{signal:r},"Failed to fetch expiring credits")}}const at={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view"},ct=Object.values(at),ut={admin:ct.filter(e=>e!==at.WORKSPACE_DELETE),member:[at.WORKSPACE_SETTINGS_VIEW,at.WORKSPACE_MEMBERS_VIEW,at.WORKSPACE_FEATURES_VIEW,at.WORKSPACE_BILLING_VIEW,at.WORKSPACE_USAGE_VIEW],viewer:[at.WORKSPACE_SETTINGS_VIEW,at.WORKSPACE_MEMBERS_VIEW]};function lt(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function pt(e){const{userId:t,workspace:r,settings:n,appPermissions:s}=e;if(!r||!t)return new Set;if(function(e,t){if(!t)return!1;const r=(n=e.createdBy)?"string"==typeof n?n:"object"==typeof n&&"_id"in n&&"string"==typeof n._id?n._id:null:null;var n;return null!==r&&r===t}(r,t)){const e=new Set(ct);if(s)for(const t of lt(s))e.add(t);if(r.permissions)for(const t of lt(r.permissions))e.add(t);if(n?.workspace?.permissions)for(const t of lt(n.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}(r,t);if(!o)return new Set;const i=r.permissions,a=n?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!i&&o in i,p=!!a&&o in a,d=o in ut;let h;if(l)h=c(i[o]);else if(p)h=c(a[o]);else if(d)h=ut[o];else{const e=n?.workspace?.defaultRole;h=e&&e in ut?ut[e]:[]}const g=new Set(h),m=l?u(i[o]):[],f=s?.[o]?u(s[o]):[],w=l?m:f;for(const e of w)g.add(e);return function(e,t,r){if(!r?.workspace)return;const{canInviteMembers:n}=r.workspace;(!1===n||"admin-only"===n&&"admin"!==t)&&e.delete(at.WORKSPACE_MEMBERS_INVITE)}(g,o,n),g}function dt(e){const{serverUrl:t,orgId:r,version:n="v1",getSessionId:s,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!r)throw new Error("BuildBase: orgId is required");const p={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},d=e=>{const s={serverUrl:t,version:n,orgId:r,sessionId:e,...p};return{workspace:new it(s),user:new ot(s),settings:new st(s),push:new rt(s),devices:new tt(s),sessions:new nt(s)}},h=new it({serverUrl:t,version:n,orgId:r,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,r)=>(await e()).workspace.updateWorkspace(t,r),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,r,n)=>(await e()).workspace.addUser(t,{email:r,role:n}),remove:async(t,r)=>(await e()).workspace.removeUser(t,r),updateRole:async(t,r,n)=>(await e()).workspace.updateUser(t,r,{role:n}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,r)=>(await e()).workspace.createCheckoutSession(t,r),update:async(t,r)=>(await e()).workspace.updateSubscription(t,r),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,r)=>(await e()).workspace.createBillingPortalSession(t,r)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,r,n)=>(await e()).workspace.listInvoices(t,r,n),get:async(t,r)=>(await e()).workspace.getInvoice(t,r)},usage:{record:async(t,r)=>(await e()).workspace.recordUsage(t,r),recordBatch:async(t,r)=>(await e()).workspace.recordUsageBatch(t,r),getQuota:async(t,r)=>(await e()).workspace.getQuotaUsageStatus(t,r),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,r)=>(await e()).workspace.getUsageLogs(t,r)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,r,n)=>(await e()).workspace.updateFeature(t,r,n)},notification:{send:async(t,r,n,s)=>(await e()).workspace.sendNotification(t,r,n,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,r)=>(await e()).workspace.consumeCredits(t,r),purchase:async(t,r)=>(await e()).workspace.purchaseCredits(t,r),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,r)=>(await e()).workspace.getCreditTransactions(t,r),getBuckets:async(t,r)=>(await e()).workspace.getCreditBuckets(t,r),getExpiring:async(t,r)=>(await e()).workspace.getExpiringCredits(t,r),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,r,n)=>{const s=await e(),[o,i,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return function(e,t){const r=pt(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)}(n,{userId:r,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,r)=>{const n=await e(),[s,o,i]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return pt({userId:r,workspaceRole:a?.role??null,workspace:s,settings:o})}},devices:{list:async()=>(await e()).devices.list(),rename:async(t,r)=>(await e()).devices.rename(t,r),signOut:async t=>(await e()).devices.signOut(t),forget:async t=>(await e()).devices.forget(t)},sessions:{list:async()=>(await e()).sessions.list(),revoke:async t=>(await e()).sessions.revoke(t)}}),m=g(async()=>d(await(async()=>{if(!s)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await s();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!s)return null;const e=await s();return e?{sessionId:e}:null},withSession:e=>{const t=d(e);return g(async()=>t)},client:{forSession:d},...m}}function ht(e){const t=ye(e.siteUrl),r=e.mcp?.path??"/api/mcp",n=`${t}${r.startsWith("/")?r:`/${r}`}`,s=e.mcp?.serverInfo??{name:e.site.name,version:"1.0.0"},o=`${t}/mcp`,i=Array.from(new Set([o,n])),a=e.mcp?.auth??(e.secret?oe({secret:e.secret,resource:i,resourceMetadataUrl:`${t}/.well-known/oauth-protected-resource/mcp`,requireAudience:!0}):void 0);if(void 0===a)throw new Error("createAgentStack: pass `secret` (the app token-signing secret) to derive auth, or set `mcp.auth` yourself (`false` disables auth — local development only).");const c=V({buildbase:e.mcp?.buildbase??dt({serverUrl:e.serverUrl,orgId:e.orgId}),serverInfo:s,auth:a,tools:e.mcp?.tools,builtinTools:e.mcp?.builtinTools??"readonly",...e.mcp?.handler}),u={serverUrl:e.serverUrl,orgId:e.orgId,siteUrl:e.siteUrl,site:e.site,mcpServerCard:c.serverCard({endpoint:n,...e.site.description?{description:e.site.description}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}),...e.scopes?{scopes:e.scopes}:{},protectedResources:i.map(t=>({resource:t,...e.mcp?.scopes?.length?{scopes:e.mcp.scopes}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}})).concat([{resource:t,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}]),apiCatalog:[{anchor:n,title:`${e.site.name} MCP server`,serviceDesc:`${t}/.well-known/mcp/server-card.json`}],...e.discovery},l={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, OPTIONS"};const p=e=>c.fetch(e);return{mcp:c,mcpEndpoint:n,config:u,linkHeader:je(u),resolvePath:e=>We(e,u),serveAgentPath:async function(e){if("OPTIONS"===e.method.toUpperCase())return new Response(null,{status:204,headers:l});const t=await We(new URL(e.url).pathname,u);return t?new Response(t.body,{status:t.status,headers:{"Content-Type":t.contentType,"Cache-Control":t.cacheControl,...t.vary?{Vary:t.vary}:{},...l}}):new Response(JSON.stringify({error:"not_found"}),{status:404,headers:{"Content-Type":"application/json",...l}})},routes:{GET:p,POST:p,DELETE:p,OPTIONS:p}}}export{u as AppBridgeError,f as bearerChallenge,oe as buildbaseAuth,v as builtinMcpTools,ht as createAgentStack,V as createMcpHandler,re as createSessionRefCrypto,A as defineMcpPrompt,$ as defineMcpResource,C as defineMcpResourceTemplate,Q as defineMcpTool,d as extractBearerToken,T as mcpAudio,P as mcpEmbeddedResource,I as mcpImage,x as mcpResourceLink,_ as mcpText,ne as mintAgentToken,E as selectBuiltinTools,g as signClientJwt,p as verifyClientJwt};