@heroui/agent 1.0.0-beta.10 → 1.0.0-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-5CSSZ76R.js → chunk-AMNE7O54.js} +1 -1
- package/dist/{chunk-MB3T5S5N.js → chunk-IGSNBYO2.js} +1 -1
- package/dist/chunk-QSLALU5G.js +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/internal/host.js +1 -1
- package/dist/internal/shared.d.ts +1 -1
- package/dist/internal/shared.js +1 -1
- package/dist/next.d.ts +1 -1
- package/dist/next.js +1 -1
- package/dist/{version-LiwSi-9e.d.ts → version-BNdyk3rt.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-23EBJXRA.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as te}from"./chunk-23EBJXRA.js";import{c as ee,h as G,i as ne,j as oe,m as re,n as ie,o as B}from"./chunk-FZXNXBTZ.js";function ye(e,t){return e.throwIfAborted(),new Promise((n,o)=>{let s=()=>o(e.reason);e.addEventListener("abort",s,{once:!0});try{t().then(n,o).finally(()=>e.removeEventListener("abort",s))}catch(u){e.removeEventListener("abort",s),o(u)}})}async function V(e,t,n){let o=new AbortController,s=setTimeout(()=>o.abort(new DOMException("Request timed out","TimeoutError")),e),u=n?AbortSignal.any([n,o.signal]):o.signal;try{return await ye(u,()=>t(u))}finally{clearTimeout(s)}}var be={approval:"This approval has expired. Ask the agent to request it again.",authentication:"Could not authenticate. Sign in if needed, then retry.",chunk:"Could not load the conversation. Retry, or reload the panel.",configuration:"Could not load the agent configuration. Try again.",connection:"Connection interrupted. Completed page changes remain applied. Reconnect to continue this chat.",credits:"This agent has reached its usage limit.",deleted:"This conversation was deleted. Start a new conversation.",rate_limit:"Too many requests. Wait a moment before retrying.",unknown:"The request could not be completed. Try again."},ve="Too many conversations are active. Wait a few minutes, then retry this chat.";function X(e,t="connecting"){let n=e&&typeof e=="object"?e:{},o=[e instanceof Error?e.message:"",n.code,n.status].filter(u=>typeof u=="string"||typeof u=="number").join(" ").toLowerCase(),s=t==="authenticating"||/auth|401|sign.in/.test(o)?"authentication":/429|rate.limit|concurrency_limit|too many conversations are active/.test(o)?"rate_limit":/credit|usage.limit|usage_limit|402/.test(o)?"credits":/deleted|conversation_not_found/.test(o)?"deleted":/approval.*expir/.test(o)?"approval":/dynamic.*import|chunk|module.*fetch/.test(o)?"chunk":/config/.test(o)?"configuration":/network|fetch|connect|timeout|timed out/.test(o)?"connection":"unknown";return{category:s,diagnosticId:crypto.randomUUID(),message:/concurrency_limit|too many conversations are active/.test(o)?ve:be[s],phase:t,retryable:!["credits","deleted","approval"].includes(s)}}var Ae=5e3;function ae(e){return`heroui-agent:anonymous:${e}`}function Te(e){return e instanceof Error?e:new Error("Auth token request failed")}var M=class{constructor(t,n){this.agentId=t;this.getAuthToken=n}cached=null;failure=null;generation=0;pending=null;controller=new AbortController;clear(){this.controller.abort(),this.controller=new AbortController,this.generation+=1,this.cached=null,this.failure=null,this.pending=null}reset(){this.clear();try{localStorage.removeItem(ae(this.agentId))}catch{}}async get(){if(this.cached&&this.expiresAt(this.cached)>Date.now()+6e4)return this.cached.token;if(!this.pending&&this.failure&&Date.now()<this.failure.retryAt)throw this.failure.error;let t=this.generation,n=this.pending??this.refresh();this.pending||(this.pending=n);try{let o=await n;return t!==this.generation?this.get():(this.cached=o,this.failure=null,o.token)}catch(o){throw t===this.generation&&(this.failure={error:Te(o),retryAt:Date.now()+Ae}),o}finally{this.pending===n&&(this.pending=null)}}async subjectHash(){let t=await this.get(),n=xe(t),o=typeof n.sub=="string"?n.sub:"anonymous",s=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${this.agentId}:${o}`));return Array.from(new Uint8Array(s),u=>u.toString(16).padStart(2,"0")).join("").slice(0,24)}anonymousId(){let t=ae(this.agentId);try{let n=localStorage.getItem(t);if(n)return n;let o=crypto.randomUUID();return localStorage.setItem(t,o),o}catch{return crypto.randomUUID()}}expiresAt(t){return t.expiresAt}async refresh(){let t=await V(15e3,n=>this.getAuthToken({agentId:this.agentId,anonymousId:this.anonymousId(),signal:n}),this.controller.signal);if(!t||typeof t.token!="string"||!t.token.trim()||typeof t.expiresAt!="number"||!Number.isFinite(t.expiresAt)||t.expiresAt<=0)throw new Error("Auth token callback returned invalid data");return{expiresAt:t.expiresAt,token:t.token}}};function xe(e){try{let t=e.split(".")[1];if(!t)return{};let n=t.replace(/-/g,"+").replace(/_/g,"/"),o=n.padEnd(Math.ceil(n.length/4)*4,"=");return JSON.parse(atob(o))}catch{return{}}}var Ee=64*1024,H=class extends Error{constructor(n,o){super(o);this.code=n}};function se(e){let t;try{let n=e??null;if(!B(n))throw new Error("Not a JSON value");t=JSON.stringify(n)}catch{throw new H("CLIENT_TOOL_RESULT_NOT_SERIALIZABLE","The client tool returned a result that is not JSON-serializable. Return plain JSON values; convert Map and Date values explicitly and remove circular references. The tool already ran; do not repeat an action without checking its outcome.")}if(new TextEncoder().encode(t).byteLength>Ee)throw new H("CLIENT_TOOL_RESULT_TOO_LARGE","The client tool result exceeds the 64 KiB limit. Request fewer rows or fields, paginate the data, or use uploadDataSource for a larger dataset. The tool already ran; do not repeat an action without checking its outcome.");return JSON.parse(t)}function le(e){return{bounds:null,closing:!1,dragging:!1,expanded:e.appearance?.panel?.expanded??!1,mounted:!1,open:!1,overlayOpen:!1,ready:!1,resizing:!1,sidebarWidth:null,viewMode:e.appearance?.viewMode??"floating"}}function A(e,t,n,o){return{background:"transparent",border:"0",clipPath:Ie(e,t,n),colorScheme:"normal",height:n&&e.open&&o?`${o.height}px`:"100dvh",inset:n&&e.open&&o?`${o.offsetTop}px 0 auto`:"0",position:"fixed",width:"100vw",zIndex:t.appearance?.zIndex??40}}function de(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.open!="boolean"||typeof t.ready!="boolean"||typeof t.expanded!="boolean"||t.viewMode!=="chat-bar"&&t.viewMode!=="floating"&&t.viewMode!=="sidebar"?null:{bounds:ke(t.bounds),closing:t.closing===!0,dragging:t.dragging===!0,expanded:t.expanded,mounted:t.mounted!==!1,open:t.open,overlayOpen:t.overlayOpen===!0,ready:t.ready,resizing:t.resizing===!0,sidebarWidth:U(t.sidebarWidth)?t.sidebarWidth:null,viewMode:t.viewMode}}function ce(){let e=document.documentElement,t=document.body;return{active:!1,body:t,original:{bodyLeft:t.style.left,bodyOverflow:t.style.overflow,bodyPosition:t.style.position,bodyRight:t.style.right,bodyTop:t.style.top,bodyWidth:t.style.width,rootMarginRight:e.style.marginRight,rootOverflow:e.style.overflow,rootTransition:e.style.transition},root:e,scrollLock:null}}function P(e,t,n,o){let s=t.open||t.closing;if(!s&&!e.active)return;s&&(e.active=!0);let u=s&&(t.viewMode==="chat-bar"?t.expanded:o||t.viewMode==="sidebar"&&t.expanded);pe(e,u);let l=s&&t.viewMode==="sidebar"&&!t.expanded&&!o?Se(t,n):e.original.rootMarginRight;e.root.style.transition=e.original.rootTransition,e.root.style.marginRight=l,s||(e.active=!1)}function ue(e){pe(e,!1),e.root.style.marginRight=e.original.rootMarginRight,e.root.style.transition=e.original.rootTransition,e.active=!1}function Ie(e,t,n){let o=e.open||e.closing;if(o&&(e.overlayOpen||n&&e.viewMode!=="chat-bar"))return"inset(0px)";if(e.bounds)return`inset(${e.bounds.top}px calc(100% - ${e.bounds.right}px) calc(100% - ${e.bounds.bottom}px) ${e.bounds.left}px)`;if(e.viewMode==="chat-bar"){if(e.expanded&&o)return"inset(0px)";let w=o?"calc(100% - min(610px, calc(100dvh - 20px)))":"calc(100% - 114px)",v=o?"calc(50% - min(288px, 50%))":"calc(50% - min(228px, 50%))";return`inset(${w} ${v} 0px ${v})`}let s=t.appearance?.launcher,u=s?.position==="bottom-left",f=(s?.offset?.x??24)+60,l=(s?.offset?.y??24)+60;if(!o)return u?`inset(calc(100% - ${l}px) calc(100% - ${f}px) 0px 0px)`:`inset(calc(100% - ${l}px) 0px 0px calc(100% - ${f}px))`;if(e.viewMode==="sidebar")return`inset(0px 0px 0px calc(100% - (${D(t.appearance?.panel?.initialWidth??420)} + 16px)))`;let g=D(t.appearance?.panel?.initialWidth??440),E=`calc(100% - min(calc(${D(t.appearance?.panel?.initialHeight??"max(420px, 56dvh)")} + 32px), 100dvh))`;return u?`inset(${E} calc(100% - min(calc(${g} + 32px), 100vw)) 0px 0px)`:`inset(${E} 0px 0px calc(100% - min(calc(${g} + 32px), 100vw)))`}function ke(e){if(!e||typeof e!="object")return null;let t=e;return!U(t.top)||!U(t.right)||!U(t.bottom)||!U(t.left)||t.right<t.left||t.bottom<t.top?null:{bottom:t.bottom,left:t.left,right:t.right,top:t.top}}function U(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1e5}function Se(e,t){return e.sidebarWidth===null?D(t.appearance?.panel?.initialWidth??420):`${Math.round(e.sidebarWidth)}px`}function D(e){return typeof e=="number"?`${Math.round(e)}px`:e}function pe(e,t){if(t&&!e.scrollLock){e.scrollLock={x:window.scrollX,y:window.scrollY},e.root.style.overflow="hidden",e.body.style.overflow="hidden",e.body.style.position="fixed",e.body.style.top=`${-e.scrollLock.y}px`,e.body.style.left=`${-e.scrollLock.x}px`,e.body.style.right="0",e.body.style.width="100%";return}if(!t&&e.scrollLock){let{x:n,y:o}=e.scrollLock;e.root.style.overflow=e.original.rootOverflow,e.body.style.overflow=e.original.bodyOverflow,e.body.style.position=e.original.bodyPosition,e.body.style.top=e.original.bodyTop,e.body.style.left=e.original.bodyLeft,e.body.style.right=e.original.bodyRight,e.body.style.width=e.original.bodyWidth,e.scrollLock=null;try{window.scrollTo(n,o)}catch{}}}var Le=16*1024;function et(e,t){let n=e;if(!n?.agentId||typeof n.getAuthToken!="function")throw new Error("HeroUIAgent.mount requires agentId and getAuthToken");G(n.tools??[]);let o=crypto.randomUUID(),s=crypto.randomUUID(),u=(n._api?.baseUrl??te).replace(/\/$/,""),f=Ue(u,n._api?.embedOrigin),l=document.createElement("iframe"),g=new Map,b=[],E=new Set,w=new Map,v=new Set,I=ce(),T=new M(n.agentId,n.getAuthToken),a=le(n),F=null,y=!1,x=!1,k=null,q=!1,S=!1,j=n.preload!==!1,C=()=>{S||T.get().catch(()=>{})},z=new URL("/embed",f);z.searchParams.set("agentId",n.agentId),z.hash=new URLSearchParams({nonce:s,parentOrigin:window.location.origin,sessionId:o}).toString(),l.allow="microphone; clipboard-write",l.referrerPolicy="origin",l.setAttribute("sandbox","allow-downloads allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),l.src=z.toString(),l.title="HeroUI Agent",Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),document.body.append(l);let m=(r,i,d)=>{S||l.contentWindow?.postMessage(re(o,s,r,i,d),f)},fe=(r,i)=>{let d=crypto.randomUUID();return new Promise((c,p)=>{let h=window.setTimeout(()=>{g.delete(d),p(new Error(`HeroUI Agent iframe request timed out: ${r}`))},3e4);g.set(d,{reject:p,resolve:c,timer:h}),m(r,i,d)})},_=new Map,J=0,Y="",N=!1,K=async(r,i=!1)=>{let d=++J;if(N)return;let c;try{c=await He(n,t)}catch(h){if(S||d!==J)return;N=!0;let O={...X(h,"failed"),category:"configuration",message:h instanceof Error?h.message.slice(0,1e3):"Invalid agent configuration",retryable:!1};n.onError?.(O),m("host.init-error",O);return}if(S||d!==J)return;let p=JSON.stringify({props:c.props,tools:c.tools});!i&&p===Y||(Y=p,m(r,{...c,restoreSession:r==="host.init"&&x}))},R=(r,i)=>{if(!a.mounted){b.push({name:r,payload:i}),b.length>32&&b.shift();return}m("host.command",{name:r,payload:i})},W=r=>{r&&C(),r&&!y&&document.activeElement!==l&&(F=document.activeElement),y=r,r||(x=!1),R(r?"show":"hide")},me=()=>{if(a.mounted)for(let r of b.splice(0))m("host.command",r)},he=()=>{x=a.mounted&&y&&!a.closing,a={...a,bounds:null,closing:!1,mounted:!1,open:x,ready:!1},q=!1;for(let r of v)r();Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640)},Z=r=>{if(r.origin!==f||r.source!==l.contentWindow)return;let i=ie(r.data);if(!(!i||i.sessionId!==o||i.nonce!==s)){if(i.type==="iframe.rpc-result"||i.type==="iframe.rpc-error"){Pe(i,g);return}Me(E,i.requestId)&&we(i)}},we=async r=>{try{if(r.type==="iframe.ready"){(a.mounted||a.ready)&&he(),await K("host.init",!0);return}if(r.type==="iframe.reload"){let i=l.cloneNode(!1),d=new URL(l.src);d.pathname=`/reload/${crypto.randomUUID()}/embed`,i.src=d.href,l.replaceWith(i),l=i;return}if(r.type==="iframe.state"){let i=de(r.payload);if(i){let d=a.mounted,c=a.open||a.closing,p=i;x?i.mounted?(x=!1,i.open||(m("host.command",{name:"show"}),p={...i,bounds:null,closing:!1,open:!0,sidebarWidth:i.sidebarWidth??a.sidebarWidth})):p={...i,bounds:null,closing:!1,open:!0,sidebarWidth:i.sidebarWidth??a.sidebarWidth}:i.open?y=!0:(i.closing||a.open||a.closing)&&(y=!1);let h=p.open||p.closing;if(h&&!c&&document.activeElement!==l&&(F=document.activeElement),!h&&c&&F?.isConnected){let O=F;window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>O.focus({preventScroll:!0})))}h!==c&&n.onOpenChange?.(h),a=p,a.mounted&&!d&&K("host.update"),h&&a.expanded?l.dataset.expanded="true":l.removeAttribute("data-expanded");for(let O of v)O();Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640),me(),a.ready&&!q&&(q=!0,n.onReady?.())}return}if(r.type==="iframe.error"){n.onError?.(r.payload);return}if(r.type==="iframe.status"){n.onStatusChange?.(r.payload);return}if(r.type==="iframe.tool-cancel"){let i=r.payload;i.idempotencyKey&&_.get(i.idempotencyKey)?.abort();return}if(r.type==="iframe.auth-request"){let i=await T.get(),d=await V(15e3,c=>fetch(`${u}/v1/agents/${encodeURIComponent(n.agentId)}/embed-sessions`,{body:JSON.stringify({iframeOrigin:f,sessionId:o}),cache:"no-store",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},method:"POST",signal:c}));if(!d.ok)throw new Error("Could not authenticate HeroUI Agent");m("host.rpc-result",{value:await d.json()},r.requestId);return}if(r.type==="iframe.context-request"){let i=_e(await n.context?.page?.()??{},Le,"Agent page context");m("host.rpc-result",{value:i},r.requestId);return}if(r.type==="iframe.tool-execute"){let i=Ce(r.payload),d=n.tools?.find(p=>p.name===i.name);if(!d)throw new Error(`Unknown client tool: ${i.name}`);let c=w.get(i.idempotencyKey);if(!c){let p=new AbortController;_.set(i.idempotencyKey,p),c=Oe(d,i,n,fe,p.signal).finally(()=>_.delete(i.idempotencyKey)),w.set(i.idempotencyKey,c),w.size>2048&&w.delete(w.keys().next().value)}m("host.rpc-result",{value:await c},r.requestId);return}if(r.type==="iframe.feedback"){await n.onFeedback?.(r.payload);return}if(r.type==="iframe.storage"){Re(r.payload);return}if(r.type==="iframe.persistence"){let i=await import("./persistence-YI6JSYCT.js").then(({executeAgentHostPersistence:d})=>d(n.agentId,r.payload));m("host.rpc-result",{value:i},r.requestId)}}catch(i){if(S)return;let d=X(i,r.type==="iframe.auth-request"?"authenticating":"failed"),c=r.type==="iframe.tool-execute",p=c&&i instanceof Error?i.message.slice(0,1e3):d.message;n.onError?.({...d,message:p}),m("host.rpc-error",{error:p,...c?{code:i instanceof H?i.code:"CLIENT_TOOL_EXECUTION_ERROR"}:{}},r.requestId)}},Q=r=>{r.composedPath().includes(l)||a.open&&(a.viewMode==="floating"||a.viewMode==="chat-bar")&&(n.appearance?.shouldCloseOnInteractOutside??!0)&&W(!1)},L=()=>{a={...a,bounds:null},Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640)},$=()=>{document.visibilityState==="visible"&&(a={...a,bounds:null},Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640),y&&a.mounted&&m("host.command",{name:"show"}),k!==null&&window.cancelAnimationFrame(k),k=window.requestAnimationFrame(()=>{k=null,Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0))}))};return window.addEventListener("message",Z),window.addEventListener("pointerdown",Q,!0),window.addEventListener("resize",L),window.addEventListener("pageshow",$),window.visualViewport?.addEventListener("resize",L),window.visualViewport?.addEventListener("scroll",L),document.addEventListener("visibilitychange",$),j&&C(),{destroy:()=>{S=!0,T.clear();for(let r of _.values())r.abort();_.clear(),window.removeEventListener("message",Z),window.removeEventListener("pointerdown",Q,!0),window.removeEventListener("resize",L),window.removeEventListener("pageshow",$),window.visualViewport?.removeEventListener("resize",L),window.visualViewport?.removeEventListener("scroll",L),document.removeEventListener("visibilitychange",$),k!==null&&window.cancelAnimationFrame(k);for(let r of g.values())window.clearTimeout(r.timer),r.reject(new Error("HeroUI Agent iframe was removed"));g.clear(),b.length=0,v.clear(),ue(I),l.remove()},hide:()=>W(!1),newConversation:r=>{C(),y=!0,R("newConversation",{prompt:r})},preload:()=>{C(),R("preload")},get ready(){return a.ready},refreshAuth:()=>{T.clear(),R("refreshAuth")},show:()=>W(!0),shutdown:()=>{y=!1,x=!1,T.reset(),R("shutdown")},subscribe:r=>(v.add(r),()=>v.delete(r)),toggle:()=>W(!y),update:r=>{if(r.agentId!==n.agentId)throw new Error("HeroUI Agent agentId cannot change without remounting");G(r.tools??[]);let i=N;N=!1;let d=r.getAuthToken!==n.getAuthToken,c=r.preload!==!1&&(d||!j);j=r.preload!==!1,d&&(T.clear(),T=new M(r.agentId,r.getAuthToken)),n=r,c&&C(),Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640),(a.mounted||i)&&K(a.mounted?"host.update":"host.init")}}}async function Oe(e,t,n,o,s){let u={conversationId:t.conversationId,idempotencyKey:t.idempotencyKey,signal:s,toolCallId:t.toolCallId,uploadDataSource:async g=>await o("host.upload-data-source",{toolCallId:t.toolCallId,upload:g})},f;try{f=ee(e,t.args)}catch(g){return{code:"CLIENT_TOOL_INVALID_INPUT",...Fe(g),error:`The arguments for ${e.name} do not match its declared schema. Correct the input and try again. No action was performed.`,success:!1}}let l=await e.execute(f,n.context??{},u)??null;return se(l)}async function He(e,t){let{context:n,getAuthToken:o,onError:s,onFeedback:u,onOpenChange:f,onReady:l,onStatusChange:g,tools:b,...E}=e,w=await t(b??[]);return{localStorage:ge(window.localStorage),props:JSON.parse(JSON.stringify(E)),sessionStorage:ge(window.sessionStorage),tools:w}}function Pe(e,t){let n=t.get(e.requestId);if(n)if(t.delete(e.requestId),window.clearTimeout(n.timer),e.type==="iframe.rpc-error"){let o=e.payload;n.reject(new Error(typeof o?.error=="string"?o.error:"Iframe request failed"))}else{let o=e.payload;n.resolve(o?.value)}}function Ce(e){if(!e||typeof e!="object")throw new Error("Invalid client tool request");let t=e;if(typeof t.conversationId!="string"||typeof t.idempotencyKey!="string"||typeof t.name!="string"||typeof t.toolCallId!="string")throw new Error("Invalid client tool request");return t}function _e(e,t,n){if(!B(e))throw new Error(`${n} must be JSON-serializable`);let o=JSON.stringify(e);if(new TextEncoder().encode(o).byteLength>t)throw new Error(`${n} exceeds ${Math.round(t/1024)} KiB`);return JSON.parse(o)}function ge(e){let t={};try{for(let n=0;n<e.length;n+=1){let o=e.key(n);o?.startsWith("heroui-agent:")&&(t[o]=e.getItem(o)??"")}}catch{}return t}function Re(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.key=="string"&&!t.key.startsWith("heroui-agent:"))return;let n=t.storage==="session"?sessionStorage:localStorage;try{if(t.operation==="set"&&typeof t.key=="string"&&typeof t.value=="string")n.setItem(t.key,t.value);else if(t.operation==="remove"&&typeof t.key=="string")n.removeItem(t.key);else if(t.operation==="clear")for(let o=n.length-1;o>=0;o-=1){let s=n.key(o);s?.startsWith("heroui-agent:")&&n.removeItem(s)}}catch{}}function Me(e,t){return e.has(t)?!1:(e.add(t),e.size>2048&&e.delete(e.values().next().value),!0)}function Ue(e,t){if(t){let n=new URL(t);if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error("HeroUI Agent embed origin must use HTTP or HTTPS");return n.origin}return/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/i.test(e)?"http://localhost:8793":e.includes("staging")?oe:ne}function Fe(e){if(!e||typeof e!="object"||!("issues"in e)||!Array.isArray(e.issues))return{};let t=e.issues.slice(0,8).flatMap(n=>{if(!n||typeof n!="object")return[];let o=n;return!Array.isArray(o.path)||typeof o.code!="string"?[]:[{code:o.code.slice(0,60),path:o.path.filter(s=>typeof s=="string"||typeof s=="number").join(".").slice(0,200),...typeof o.minimum=="number"&&Number.isFinite(o.minimum)?{minimum:o.minimum}:{},...typeof o.maximum=="number"&&Number.isFinite(o.maximum)?{maximum:o.maximum}:{},...typeof o.expected=="string"?{expected:o.expected.slice(0,100)}:{}}]});return t.length?{issues:t}:{}}export{ye as a,V as b,X as c,M as d,H as e,se as f,et as g};
|
|
1
|
+
import{b as te}from"./chunk-QSLALU5G.js";import{c as ee,h as G,i as ne,j as oe,m as re,n as ie,o as B}from"./chunk-FZXNXBTZ.js";function ye(e,t){return e.throwIfAborted(),new Promise((n,o)=>{let s=()=>o(e.reason);e.addEventListener("abort",s,{once:!0});try{t().then(n,o).finally(()=>e.removeEventListener("abort",s))}catch(u){e.removeEventListener("abort",s),o(u)}})}async function V(e,t,n){let o=new AbortController,s=setTimeout(()=>o.abort(new DOMException("Request timed out","TimeoutError")),e),u=n?AbortSignal.any([n,o.signal]):o.signal;try{return await ye(u,()=>t(u))}finally{clearTimeout(s)}}var be={approval:"This approval has expired. Ask the agent to request it again.",authentication:"Could not authenticate. Sign in if needed, then retry.",chunk:"Could not load the conversation. Retry, or reload the panel.",configuration:"Could not load the agent configuration. Try again.",connection:"Connection interrupted. Completed page changes remain applied. Reconnect to continue this chat.",credits:"This agent has reached its usage limit.",deleted:"This conversation was deleted. Start a new conversation.",rate_limit:"Too many requests. Wait a moment before retrying.",unknown:"The request could not be completed. Try again."},ve="Too many conversations are active. Wait a few minutes, then retry this chat.";function X(e,t="connecting"){let n=e&&typeof e=="object"?e:{},o=[e instanceof Error?e.message:"",n.code,n.status].filter(u=>typeof u=="string"||typeof u=="number").join(" ").toLowerCase(),s=t==="authenticating"||/auth|401|sign.in/.test(o)?"authentication":/429|rate.limit|concurrency_limit|too many conversations are active/.test(o)?"rate_limit":/credit|usage.limit|usage_limit|402/.test(o)?"credits":/deleted|conversation_not_found/.test(o)?"deleted":/approval.*expir/.test(o)?"approval":/dynamic.*import|chunk|module.*fetch/.test(o)?"chunk":/config/.test(o)?"configuration":/network|fetch|connect|timeout|timed out/.test(o)?"connection":"unknown";return{category:s,diagnosticId:crypto.randomUUID(),message:/concurrency_limit|too many conversations are active/.test(o)?ve:be[s],phase:t,retryable:!["credits","deleted","approval"].includes(s)}}var Ae=5e3;function ae(e){return`heroui-agent:anonymous:${e}`}function Te(e){return e instanceof Error?e:new Error("Auth token request failed")}var M=class{constructor(t,n){this.agentId=t;this.getAuthToken=n}cached=null;failure=null;generation=0;pending=null;controller=new AbortController;clear(){this.controller.abort(),this.controller=new AbortController,this.generation+=1,this.cached=null,this.failure=null,this.pending=null}reset(){this.clear();try{localStorage.removeItem(ae(this.agentId))}catch{}}async get(){if(this.cached&&this.expiresAt(this.cached)>Date.now()+6e4)return this.cached.token;if(!this.pending&&this.failure&&Date.now()<this.failure.retryAt)throw this.failure.error;let t=this.generation,n=this.pending??this.refresh();this.pending||(this.pending=n);try{let o=await n;return t!==this.generation?this.get():(this.cached=o,this.failure=null,o.token)}catch(o){throw t===this.generation&&(this.failure={error:Te(o),retryAt:Date.now()+Ae}),o}finally{this.pending===n&&(this.pending=null)}}async subjectHash(){let t=await this.get(),n=xe(t),o=typeof n.sub=="string"?n.sub:"anonymous",s=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${this.agentId}:${o}`));return Array.from(new Uint8Array(s),u=>u.toString(16).padStart(2,"0")).join("").slice(0,24)}anonymousId(){let t=ae(this.agentId);try{let n=localStorage.getItem(t);if(n)return n;let o=crypto.randomUUID();return localStorage.setItem(t,o),o}catch{return crypto.randomUUID()}}expiresAt(t){return t.expiresAt}async refresh(){let t=await V(15e3,n=>this.getAuthToken({agentId:this.agentId,anonymousId:this.anonymousId(),signal:n}),this.controller.signal);if(!t||typeof t.token!="string"||!t.token.trim()||typeof t.expiresAt!="number"||!Number.isFinite(t.expiresAt)||t.expiresAt<=0)throw new Error("Auth token callback returned invalid data");return{expiresAt:t.expiresAt,token:t.token}}};function xe(e){try{let t=e.split(".")[1];if(!t)return{};let n=t.replace(/-/g,"+").replace(/_/g,"/"),o=n.padEnd(Math.ceil(n.length/4)*4,"=");return JSON.parse(atob(o))}catch{return{}}}var Ee=64*1024,H=class extends Error{constructor(n,o){super(o);this.code=n}};function se(e){let t;try{let n=e??null;if(!B(n))throw new Error("Not a JSON value");t=JSON.stringify(n)}catch{throw new H("CLIENT_TOOL_RESULT_NOT_SERIALIZABLE","The client tool returned a result that is not JSON-serializable. Return plain JSON values; convert Map and Date values explicitly and remove circular references. The tool already ran; do not repeat an action without checking its outcome.")}if(new TextEncoder().encode(t).byteLength>Ee)throw new H("CLIENT_TOOL_RESULT_TOO_LARGE","The client tool result exceeds the 64 KiB limit. Request fewer rows or fields, paginate the data, or use uploadDataSource for a larger dataset. The tool already ran; do not repeat an action without checking its outcome.");return JSON.parse(t)}function le(e){return{bounds:null,closing:!1,dragging:!1,expanded:e.appearance?.panel?.expanded??!1,mounted:!1,open:!1,overlayOpen:!1,ready:!1,resizing:!1,sidebarWidth:null,viewMode:e.appearance?.viewMode??"floating"}}function A(e,t,n,o){return{background:"transparent",border:"0",clipPath:Ie(e,t,n),colorScheme:"normal",height:n&&e.open&&o?`${o.height}px`:"100dvh",inset:n&&e.open&&o?`${o.offsetTop}px 0 auto`:"0",position:"fixed",width:"100vw",zIndex:t.appearance?.zIndex??40}}function de(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.open!="boolean"||typeof t.ready!="boolean"||typeof t.expanded!="boolean"||t.viewMode!=="chat-bar"&&t.viewMode!=="floating"&&t.viewMode!=="sidebar"?null:{bounds:ke(t.bounds),closing:t.closing===!0,dragging:t.dragging===!0,expanded:t.expanded,mounted:t.mounted!==!1,open:t.open,overlayOpen:t.overlayOpen===!0,ready:t.ready,resizing:t.resizing===!0,sidebarWidth:U(t.sidebarWidth)?t.sidebarWidth:null,viewMode:t.viewMode}}function ce(){let e=document.documentElement,t=document.body;return{active:!1,body:t,original:{bodyLeft:t.style.left,bodyOverflow:t.style.overflow,bodyPosition:t.style.position,bodyRight:t.style.right,bodyTop:t.style.top,bodyWidth:t.style.width,rootMarginRight:e.style.marginRight,rootOverflow:e.style.overflow,rootTransition:e.style.transition},root:e,scrollLock:null}}function P(e,t,n,o){let s=t.open||t.closing;if(!s&&!e.active)return;s&&(e.active=!0);let u=s&&(t.viewMode==="chat-bar"?t.expanded:o||t.viewMode==="sidebar"&&t.expanded);pe(e,u);let l=s&&t.viewMode==="sidebar"&&!t.expanded&&!o?Se(t,n):e.original.rootMarginRight;e.root.style.transition=e.original.rootTransition,e.root.style.marginRight=l,s||(e.active=!1)}function ue(e){pe(e,!1),e.root.style.marginRight=e.original.rootMarginRight,e.root.style.transition=e.original.rootTransition,e.active=!1}function Ie(e,t,n){let o=e.open||e.closing;if(o&&(e.overlayOpen||n&&e.viewMode!=="chat-bar"))return"inset(0px)";if(e.bounds)return`inset(${e.bounds.top}px calc(100% - ${e.bounds.right}px) calc(100% - ${e.bounds.bottom}px) ${e.bounds.left}px)`;if(e.viewMode==="chat-bar"){if(e.expanded&&o)return"inset(0px)";let w=o?"calc(100% - min(610px, calc(100dvh - 20px)))":"calc(100% - 114px)",v=o?"calc(50% - min(288px, 50%))":"calc(50% - min(228px, 50%))";return`inset(${w} ${v} 0px ${v})`}let s=t.appearance?.launcher,u=s?.position==="bottom-left",f=(s?.offset?.x??24)+60,l=(s?.offset?.y??24)+60;if(!o)return u?`inset(calc(100% - ${l}px) calc(100% - ${f}px) 0px 0px)`:`inset(calc(100% - ${l}px) 0px 0px calc(100% - ${f}px))`;if(e.viewMode==="sidebar")return`inset(0px 0px 0px calc(100% - (${D(t.appearance?.panel?.initialWidth??420)} + 16px)))`;let g=D(t.appearance?.panel?.initialWidth??440),E=`calc(100% - min(calc(${D(t.appearance?.panel?.initialHeight??"max(420px, 56dvh)")} + 32px), 100dvh))`;return u?`inset(${E} calc(100% - min(calc(${g} + 32px), 100vw)) 0px 0px)`:`inset(${E} 0px 0px calc(100% - min(calc(${g} + 32px), 100vw)))`}function ke(e){if(!e||typeof e!="object")return null;let t=e;return!U(t.top)||!U(t.right)||!U(t.bottom)||!U(t.left)||t.right<t.left||t.bottom<t.top?null:{bottom:t.bottom,left:t.left,right:t.right,top:t.top}}function U(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1e5}function Se(e,t){return e.sidebarWidth===null?D(t.appearance?.panel?.initialWidth??420):`${Math.round(e.sidebarWidth)}px`}function D(e){return typeof e=="number"?`${Math.round(e)}px`:e}function pe(e,t){if(t&&!e.scrollLock){e.scrollLock={x:window.scrollX,y:window.scrollY},e.root.style.overflow="hidden",e.body.style.overflow="hidden",e.body.style.position="fixed",e.body.style.top=`${-e.scrollLock.y}px`,e.body.style.left=`${-e.scrollLock.x}px`,e.body.style.right="0",e.body.style.width="100%";return}if(!t&&e.scrollLock){let{x:n,y:o}=e.scrollLock;e.root.style.overflow=e.original.rootOverflow,e.body.style.overflow=e.original.bodyOverflow,e.body.style.position=e.original.bodyPosition,e.body.style.top=e.original.bodyTop,e.body.style.left=e.original.bodyLeft,e.body.style.right=e.original.bodyRight,e.body.style.width=e.original.bodyWidth,e.scrollLock=null;try{window.scrollTo(n,o)}catch{}}}var Le=16*1024;function et(e,t){let n=e;if(!n?.agentId||typeof n.getAuthToken!="function")throw new Error("HeroUIAgent.mount requires agentId and getAuthToken");G(n.tools??[]);let o=crypto.randomUUID(),s=crypto.randomUUID(),u=(n._api?.baseUrl??te).replace(/\/$/,""),f=Ue(u,n._api?.embedOrigin),l=document.createElement("iframe"),g=new Map,b=[],E=new Set,w=new Map,v=new Set,I=ce(),T=new M(n.agentId,n.getAuthToken),a=le(n),F=null,y=!1,x=!1,k=null,q=!1,S=!1,j=n.preload!==!1,C=()=>{S||T.get().catch(()=>{})},z=new URL("/embed",f);z.searchParams.set("agentId",n.agentId),z.hash=new URLSearchParams({nonce:s,parentOrigin:window.location.origin,sessionId:o}).toString(),l.allow="microphone; clipboard-write",l.referrerPolicy="origin",l.setAttribute("sandbox","allow-downloads allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),l.src=z.toString(),l.title="HeroUI Agent",Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),document.body.append(l);let m=(r,i,d)=>{S||l.contentWindow?.postMessage(re(o,s,r,i,d),f)},fe=(r,i)=>{let d=crypto.randomUUID();return new Promise((c,p)=>{let h=window.setTimeout(()=>{g.delete(d),p(new Error(`HeroUI Agent iframe request timed out: ${r}`))},3e4);g.set(d,{reject:p,resolve:c,timer:h}),m(r,i,d)})},_=new Map,J=0,Y="",N=!1,K=async(r,i=!1)=>{let d=++J;if(N)return;let c;try{c=await He(n,t)}catch(h){if(S||d!==J)return;N=!0;let O={...X(h,"failed"),category:"configuration",message:h instanceof Error?h.message.slice(0,1e3):"Invalid agent configuration",retryable:!1};n.onError?.(O),m("host.init-error",O);return}if(S||d!==J)return;let p=JSON.stringify({props:c.props,tools:c.tools});!i&&p===Y||(Y=p,m(r,{...c,restoreSession:r==="host.init"&&x}))},R=(r,i)=>{if(!a.mounted){b.push({name:r,payload:i}),b.length>32&&b.shift();return}m("host.command",{name:r,payload:i})},W=r=>{r&&C(),r&&!y&&document.activeElement!==l&&(F=document.activeElement),y=r,r||(x=!1),R(r?"show":"hide")},me=()=>{if(a.mounted)for(let r of b.splice(0))m("host.command",r)},he=()=>{x=a.mounted&&y&&!a.closing,a={...a,bounds:null,closing:!1,mounted:!1,open:x,ready:!1},q=!1;for(let r of v)r();Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640)},Z=r=>{if(r.origin!==f||r.source!==l.contentWindow)return;let i=ie(r.data);if(!(!i||i.sessionId!==o||i.nonce!==s)){if(i.type==="iframe.rpc-result"||i.type==="iframe.rpc-error"){Pe(i,g);return}Me(E,i.requestId)&&we(i)}},we=async r=>{try{if(r.type==="iframe.ready"){(a.mounted||a.ready)&&he(),await K("host.init",!0);return}if(r.type==="iframe.reload"){let i=l.cloneNode(!1),d=new URL(l.src);d.pathname=`/reload/${crypto.randomUUID()}/embed`,i.src=d.href,l.replaceWith(i),l=i;return}if(r.type==="iframe.state"){let i=de(r.payload);if(i){let d=a.mounted,c=a.open||a.closing,p=i;x?i.mounted?(x=!1,i.open||(m("host.command",{name:"show"}),p={...i,bounds:null,closing:!1,open:!0,sidebarWidth:i.sidebarWidth??a.sidebarWidth})):p={...i,bounds:null,closing:!1,open:!0,sidebarWidth:i.sidebarWidth??a.sidebarWidth}:i.open?y=!0:(i.closing||a.open||a.closing)&&(y=!1);let h=p.open||p.closing;if(h&&!c&&document.activeElement!==l&&(F=document.activeElement),!h&&c&&F?.isConnected){let O=F;window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>O.focus({preventScroll:!0})))}h!==c&&n.onOpenChange?.(h),a=p,a.mounted&&!d&&K("host.update"),h&&a.expanded?l.dataset.expanded="true":l.removeAttribute("data-expanded");for(let O of v)O();Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640),me(),a.ready&&!q&&(q=!0,n.onReady?.())}return}if(r.type==="iframe.error"){n.onError?.(r.payload);return}if(r.type==="iframe.status"){n.onStatusChange?.(r.payload);return}if(r.type==="iframe.tool-cancel"){let i=r.payload;i.idempotencyKey&&_.get(i.idempotencyKey)?.abort();return}if(r.type==="iframe.auth-request"){let i=await T.get(),d=await V(15e3,c=>fetch(`${u}/v1/agents/${encodeURIComponent(n.agentId)}/embed-sessions`,{body:JSON.stringify({iframeOrigin:f,sessionId:o}),cache:"no-store",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},method:"POST",signal:c}));if(!d.ok)throw new Error("Could not authenticate HeroUI Agent");m("host.rpc-result",{value:await d.json()},r.requestId);return}if(r.type==="iframe.context-request"){let i=_e(await n.context?.page?.()??{},Le,"Agent page context");m("host.rpc-result",{value:i},r.requestId);return}if(r.type==="iframe.tool-execute"){let i=Ce(r.payload),d=n.tools?.find(p=>p.name===i.name);if(!d)throw new Error(`Unknown client tool: ${i.name}`);let c=w.get(i.idempotencyKey);if(!c){let p=new AbortController;_.set(i.idempotencyKey,p),c=Oe(d,i,n,fe,p.signal).finally(()=>_.delete(i.idempotencyKey)),w.set(i.idempotencyKey,c),w.size>2048&&w.delete(w.keys().next().value)}m("host.rpc-result",{value:await c},r.requestId);return}if(r.type==="iframe.feedback"){await n.onFeedback?.(r.payload);return}if(r.type==="iframe.storage"){Re(r.payload);return}if(r.type==="iframe.persistence"){let i=await import("./persistence-YI6JSYCT.js").then(({executeAgentHostPersistence:d})=>d(n.agentId,r.payload));m("host.rpc-result",{value:i},r.requestId)}}catch(i){if(S)return;let d=X(i,r.type==="iframe.auth-request"?"authenticating":"failed"),c=r.type==="iframe.tool-execute",p=c&&i instanceof Error?i.message.slice(0,1e3):d.message;n.onError?.({...d,message:p}),m("host.rpc-error",{error:p,...c?{code:i instanceof H?i.code:"CLIENT_TOOL_EXECUTION_ERROR"}:{}},r.requestId)}},Q=r=>{r.composedPath().includes(l)||a.open&&(a.viewMode==="floating"||a.viewMode==="chat-bar")&&(n.appearance?.shouldCloseOnInteractOutside??!0)&&W(!1)},L=()=>{a={...a,bounds:null},Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640)},$=()=>{document.visibilityState==="visible"&&(a={...a,bounds:null},Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640),y&&a.mounted&&m("host.command",{name:"show"}),k!==null&&window.cancelAnimationFrame(k),k=window.requestAnimationFrame(()=>{k=null,Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0))}))};return window.addEventListener("message",Z),window.addEventListener("pointerdown",Q,!0),window.addEventListener("resize",L),window.addEventListener("pageshow",$),window.visualViewport?.addEventListener("resize",L),window.visualViewport?.addEventListener("scroll",L),document.addEventListener("visibilitychange",$),j&&C(),{destroy:()=>{S=!0,T.clear();for(let r of _.values())r.abort();_.clear(),window.removeEventListener("message",Z),window.removeEventListener("pointerdown",Q,!0),window.removeEventListener("resize",L),window.removeEventListener("pageshow",$),window.visualViewport?.removeEventListener("resize",L),window.visualViewport?.removeEventListener("scroll",L),document.removeEventListener("visibilitychange",$),k!==null&&window.cancelAnimationFrame(k);for(let r of g.values())window.clearTimeout(r.timer),r.reject(new Error("HeroUI Agent iframe was removed"));g.clear(),b.length=0,v.clear(),ue(I),l.remove()},hide:()=>W(!1),newConversation:r=>{C(),y=!0,R("newConversation",{prompt:r})},preload:()=>{C(),R("preload")},get ready(){return a.ready},refreshAuth:()=>{T.clear(),R("refreshAuth")},show:()=>W(!0),shutdown:()=>{y=!1,x=!1,T.reset(),R("shutdown")},subscribe:r=>(v.add(r),()=>v.delete(r)),toggle:()=>W(!y),update:r=>{if(r.agentId!==n.agentId)throw new Error("HeroUI Agent agentId cannot change without remounting");G(r.tools??[]);let i=N;N=!1;let d=r.getAuthToken!==n.getAuthToken,c=r.preload!==!1&&(d||!j);j=r.preload!==!1,d&&(T.clear(),T=new M(r.agentId,r.getAuthToken)),n=r,c&&C(),Object.assign(l.style,A(a,n,window.innerWidth<640,window.visualViewport?.scale===1?window.visualViewport:void 0)),P(I,a,n,window.innerWidth<640),(a.mounted||i)&&K(a.mounted?"host.update":"host.init")}}}async function Oe(e,t,n,o,s){let u={conversationId:t.conversationId,idempotencyKey:t.idempotencyKey,signal:s,toolCallId:t.toolCallId,uploadDataSource:async g=>await o("host.upload-data-source",{toolCallId:t.toolCallId,upload:g})},f;try{f=ee(e,t.args)}catch(g){return{code:"CLIENT_TOOL_INVALID_INPUT",...Fe(g),error:`The arguments for ${e.name} do not match its declared schema. Correct the input and try again. No action was performed.`,success:!1}}let l=await e.execute(f,n.context??{},u)??null;return se(l)}async function He(e,t){let{context:n,getAuthToken:o,onError:s,onFeedback:u,onOpenChange:f,onReady:l,onStatusChange:g,tools:b,...E}=e,w=await t(b??[]);return{localStorage:ge(window.localStorage),props:JSON.parse(JSON.stringify(E)),sessionStorage:ge(window.sessionStorage),tools:w}}function Pe(e,t){let n=t.get(e.requestId);if(n)if(t.delete(e.requestId),window.clearTimeout(n.timer),e.type==="iframe.rpc-error"){let o=e.payload;n.reject(new Error(typeof o?.error=="string"?o.error:"Iframe request failed"))}else{let o=e.payload;n.resolve(o?.value)}}function Ce(e){if(!e||typeof e!="object")throw new Error("Invalid client tool request");let t=e;if(typeof t.conversationId!="string"||typeof t.idempotencyKey!="string"||typeof t.name!="string"||typeof t.toolCallId!="string")throw new Error("Invalid client tool request");return t}function _e(e,t,n){if(!B(e))throw new Error(`${n} must be JSON-serializable`);let o=JSON.stringify(e);if(new TextEncoder().encode(o).byteLength>t)throw new Error(`${n} exceeds ${Math.round(t/1024)} KiB`);return JSON.parse(o)}function ge(e){let t={};try{for(let n=0;n<e.length;n+=1){let o=e.key(n);o?.startsWith("heroui-agent:")&&(t[o]=e.getItem(o)??"")}}catch{}return t}function Re(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.key=="string"&&!t.key.startsWith("heroui-agent:"))return;let n=t.storage==="session"?sessionStorage:localStorage;try{if(t.operation==="set"&&typeof t.key=="string"&&typeof t.value=="string")n.setItem(t.key,t.value);else if(t.operation==="remove"&&typeof t.key=="string")n.removeItem(t.key);else if(t.operation==="clear")for(let o=n.length-1;o>=0;o-=1){let s=n.key(o);s?.startsWith("heroui-agent:")&&n.removeItem(s)}}catch{}}function Me(e,t){return e.has(t)?!1:(e.add(t),e.size>2048&&e.delete(e.values().next().value),!0)}function Ue(e,t){if(t){let n=new URL(t);if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error("HeroUI Agent embed origin must use HTTP or HTTPS");return n.origin}return/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/i.test(e)?"http://localhost:8793":e.includes("staging")?oe:ne}function Fe(e){if(!e||typeof e!="object"||!("issues"in e)||!Array.isArray(e.issues))return{};let t=e.issues.slice(0,8).flatMap(n=>{if(!n||typeof n!="object")return[];let o=n;return!Array.isArray(o.path)||typeof o.code!="string"?[]:[{code:o.code.slice(0,60),path:o.path.filter(s=>typeof s=="string"||typeof s=="number").join(".").slice(0,200),...typeof o.minimum=="number"&&Number.isFinite(o.minimum)?{minimum:o.minimum}:{},...typeof o.maximum=="number"&&Number.isFinite(o.maximum)?{maximum:o.maximum}:{},...typeof o.expected=="string"?{expected:o.expected.slice(0,100)}:{}}]});return t.length?{issues:t}:{}}export{ye as a,V as b,X as c,M as d,H as e,se as f,et as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as S}from"./chunk-
|
|
1
|
+
import{g as S}from"./chunk-AMNE7O54.js";import{b as p}from"./chunk-FZXNXBTZ.js";import{useEffect as O,useLayoutEffect as m,useMemo as b,useRef as f,useState as k,useSyncExternalStore as H}from"react";var i=new Map,h=new Set;function C(){for(let t of h)t()}function R(t){return h.add(t),()=>h.delete(t)}function a(t,n,r){let o=t?i.get(t):[...i.values()][i.size-1];if(!o){console.warn("HeroUI Agent is not mounted yet. Add <HeroUIAgent /> to your layout.");return}n==="newConversation"?o.newConversation(r):o[n]()}function w(t){let n=H(R,()=>(t?i.get(t):[...i.values()].at(-1))?.ready??!1,()=>!1);return b(()=>({hide:()=>a(t,"hide"),newConversation:r=>a(t,"newConversation",r),preload:()=>a(t,"preload"),ready:n,refreshAuth:()=>a(t,"refreshAuth"),show:()=>a(t,"show"),shutdown:()=>a(t,"shutdown"),toggle:()=>a(t,"toggle")}),[t,n])}async function I(t){let{serializeClientTools:n}=await import("./client-tools-manifest-PCUOVUXR.js");return n(t).map(o=>{let s=t.find(l=>l.name===o.name);return{...o,...s?.displayName?{displayName:s.displayName}:{},...s?.icon?{icon:s.icon}:{},...s?.iconColor?{iconColor:s.iconColor}:{}}})}function P(t){let n=f(t),r=f(null),o=f(null);m(()=>{n.current=t}),o.current||(o.current={getAuthToken:e=>n.current.getAuthToken(e),onError:e=>n.current.onError?.(e),onFeedback:e=>n.current.onFeedback?.(e),onOpenChange:e=>n.current.onOpenChange?.(e),onReady:()=>n.current.onReady?.(),onStatusChange:e=>n.current.onStatusChange?.(e)},Object.defineProperties(o.current,{context:{enumerable:!0,get(){return n.current.context}},tools:{enumerable:!0,get(){return n.current.tools}}}));let s=x(t),l=o.current;for(let e of Object.keys(l))e!=="context"&&e!=="getAuthToken"&&e!=="onError"&&e!=="onStatusChange"&&e!=="onFeedback"&&e!=="onReady"&&e!=="onOpenChange"&&e!=="tools"&&!(e in s)&&delete l[e];Object.assign(l,s,{agentId:t.agentId});let u=o.current;m(()=>{let e=S(u,I),c=e.subscribe(C);return r.current=e,i.set(t.agentId,e),C(),()=>{c(),e.destroy(),i.get(t.agentId)===e&&i.delete(t.agentId),r.current===e&&(r.current=null),C()}},[t.agentId]);let[y,g]=k("");O(()=>{let e=t.tools??[];if(!e.some(d=>p(d.parameters))){g("");return}let c=!1;return import("./client-tools-manifest-PCUOVUXR.js").then(({serializeClientTools:d})=>{c||g(JSON.stringify(d(e).map(T=>({inputSchema:T.inputSchema,name:T.name}))))}),()=>{c=!0}},[t.tools]);let A=JSON.stringify({props:x(t),tools:(t.tools??[]).map(e=>({description:e.description,displayName:e.displayName,icon:e.icon,iconColor:e.iconColor,name:e.name,needsApproval:e.needsApproval===!0,parameters:p(e.parameters)?null:e.parameters})),zodToolsSchemasKey:y});return m(()=>{r.current?.update(u)},[A]),null}function x(t){let{context:n,getAuthToken:r,onError:o,onFeedback:s,onOpenChange:l,onReady:u,onStatusChange:y,tools:g,...A}=t;return JSON.parse(JSON.stringify(A))}export{w as a,P as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t="1.0.0-beta.11",o="https://api.heroui.pro";export{t as a,o as b};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { U as HeroUIAgentProps, i as AgentController } from './types-C3g7R0hr.js';
|
|
2
2
|
export { A as AgentApiOverrides, a as AgentAppearance, b as AgentAttachmentContentType, c as AgentAuthToken, d as AgentCapabilities, e as AgentColorScheme, f as AgentComponentExportFormat, g as AgentComposerOptions, h as AgentContext, j as AgentDataSource, k as AgentDataSourceFormat, l as AgentDesignTheme, m as AgentError, n as AgentFeedbackReason, o as AgentLauncherOptions, p as AgentLauncherPosition, q as AgentMarkdownAnimation, r as AgentMarkdownAnimationOptions, s as AgentMarkdownCaret, t as AgentMarkdownOptions, u as AgentMessageAction, v as AgentModelId, w as AgentPanelOptions, x as AgentPermissionMode, y as AgentPermissionOptions, z as AgentRadius, B as AgentResponseFeedback, C as AgentSharedContext, D as AgentShouldCloseOnInteractOutside, E as AgentStartScreenOptions, F as AgentStatus, G as AgentSurfaceVariant, H as AgentThemeColor, I as AgentThemeColors, J as AgentThemeOptions, K as AgentTypography, L as AgentViewMode, M as ClientTool, N as ClientToolExecutionContext, O as ClientToolIcon, P as ClientToolStatus, Q as ClientToolVisualResult, R as DEFAULT_MARKDOWN_ANIMATION, S as GetAuthToken, T as GetAuthTokenContext, V as UploadAgentDataSourceInput, W as createToolHelper } from './types-C3g7R0hr.js';
|
|
3
|
-
export { H as HEROUI_AGENT_API_BASE_URL, a as HEROUI_AGENT_SDK_VERSION } from './version-
|
|
3
|
+
export { H as HEROUI_AGENT_API_BASE_URL, a as HEROUI_AGENT_SDK_VERSION } from './version-BNdyk3rt.js';
|
|
4
4
|
import 'react';
|
|
5
5
|
|
|
6
6
|
/** Imperative controls for the hosted iframe Agent. */
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as d,b as e}from"./chunk-
|
|
1
|
+
import{a as d,b as e}from"./chunk-IGSNBYO2.js";import"./chunk-AMNE7O54.js";import{a as f}from"./chunk-AR424OVX.js";import{a as b,b as c}from"./chunk-QSLALU5G.js";import{a}from"./chunk-FZXNXBTZ.js";export{f as DEFAULT_MARKDOWN_ANIMATION,c as HEROUI_AGENT_API_BASE_URL,b as HEROUI_AGENT_SDK_VERSION,e as HeroUIAgent,a as createToolHelper,d as useAgent};
|
package/dist/internal/host.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as r,b as t,c as l,d as a,e as i,f as n,g as s}from"../chunk-
|
|
1
|
+
import{a as r,b as t,c as l,d as a,e as i,f as n,g as s}from"../chunk-AMNE7O54.js";import"../chunk-QSLALU5G.js";import{c as o,d as e,i as m,j as p,k as f,l as x,m as g,n as u,o as A,p as C}from"../chunk-FZXNXBTZ.js";export{i as ClientToolResultError,a as EmbedSessionManager,f as HEROUI_AGENT_BRIDGE_MAX_MESSAGE_BYTES,x as HEROUI_AGENT_BRIDGE_MAX_PERSISTENCE_BYTES,m as HEROUI_AGENT_HOSTED_ORIGIN,p as HEROUI_AGENT_HOSTED_STAGING_ORIGIN,r as abortable,g as createAgentBridgeEnvelope,l as createAgentError,C as estimateAgentBridgeMessageBytes,A as isAgentBridgeJsonValue,s as mountAgent,u as parseAgentBridgeEnvelope,o as parseClientToolArgs,e as resolveDirectToolAction,n as serializeClientToolResult,t as withDeadline};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { H as HEROUI_AGENT_API_BASE_URL, a as HEROUI_AGENT_SDK_VERSION } from '../version-
|
|
1
|
+
export { H as HEROUI_AGENT_API_BASE_URL, a as HEROUI_AGENT_SDK_VERSION } from '../version-BNdyk3rt.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { M as ClientTool } from '../types-C3g7R0hr.js';
|
|
4
4
|
export { R as DEFAULT_MARKDOWN_ANIMATION } from '../types-C3g7R0hr.js';
|
package/dist/internal/shared.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as l}from"../chunk-AR424OVX.js";import{a as s,b as A}from"../chunk-
|
|
1
|
+
import{a as l}from"../chunk-AR424OVX.js";import{a as s,b as A}from"../chunk-QSLALU5G.js";import{a as c,b as h,c as p,d as u,e as g}from"../chunk-KFWXAD55.js";import{e as r,f as m}from"../chunk-FZXNXBTZ.js";import{z as e}from"zod";var d=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),t=e.string().trim().min(1).max(200).refine(n=>!d.has(n.toLowerCase()),{message:"Identity id is reserved"}),o=e.discriminatedUnion("type",[e.object({id:t,type:e.literal("anonymous")}),e.object({id:t,type:e.literal("user")})]),i=e.object({avatarUrl:e.string().trim().pipe(e.url()).optional(),email:e.string().trim().max(320).pipe(e.email()).optional(),name:e.string().trim().max(120).optional()}),a=e.record(e.string(),e.string()).refine(n=>new TextEncoder().encode(JSON.stringify(n)).byteLength<=4096,{message:"Metadata must not exceed 4 KiB"}),S=e.object({anonymousId:t.optional(),identity:o,metadata:a.optional(),profile:i.optional()}),T=e.object({expiresAt:e.number().int().positive(),token:e.string().trim().min(1)});export{l as DEFAULT_MARKDOWN_ANIMATION,A as HEROUI_AGENT_API_BASE_URL,s as HEROUI_AGENT_SDK_VERSION,c as MAX_CLIENT_TOOLS,h as MAX_CLIENT_TOOLS_BYTES,r as RESERVED_AGENT_TOOL_NAMES,m as RESERVED_AGENT_TOOL_PREFIX,o as agentAuthIdentitySchema,a as agentAuthMetadataSchema,i as agentAuthProfileSchema,T as agentAuthTokenSchema,t as agentIdentityIdSchema,p as clientToolManifestEntrySchema,u as clientToolsSchema,S as createAgentAuthTokenRequestSchema,g as serializeClientTools};
|
package/dist/next.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { A as AgentApiOverrides, a as AgentAppearance, b as AgentAttachmentContentType, c as AgentAuthToken, d as AgentCapabilities, e as AgentColorScheme, f as AgentComponentExportFormat, g as AgentComposerOptions, h as AgentContext, i as AgentController, j as AgentDataSource, k as AgentDataSourceFormat, l as AgentDesignTheme, m as AgentError, n as AgentFeedbackReason, o as AgentLauncherOptions, p as AgentLauncherPosition, q as AgentMarkdownAnimation, r as AgentMarkdownAnimationOptions, s as AgentMarkdownCaret, t as AgentMarkdownOptions, u as AgentMessageAction, v as AgentModelId, w as AgentPanelOptions, x as AgentPermissionMode, y as AgentPermissionOptions, z as AgentRadius, B as AgentResponseFeedback, C as AgentSharedContext, D as AgentShouldCloseOnInteractOutside, E as AgentStartScreenOptions, F as AgentStatus, G as AgentSurfaceVariant, H as AgentThemeColor, I as AgentThemeColors, J as AgentThemeOptions, K as AgentTypography, L as AgentViewMode, M as ClientTool, N as ClientToolExecutionContext, O as ClientToolIcon, P as ClientToolStatus, Q as ClientToolVisualResult, R as DEFAULT_MARKDOWN_ANIMATION, S as GetAuthToken, T as GetAuthTokenContext, U as HeroUIAgentProps, V as UploadAgentDataSourceInput, W as createToolHelper } from './types-C3g7R0hr.js';
|
|
2
2
|
export { HeroUIAgent, useAgent } from './index.js';
|
|
3
|
-
export { H as HEROUI_AGENT_API_BASE_URL, a as HEROUI_AGENT_SDK_VERSION } from './version-
|
|
3
|
+
export { H as HEROUI_AGENT_API_BASE_URL, a as HEROUI_AGENT_SDK_VERSION } from './version-BNdyk3rt.js';
|
|
4
4
|
import 'react';
|
package/dist/next.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as f,b as m}from"./chunk-
|
|
1
|
+
import{a as f,b as m}from"./chunk-IGSNBYO2.js";import"./chunk-AMNE7O54.js";import{a as p}from"./chunk-AR424OVX.js";import{a as r,b as e}from"./chunk-QSLALU5G.js";import{a as o}from"./chunk-FZXNXBTZ.js";export{p as DEFAULT_MARKDOWN_ANIMATION,e as HEROUI_AGENT_API_BASE_URL,r as HEROUI_AGENT_SDK_VERSION,m as HeroUIAgent,o as createToolHelper,f as useAgent};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
declare const HEROUI_AGENT_SDK_VERSION: "1.0.0-beta.
|
|
1
|
+
declare const HEROUI_AGENT_SDK_VERSION: "1.0.0-beta.11";
|
|
2
2
|
/** Production Agent API origin used when hosts omit `_api.baseUrl` / `apiBaseUrl`. */
|
|
3
3
|
declare const HEROUI_AGENT_API_BASE_URL: "https://api.heroui.pro";
|
|
4
4
|
|
package/package.json
CHANGED
package/dist/chunk-23EBJXRA.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var t="1.0.0-beta.10",o="https://api.heroui.pro";export{t as a,o as b};
|