@heroui/agent 1.0.0-beta.6 → 1.0.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +40 -2
- package/dist/chunk-2W6CUSN3.js +1 -0
- package/dist/chunk-KMVOOEIK.js +1 -0
- package/dist/chunk-KQ3FZPFS.js +1 -0
- package/dist/chunk-MUJYIDA4.js +1 -0
- package/dist/chunk-YPHOJDYK.js +1 -0
- package/dist/{client-tools-manifest-2T23ADUM.js → client-tools-manifest-BD7O7M3V.js} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/internal/host.d.ts +110 -39
- package/dist/internal/host.js +1 -1
- package/dist/internal/shared.d.ts +4 -4
- package/dist/internal/shared.js +1 -1
- package/dist/next.d.ts +2 -2
- package/dist/next.js +1 -1
- package/dist/{types-BeXKAj2P.d.ts → types-Cuqd4_1K.d.ts} +25 -3
- package/dist/{version-BOWn57s2.d.ts → version-DDaVFBVG.d.ts} +1 -1
- package/package.json +2 -2
- package/dist/chunk-3UR3CJAJ.js +0 -1
- package/dist/chunk-BYV3XUCN.js +0 -1
- package/dist/chunk-L5DXTMC2.js +0 -1
- package/dist/chunk-LMNV4H5B.js +0 -1
- package/dist/chunk-ZD5U6JIE.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Add `locale` to React and vanilla integrations, including `auto` for browser language detection, regional formatting, and optional `translations` for custom copy by language.
|
|
6
|
+
- Select localized agent copy using the SDK override or saved agent default. AI responses follow the user's language.
|
|
7
|
+
|
|
8
|
+
## Unreleased
|
|
9
|
+
|
|
5
10
|
- Move the model catalog, attachment limits and MIME allowlist, and design theme
|
|
6
11
|
list out of the published package and into the hosted runtime. Adding a model,
|
|
7
12
|
attachment type, or theme variant no longer requires a customer npm release.
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ package and is deployed through `agent.heroui.pro`.
|
|
|
14
14
|
## React installation
|
|
15
15
|
|
|
16
16
|
```bash
|
|
17
|
-
npm install @heroui/agent@
|
|
17
|
+
npm install @heroui/agent@latest
|
|
18
18
|
```
|
|
19
19
|
|
|
20
20
|
## React (Vite) usage
|
|
@@ -31,6 +31,7 @@ export function AppAgent() {
|
|
|
31
31
|
getAuthToken={async (context) => {
|
|
32
32
|
const response = await fetch("/api/heroui-agent/auth-token", {
|
|
33
33
|
method: "POST",
|
|
34
|
+
signal: context.signal,
|
|
34
35
|
headers: {"Content-Type": "application/json"},
|
|
35
36
|
body: JSON.stringify(context),
|
|
36
37
|
});
|
|
@@ -58,6 +59,7 @@ export function AppAgent() {
|
|
|
58
59
|
getAuthToken={async (context) => {
|
|
59
60
|
const response = await fetch("/api/heroui-agent/auth-token", {
|
|
60
61
|
method: "POST",
|
|
62
|
+
signal: context.signal,
|
|
61
63
|
headers: {"Content-Type": "application/json"},
|
|
62
64
|
body: JSON.stringify(context),
|
|
63
65
|
});
|
|
@@ -154,7 +156,7 @@ The typed React bridge for embedding the hosted Agent iframe.
|
|
|
154
156
|
#### Installation
|
|
155
157
|
|
|
156
158
|
```bash
|
|
157
|
-
npm install @heroui/agent@
|
|
159
|
+
npm install @heroui/agent@latest
|
|
158
160
|
```
|
|
159
161
|
|
|
160
162
|
### @heroui/agent/next
|
|
@@ -264,3 +266,39 @@ MIT — see [LICENSE](LICENSE).
|
|
|
264
266
|
---
|
|
265
267
|
|
|
266
268
|
Built by [HeroUI](https://www.heroui.com)
|
|
269
|
+
|
|
270
|
+
## Status, recovery, and cancellation
|
|
271
|
+
|
|
272
|
+
Use `onStatusChange(status)` to observe startup, connection, generation, finishing, and recovery.
|
|
273
|
+
`onError(error)` receives a safe `message`, `category`, `phase`, `retryable`, and `diagnosticId`.
|
|
274
|
+
Use the diagnostic ID to correlate failures; keep prompts, form values, files, credentials, and tool
|
|
275
|
+
outputs out of telemetry. The hosted panel supplies recovery actions and preserves conversation drafts.
|
|
276
|
+
|
|
277
|
+
Pass `context.signal` from `getAuthToken` into your authentication fetch. Authentication expires
|
|
278
|
+
after 15 seconds and superseded attempts are cancelled. Client tools receive
|
|
279
|
+
`execution.signal` as their third argument; pass it into cancellable requests and use
|
|
280
|
+
`execution.idempotencyKey` for server mutations. Cancellation after dispatch can leave an unknown
|
|
281
|
+
outcome, so the runtime preserves a receipt and does not automatically repeat the effect.
|
|
282
|
+
|
|
283
|
+
Generated forms submit their validated values as a queued user message without changing the composer
|
|
284
|
+
draft. “Submitted to agent” confirms queue acceptance; action completion is reported separately.
|
|
285
|
+
The selected conversation stays connected while visible. Settled inactive conversations disconnect
|
|
286
|
+
after a grace period; closing the panel leaves active work running.
|
|
287
|
+
|
|
288
|
+
## Language
|
|
289
|
+
|
|
290
|
+
Set the default language in the HeroUI Agents editor. Pass `locale` to override it for a user:
|
|
291
|
+
|
|
292
|
+
```tsx
|
|
293
|
+
<HeroUIAgent agentId={agentId} getAuthToken={getAuthToken} locale="es" />
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
The vanilla integration accepts the same `locale` option. English (`en`) and neutral Latin American Spanish (`es`) are supported. Regional tags such as `es-AR` share Spanish text and use regional number and date formatting. Unsupported locales fall back to English.
|
|
297
|
+
|
|
298
|
+
Set `locale="auto"` (or choose **Auto** in the editor) to use the first supported language in the visitor’s browser preferences, with English as the fallback. Regional formatting is preserved. Auto updates when browser language preferences change.
|
|
299
|
+
|
|
300
|
+
The SDK locale takes precedence over the saved agent locale, then English. With `remoteConfig={false}`, only the SDK locale and English fallback apply. Update the prop when your application's language changes; existing messages stay intact and subsequent submissions capture the new locale.
|
|
301
|
+
|
|
302
|
+
Interface language and response language are separate: the AI follows the user's message, keeps the previous conversational language for ambiguous follow-ups, and otherwise uses the configured locale. Explicit translation requests are honored.
|
|
303
|
+
|
|
304
|
+
Edit English and Spanish greetings, subtitles, placeholders, disclaimers, and suggested prompts in the editor's **Edit and preview** tabs. Explicit SDK copy overrides the selected translation. With `remoteConfig={false}`, pass a `translations` object keyed by base language (`{en: {greeting: "Hello"}, es: {greeting: "Hola"}}`) to provide custom copy for Auto. Missing Spanish copy uses built-in Spanish defaults; untranslated suggested prompts are hidden. Empty values and disabled disclaimers are preserved. Legacy custom copy remains English.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t="1.0.0-beta.8",o="https://api.heroui.pro";export{t as a,o as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as J}from"./chunk-2W6CUSN3.js";import{c as G,e as V,f as X,i as Y,j as Q,k as Z}from"./chunk-YPHOJDYK.js";function ge(e,t){return e.throwIfAborted(),new Promise((n,r)=>{let l=()=>r(e.reason);e.addEventListener("abort",l,{once:!0});try{t().then(n,r).finally(()=>e.removeEventListener("abort",l))}catch(c){e.removeEventListener("abort",l),r(c)}})}async function U(e,t,n){let r=new AbortController,l=setTimeout(()=>r.abort(new DOMException("Request timed out","TimeoutError")),e),c=n?AbortSignal.any([n,r.signal]):r.signal;try{return await ge(c,()=>t(c))}finally{clearTimeout(l)}}var fe={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."},me="Too many conversations are active. Wait a few minutes, then retry this chat.";function ee(e,t="connecting"){let n=e&&typeof e=="object"?e:{},r=[e instanceof Error?e.message:"",n.code,n.status].filter(c=>typeof c=="string"||typeof c=="number").join(" ").toLowerCase(),l=t==="authenticating"||/auth|401|sign.in/.test(r)?"authentication":/429|rate.limit|concurrency_limit|too many conversations are active/.test(r)?"rate_limit":/credit|usage.limit|usage_limit|402/.test(r)?"credits":/deleted|conversation_not_found/.test(r)?"deleted":/approval.*expir/.test(r)?"approval":/dynamic.*import|chunk|module.*fetch/.test(r)?"chunk":/config/.test(r)?"configuration":/network|fetch|connect|timeout|timed out/.test(r)?"connection":"unknown";return{category:l,diagnosticId:crypto.randomUUID(),message:/concurrency_limit|too many conversations are active/.test(r)?me:fe[l],phase:t,retryable:!["credits","deleted","approval"].includes(l)}}var he=5e3;function te(e){return`heroui-agent:anonymous:${e}`}function ye(e){return e instanceof Error?e:new Error("Auth token request failed")}var P=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(te(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 r=await n;return t!==this.generation?this.get():(this.cached=r,this.failure=null,r.token)}catch(r){throw t===this.generation&&(this.failure={error:ye(r),retryAt:Date.now()+he}),r}finally{this.pending===n&&(this.pending=null)}}async subjectHash(){let t=await this.get(),n=we(t),r=typeof n.sub=="string"?n.sub:"anonymous",l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${this.agentId}:${r}`));return Array.from(new Uint8Array(l),c=>c.toString(16).padStart(2,"0")).join("").slice(0,24)}anonymousId(){let t=te(this.agentId);try{let n=localStorage.getItem(t);if(n)return n;let r=crypto.randomUUID();return localStorage.setItem(t,r),r}catch{return crypto.randomUUID()}}expiresAt(t){return t.expiresAt}async refresh(){let t=await U(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 we(e){try{let t=e.split(".")[1];if(!t)return{};let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=n.padEnd(Math.ceil(n.length/4)*4,"=");return JSON.parse(atob(r))}catch{return{}}}function ne(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 w(e,t,n){return{background:"transparent",border:"0",clipPath:be(e,t,n),colorScheme:"normal",height:"100dvh",inset:"0",position:"fixed",width:"100vw",zIndex:t.appearance?.zIndex??40}}function oe(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!=="floating"&&t.viewMode!=="sidebar"?null:{bounds:ve(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:L(t.sidebarWidth)?t.sidebarWidth:null,viewMode:t.viewMode}}function re(){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 x(e,t,n,r){let l=t.open||t.closing;if(!l&&!e.active)return;l&&(e.active=!0);let c=l&&(r||t.viewMode==="sidebar"&&t.expanded);se(e,c);let a=l&&t.viewMode==="sidebar"&&!t.expanded&&!r?Ae(t,n):e.original.rootMarginRight;e.root.style.transition=e.original.rootTransition,e.root.style.marginRight=a,l||(e.active=!1)}function ie(e){se(e,!1),e.root.style.marginRight=e.original.rootMarginRight,e.root.style.transition=e.original.rootTransition,e.active=!1}function be(e,t,n){let r=e.open||e.closing;if(r&&(n||e.overlayOpen))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)`;let l=t.appearance?.launcher,c=l?.position==="bottom-left",g=(l?.offset?.x??24)+60,a=(l?.offset?.y??24)+60;if(!r)return c?`inset(calc(100% - ${a}px) calc(100% - ${g}px) 0px 0px)`:`inset(calc(100% - ${a}px) 0px 0px calc(100% - ${g}px))`;if(e.viewMode==="sidebar")return`inset(0px 0px 0px calc(100% - (${F(t.appearance?.panel?.initialWidth??420)} + 16px)))`;let f=F(t.appearance?.panel?.initialWidth??440),v=`calc(100% - min(calc(${F(t.appearance?.panel?.initialHeight??"max(420px, 56dvh)")} + 32px), 100dvh))`;return c?`inset(${v} calc(100% - min(calc(${f} + 32px), 100vw)) 0px 0px)`:`inset(${v} 0px 0px calc(100% - min(calc(${f} + 32px), 100vw)))`}function ve(e){if(!e||typeof e!="object")return null;let t=e;return!L(t.top)||!L(t.right)||!L(t.bottom)||!L(t.left)||t.right<t.left||t.bottom<t.top?null:{bottom:t.bottom,left:t.left,right:t.right,top:t.top}}function L(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1e5}function Ae(e,t){return e.sidebarWidth===null?F(t.appearance?.panel?.initialWidth??420):`${Math.round(e.sidebarWidth)}px`}function F(e){return typeof e=="number"?`${Math.round(e)}px`:e}function se(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:r}=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,r)}catch{}}}var Te=16*1024,Ie=64*1024;function qe(e,t){let n=e;if(!n?.agentId||typeof n.getAuthToken!="function")throw new Error("HeroUIAgent.mount requires agentId and getAuthToken");let r=crypto.randomUUID(),l=crypto.randomUUID(),c=(n._api?.baseUrl??J).replace(/\/$/,""),g=Le(c,n._api?.embedOrigin),a=document.createElement("iframe"),f=new Map,y=[],v=new Set,A=new Map,k=new Set,T=re(),C=new P(n.agentId,n.getAuthToken),s=ne(n),O=null,h=!1,b=!1,I=null,W=!1,$=!1,N=new URL("/embed",g);N.searchParams.set("agentId",n.agentId),N.hash=new URLSearchParams({nonce:l,parentOrigin:window.location.origin,sessionId:r}).toString(),a.allow="microphone; clipboard-write",a.referrerPolicy="origin",a.setAttribute("sandbox","allow-downloads allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),a.src=N.toString(),a.title="HeroUI Agent",Object.assign(a.style,w(s,n,window.innerWidth<640)),document.body.append(a);let m=(o,i,d)=>{$||a.contentWindow?.postMessage(Y(r,l,o,i,d),g)},de=(o,i)=>{let d=crypto.randomUUID();return new Promise((p,u)=>{let H=window.setTimeout(()=>{f.delete(d),u(new Error(`HeroUI Agent iframe request timed out: ${o}`))},3e4);f.set(d,{reject:u,resolve:p,timer:H}),m(o,i,d)})},S=new Map,q=0,z="",B=async(o,i=!1)=>{let d=++q,p=await ke(n,t);if($||d!==q)return;let u=JSON.stringify({props:p.props,tools:p.tools});!i&&u===z||(z=u,m(o,{...p,restoreSession:o==="host.init"&&b}))},E=(o,i)=>{if(!s.mounted){y.push({name:o,payload:i}),y.length>32&&y.shift();return}m("host.command",{name:o,payload:i})},M=o=>{o&&!h&&document.activeElement!==a&&(O=document.activeElement),h=o,o||(b=!1),E(o?"show":"hide")},ce=()=>{if(s.mounted)for(let o of y.splice(0))m("host.command",o)},ue=()=>{b=s.mounted&&h&&!s.closing,s={...s,bounds:null,closing:!1,mounted:!1,open:b,ready:!1},W=!1;for(let o of k)o();Object.assign(a.style,w(s,n,window.innerWidth<640)),x(T,s,n,window.innerWidth<640)},j=o=>{if(o.origin!==g||o.source!==a.contentWindow)return;let i=Q(o.data);if(!(!i||i.sessionId!==r||i.nonce!==l)){if(i.type==="iframe.rpc-result"||i.type==="iframe.rpc-error"){Se(i,f);return}Pe(v,i.requestId)&&pe(i)}},pe=async o=>{try{if(o.type==="iframe.ready"){(s.mounted||s.ready)&&ue(),await B("host.init",!0);return}if(o.type==="iframe.reload"){let i=a.cloneNode(!1),d=new URL(a.src);d.pathname=`/reload/${crypto.randomUUID()}/embed`,i.src=d.href,a.replaceWith(i),a=i;return}if(o.type==="iframe.state"){let i=oe(o.payload);if(i){let d=s.mounted,p=s.open||s.closing,u=i;b?i.mounted?(b=!1,i.open||(m("host.command",{name:"show"}),u={...i,bounds:null,closing:!1,open:!0,sidebarWidth:i.sidebarWidth??s.sidebarWidth})):u={...i,bounds:null,closing:!1,open:!0,sidebarWidth:i.sidebarWidth??s.sidebarWidth}:i.open?h=!0:(i.closing||s.open||s.closing)&&(h=!1);let H=u.open||u.closing;if(H&&!p&&document.activeElement!==a&&(O=document.activeElement),!H&&p&&O?.isConnected){let D=O;window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>D.focus({preventScroll:!0})))}s=u,s.mounted&&!d&&B("host.update"),H&&s.expanded?a.dataset.expanded="true":a.removeAttribute("data-expanded");for(let D of k)D();Object.assign(a.style,w(s,n,window.innerWidth<640)),x(T,s,n,window.innerWidth<640),ce(),s.ready&&!W&&(W=!0,n.onReady?.())}return}if(o.type==="iframe.error"){n.onError?.(o.payload);return}if(o.type==="iframe.status"){n.onStatusChange?.(o.payload);return}if(o.type==="iframe.tool-cancel"){let i=o.payload;i.idempotencyKey&&S.get(i.idempotencyKey)?.abort();return}if(o.type==="iframe.auth-request"){let i=await C.get(),d=await U(15e3,p=>fetch(`${c}/v1/agents/${encodeURIComponent(n.agentId)}/embed-sessions`,{body:JSON.stringify({iframeOrigin:g,sessionId:r}),cache:"no-store",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},method:"POST",signal:p}));if(!d.ok)throw new Error("Could not authenticate HeroUI Agent");m("host.rpc-result",{value:await d.json()},o.requestId);return}if(o.type==="iframe.context-request"){let i=le(await n.context?.page?.()??{},Te,"Agent page context");m("host.rpc-result",{value:i},o.requestId);return}if(o.type==="iframe.tool-execute"){let i=Ee(o.payload),d=n.tools?.find(u=>u.name===i.name);if(!d)throw new Error(`Unknown client tool: ${i.name}`);let p=A.get(i.idempotencyKey);if(!p){let u=new AbortController;S.set(i.idempotencyKey,u),p=xe(d,i,n,de,u.signal).finally(()=>S.delete(i.idempotencyKey)),A.set(i.idempotencyKey,p),A.size>2048&&A.delete(A.keys().next().value)}m("host.rpc-result",{value:await p},o.requestId);return}if(o.type==="iframe.feedback"){await n.onFeedback?.(o.payload);return}if(o.type==="iframe.storage"){He(o.payload);return}if(o.type==="iframe.persistence"){let i=await import("./persistence-YI6JSYCT.js").then(({executeAgentHostPersistence:d})=>d(n.agentId,o.payload));m("host.rpc-result",{value:i},o.requestId)}}catch(i){let d=ee(i,o.type==="iframe.auth-request"?"authenticating":"failed");n.onError?.(d),m("host.rpc-error",{error:d.message},o.requestId)}},K=o=>{o.composedPath().includes(a)||s.open&&s.viewMode==="floating"&&(n.appearance?.shouldCloseOnInteractOutside??!0)&&M(!1)},R=()=>{s={...s,bounds:null},Object.assign(a.style,w(s,n,window.innerWidth<640)),x(T,s,n,window.innerWidth<640)},_=()=>{document.visibilityState==="visible"&&(s={...s,bounds:null},Object.assign(a.style,w(s,n,window.innerWidth<640)),x(T,s,n,window.innerWidth<640),h&&s.mounted&&m("host.command",{name:"show"}),I!==null&&window.cancelAnimationFrame(I),I=window.requestAnimationFrame(()=>{I=null,Object.assign(a.style,w(s,n,window.innerWidth<640))}))};return window.addEventListener("message",j),window.addEventListener("pointerdown",K,!0),window.addEventListener("resize",R),window.addEventListener("pageshow",_),window.visualViewport?.addEventListener("resize",R),document.addEventListener("visibilitychange",_),{destroy:()=>{$=!0;for(let o of S.values())o.abort();S.clear(),window.removeEventListener("message",j),window.removeEventListener("pointerdown",K,!0),window.removeEventListener("resize",R),window.removeEventListener("pageshow",_),window.visualViewport?.removeEventListener("resize",R),document.removeEventListener("visibilitychange",_),I!==null&&window.cancelAnimationFrame(I);for(let o of f.values())window.clearTimeout(o.timer),o.reject(new Error("HeroUI Agent iframe was removed"));f.clear(),y.length=0,k.clear(),ie(T),a.remove()},hide:()=>M(!1),newConversation:o=>{h=!0,E("newConversation",{prompt:o})},preload:()=>E("preload"),get ready(){return s.ready},refreshAuth:()=>{C.clear(),E("refreshAuth")},show:()=>M(!0),shutdown:()=>{h=!1,b=!1,C.reset(),E("shutdown")},subscribe:o=>(k.add(o),()=>k.delete(o)),toggle:()=>M(!h),update:o=>{if(o.agentId!==n.agentId)throw new Error("HeroUI Agent agentId cannot change without remounting");o.getAuthToken!==n.getAuthToken&&(C=new P(o.agentId,o.getAuthToken)),n=o,Object.assign(a.style,w(s,n,window.innerWidth<640)),x(T,s,n,window.innerWidth<640),s.mounted&&B("host.update")}}}async function xe(e,t,n,r,l){let c={conversationId:t.conversationId,idempotencyKey:t.idempotencyKey,signal:l,toolCallId:t.toolCallId,uploadDataSource:async f=>await r("host.upload-data-source",{toolCallId:t.toolCallId,upload:f})},g;try{g=G(e,t.args)}catch{return{code:"CLIENT_TOOL_INVALID_INPUT",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 a=await e.execute(g,n.context??{},c)??null;return le(a,Ie,`Client tool ${e.name} result`)}async function ke(e,t){let{context:n,getAuthToken:r,onError:l,onFeedback:c,onReady:g,onStatusChange:a,tools:f,...y}=e,v=await t(f??[]);return{localStorage:ae(window.localStorage),props:JSON.parse(JSON.stringify(y)),sessionStorage:ae(window.sessionStorage),tools:v}}function Se(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 r=e.payload;n.reject(new Error(typeof r?.error=="string"?r.error:"Iframe request failed"))}else{let r=e.payload;n.resolve(r?.value)}}function Ee(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 le(e,t,n){if(!Z(e))throw new Error(`${n} must be JSON-serializable`);let r=JSON.stringify(e);if(new TextEncoder().encode(r).byteLength>t)throw new Error(`${n} exceeds ${Math.round(t/1024)} KiB`);return JSON.parse(r)}function ae(e){let t={};try{for(let n=0;n<e.length;n+=1){let r=e.key(n);r?.startsWith("heroui-agent:")&&(t[r]=e.getItem(r)??"")}}catch{}return t}function He(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 r=n.length-1;r>=0;r-=1){let l=n.key(r);l?.startsWith("heroui-agent:")&&n.removeItem(l)}}catch{}}function Pe(e,t){return e.has(t)?!1:(e.add(t),e.size>2048&&e.delete(e.values().next().value),!0)}function Le(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")?X:V}export{ge as a,U as b,ee as c,P as d,qe as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as i,k as a}from"./chunk-YPHOJDYK.js";import{z as t}from"zod";var c=["readConversationHistory","callMcpTool","composeUI","executeSandbox","generateFile","getUIComponents","readSkill","renderComponent","renderDocument","searchKnowledge","searchMcpTools","searchWeb"],m="mcp_",p=20,l=16*1024,d=t.object({description:t.string().trim().min(1).max(1e3),inputSchema:t.record(t.string(),t.unknown()),name:t.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).refine(e=>!c.includes(e)&&!e.toLowerCase().startsWith(m),"Client tool name is reserved by the HeroUI Agent runtime"),needsApproval:t.boolean().optional()}),f=t.array(d).max(p).superRefine((e,n)=>{let o=new Set;for(let r of e)o.has(r.name)&&n.addIssue({code:"custom",message:`Duplicate client tool name: ${r.name}`}),o.add(r.name);new TextEncoder().encode(JSON.stringify(e)).byteLength>l&&n.addIssue({code:"custom",message:"Client tool manifest exceeds 16KB"})});function u(e){let n=i(e.parameters)?t.toJSONSchema(e.parameters):e.parameters;if(!a(n))throw new Error(`Client tool ${e.name} parameters must be a JSON-serializable schema`);return s(n)}function s(e){return Array.isArray(e)?e.map(s):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,s(o)])):e}function E(e){return f.parse(e.map(n=>({description:n.description,inputSchema:u(n),name:n.name,...n.needsApproval?{needsApproval:!0}:{}})))}export{c as a,m as b,p as c,l as d,d as e,f,E as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as S}from"./chunk-KMVOOEIK.js";import{b as d}from"./chunk-YPHOJDYK.js";import{useEffect as k,useLayoutEffect as p,useMemo as x,useRef as m,useState as O,useSyncExternalStore as w}from"react";var i=new Map,h=new Set;function f(){for(let e of h)e()}function H(e){return h.add(e),()=>h.delete(e)}function a(e,n,r){let o=e?i.get(e):[...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 R(e){let n=w(H,()=>(e?i.get(e):[...i.values()].at(-1))?.ready??!1,()=>!1);return x(()=>({hide:()=>a(e,"hide"),newConversation:r=>a(e,"newConversation",r),preload:()=>a(e,"preload"),ready:n,refreshAuth:()=>a(e,"refreshAuth"),show:()=>a(e,"show"),shutdown:()=>a(e,"shutdown"),toggle:()=>a(e,"toggle")}),[e,n])}async function E(e){let{serializeClientTools:n}=await import("./client-tools-manifest-BD7O7M3V.js");return n(e).map(o=>{let s=e.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(e){let n=m(e),r=m(null),o=m(null);p(()=>{n.current=e}),o.current||(o.current={getAuthToken:t=>n.current.getAuthToken(t),onError:t=>n.current.onError?.(t),onFeedback:t=>n.current.onFeedback?.(t),onReady:()=>n.current.onReady?.(),onStatusChange:t=>n.current.onStatusChange?.(t)},Object.defineProperties(o.current,{context:{enumerable:!0,get(){return n.current.context}},tools:{enumerable:!0,get(){return n.current.tools}}}));let s=T(e),l=o.current;for(let t of Object.keys(l))t!=="context"&&t!=="getAuthToken"&&t!=="onError"&&t!=="onStatusChange"&&t!=="onFeedback"&&t!=="onReady"&&t!=="tools"&&!(t in s)&&delete l[t];Object.assign(l,s,{agentId:e.agentId});let g=o.current;p(()=>{let t=S(g,E),u=t.subscribe(f);return r.current=t,i.set(e.agentId,t),f(),()=>{u(),t.destroy(),i.get(e.agentId)===t&&i.delete(e.agentId),r.current===t&&(r.current=null),f()}},[e.agentId]);let[C,c]=O("");k(()=>{let t=e.tools??[];if(!t.some(A=>d(A.parameters))){c("");return}let u=!1;return import("./client-tools-manifest-BD7O7M3V.js").then(({serializeClientTools:A})=>{u||c(JSON.stringify(A(t).map(y=>({inputSchema:y.inputSchema,name:y.name}))))}),()=>{u=!0}},[e.tools]);let b=JSON.stringify({props:T(e),tools:(e.tools??[]).map(t=>({description:t.description,displayName:t.displayName,icon:t.icon,iconColor:t.iconColor,name:t.name,needsApproval:t.needsApproval===!0,parameters:d(t.parameters)?null:t.parameters})),zodToolsSchemasKey:C});return p(()=>{r.current?.update(g)},[b]),null}function T(e){let{context:n,getAuthToken:r,onError:o,onFeedback:s,onReady:l,onStatusChange:g,tools:C,...c}=e;return JSON.parse(JSON.stringify(c))}export{R as a,P as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function m(){return function(e){return e}}function u(t){return!!(t&&typeof t=="object"&&typeof t.safeParse=="function")}function A(t,e){return u(t.parameters)?t.parameters.parse(e):e}function y(t,e){let n=t.get(e);return!n||n.needsApproval?null:n}var x="https://agent.heroui.pro",h="https://staging-agent.heroui.pro",I=262144,S=57671680;function b(t,e,n,s,i=crypto.randomUUID()){return{nonce:e,...s===void 0?{}:{payload:s},requestId:i,sessionId:t,type:n}}function E(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.sessionId!="string"||!a(e.sessionId)||typeof e.nonce!="string"||!a(e.nonce)||typeof e.requestId!="string"||!a(e.requestId)||typeof e.type!="string"||e.type.length===0||!l.has(e.type))return null;let n=e.type==="iframe.persistence"||e.type==="host.upload-data-source"||e.type==="host.rpc-result"?57671680:262144;return p(t)>n||!f(e.type,e.payload)?null:{nonce:e.nonce,...Object.hasOwn(e,"payload")?{payload:e.payload}:{},requestId:e.requestId,sessionId:e.sessionId,type:e.type}}function d(t,e=new Set){if(t===null||typeof t=="string"||typeof t=="boolean")return!0;if(typeof t=="number")return Number.isFinite(t);if(typeof t!="object"||e.has(t))return!1;e.add(t);let n=i=>i===void 0||d(i,e),s=Array.isArray(t)?t.every(n):Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(n);return e.delete(t),s}function p(t){return g(t,new Set)}function g(t,e){if(t==null)return 4;if(typeof t=="string")return new TextEncoder().encode(t).byteLength+2;if(typeof t=="boolean"||typeof t=="number")return 8;if(typeof t!="object"||e.has(t))return Number.POSITIVE_INFINITY;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return t.byteLength;if(typeof Blob<"u"&&t instanceof Blob)return t.size;e.add(t);let n=2;for(let[s,i]of Object.entries(t))if(n+=g(s,e)+g(i,e),!Number.isFinite(n))break;return e.delete(t),n}function a(t){return t.length>0&&t.length<=128&&/^[A-Za-z0-9._:-]+$/.test(t)}var l=new Set(["host.command","host.init","host.update","host.rpc-result","host.rpc-error","host.upload-data-source","iframe.ready","iframe.reload","iframe.auth-request","iframe.context-request","iframe.feedback","iframe.persistence","iframe.state","iframe.storage","iframe.rpc-result","iframe.rpc-error","iframe.error","iframe.status","iframe.tool-cancel","iframe.tool-execute"]),c=["loading","authenticating","connecting","ready","generating","finishing","reconnecting","failed"],o=t=>!!(t&&typeof t=="object"&&!Array.isArray(t)),r=t=>typeof t=="string";function f(t,e){if(t==="iframe.ready"||t==="iframe.reload"||t==="iframe.auth-request"||t==="iframe.context-request")return e===void 0;if(t==="iframe.status")return c.includes(e);if(!o(e))return!1;switch(t){case"host.init":case"host.update":return o(e.props)&&o(e.localStorage)&&o(e.sessionStorage)&&Object.values(e.localStorage).every(r)&&Object.values(e.sessionStorage).every(r)&&(e.restoreSession===void 0||typeof e.restoreSession=="boolean")&&Array.isArray(e.tools)&&e.tools.every(n=>o(n)&&r(n.name)&&r(n.description)&&o(n.inputSchema));case"host.command":return["show","hide","toggle","preload","refreshAuth","shutdown","newConversation"].includes(e.name);case"host.rpc-error":case"iframe.rpc-error":return r(e.error);case"host.rpc-result":case"iframe.rpc-result":return!0;case"host.upload-data-source":return r(e.toolCallId)&&o(e.upload);case"iframe.tool-cancel":return r(e.idempotencyKey);case"iframe.tool-execute":return["name","conversationId","idempotencyKey","toolCallId"].every(n=>r(e[n]));case"iframe.error":return["authentication","connection","configuration","chunk","rate_limit","credits","deleted","approval","unknown"].includes(e.category)&&c.includes(e.phase)&&r(e.message)&&r(e.diagnosticId)&&typeof e.retryable=="boolean";case"iframe.state":return["open","ready","expanded","closing","dragging","mounted","overlayOpen","resizing"].every(n=>typeof e[n]=="boolean")&&["floating","sidebar"].includes(e.viewMode);case"iframe.storage":return["local","session"].includes(e.storage)&&(e.operation==="clear"||r(e.key)&&(e.operation==="remove"||e.operation==="set"&&r(e.value)));case"iframe.persistence":return["composer-image-drafts","message-outboxes"].includes(e.store)&&(e.operation==="deletePrefix"?r(e.prefix):["get","put","delete"].includes(e.operation)&&r(e.key));case"iframe.feedback":return r(e.conversationId)&&r(e.messageId)&&["positive","negative"].includes(e.rating)&&Array.isArray(e.reasons)}}export{m as a,u as b,A as c,y as d,x as e,h as f,I as g,S as h,b as i,E as j,d as k,p as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-KQ3FZPFS.js";import"./chunk-YPHOJDYK.js";export{c as MAX_CLIENT_TOOLS,d as MAX_CLIENT_TOOLS_BYTES,a as RESERVED_AGENT_TOOL_NAMES,b as RESERVED_AGENT_TOOL_PREFIX,e as clientToolManifestEntrySchema,f as clientToolsSchema,g as serializeClientTools};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
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
|
|
3
|
-
export { H as HEROUI_AGENT_API_BASE_URL, a as HEROUI_AGENT_SDK_VERSION } from './version-
|
|
1
|
+
import { T as HeroUIAgentProps, i as AgentController } from './types-Cuqd4_1K.js';
|
|
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 DEFAULT_MARKDOWN_ANIMATION, R as GetAuthToken, S as GetAuthTokenContext, U as UploadAgentDataSourceInput, V as createToolHelper } from './types-Cuqd4_1K.js';
|
|
3
|
+
export { H as HEROUI_AGENT_API_BASE_URL, a as HEROUI_AGENT_SDK_VERSION } from './version-DDaVFBVG.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-MUJYIDA4.js";import"./chunk-KMVOOEIK.js";import{a as f}from"./chunk-AR424OVX.js";import{a as b,b as c}from"./chunk-2W6CUSN3.js";import{a}from"./chunk-YPHOJDYK.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.d.ts
CHANGED
|
@@ -1,43 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { O as ClientToolIcon, U as UploadAgentDataSourceInput, B as AgentResponseFeedback, m as AgentError, F as AgentStatus, i as AgentController, T as HeroUIAgentProps, M as ClientTool, R as GetAuthToken } from '../types-Cuqd4_1K.js';
|
|
2
|
+
export { W as parseClientToolArgs, X as resolveDirectToolAction } from '../types-Cuqd4_1K.js';
|
|
3
3
|
import 'react';
|
|
4
4
|
|
|
5
|
-
declare const HEROUI_AGENT_HOSTED_ORIGIN: "https://agent.heroui.pro";
|
|
6
|
-
declare const HEROUI_AGENT_HOSTED_STAGING_ORIGIN: "https://staging-agent.heroui.pro";
|
|
7
|
-
declare const HEROUI_AGENT_BRIDGE_MAX_MESSAGE_BYTES: number;
|
|
8
|
-
declare const HEROUI_AGENT_BRIDGE_MAX_PERSISTENCE_BYTES: number;
|
|
9
|
-
type AgentBridgeJsonValue = boolean | null | number | string | AgentBridgeJsonValue[] | {
|
|
10
|
-
[key: string]: AgentBridgeJsonValue;
|
|
11
|
-
};
|
|
12
|
-
type HostedAgentToolManifest = {
|
|
13
|
-
description: string;
|
|
14
|
-
displayName?: string;
|
|
15
|
-
icon?: ClientToolIcon;
|
|
16
|
-
iconColor?: string;
|
|
17
|
-
inputSchema: Record<string, unknown>;
|
|
18
|
-
name: string;
|
|
19
|
-
needsApproval?: boolean;
|
|
20
|
-
};
|
|
21
|
-
type AgentBridgeEnvelope = {
|
|
22
|
-
nonce: string;
|
|
23
|
-
payload?: unknown;
|
|
24
|
-
requestId: string;
|
|
25
|
-
sessionId: string;
|
|
26
|
-
type: string;
|
|
27
|
-
};
|
|
28
|
-
declare function createAgentBridgeEnvelope(sessionId: string, nonce: string, type: string, payload?: unknown, requestId?: string): AgentBridgeEnvelope;
|
|
29
|
-
declare function parseAgentBridgeEnvelope(value: unknown): AgentBridgeEnvelope | null;
|
|
30
|
-
declare function isAgentBridgeJsonValue(value: unknown, seen?: Set<object>): value is AgentBridgeJsonValue;
|
|
31
|
-
declare function estimateAgentBridgeMessageBytes(value: unknown): number;
|
|
32
|
-
|
|
33
|
-
type AgentHostController = AgentController & {
|
|
34
|
-
destroy: () => void;
|
|
35
|
-
subscribe: (listener: () => void) => () => void;
|
|
36
|
-
update: (options: HeroUIAgentProps) => void;
|
|
37
|
-
};
|
|
38
|
-
type ClientToolManifestSerializer = (tools: ClientTool[]) => HostedAgentToolManifest[] | Promise<HostedAgentToolManifest[]>;
|
|
39
|
-
declare function mountAgent(initialOptions: HeroUIAgentProps, serializeTools: ClientToolManifestSerializer): AgentHostController;
|
|
40
|
-
|
|
41
5
|
type HostedFrameBounds = {
|
|
42
6
|
bottom: number;
|
|
43
7
|
left: number;
|
|
@@ -78,6 +42,112 @@ type HostPageLayout = {
|
|
|
78
42
|
} | null;
|
|
79
43
|
};
|
|
80
44
|
|
|
45
|
+
declare const HEROUI_AGENT_HOSTED_ORIGIN: "https://agent.heroui.pro";
|
|
46
|
+
declare const HEROUI_AGENT_HOSTED_STAGING_ORIGIN: "https://staging-agent.heroui.pro";
|
|
47
|
+
declare const HEROUI_AGENT_BRIDGE_MAX_MESSAGE_BYTES: number;
|
|
48
|
+
declare const HEROUI_AGENT_BRIDGE_MAX_PERSISTENCE_BYTES: number;
|
|
49
|
+
type AgentBridgeJsonValue = boolean | null | number | string | AgentBridgeJsonValue[] | {
|
|
50
|
+
[key: string]: AgentBridgeJsonValue;
|
|
51
|
+
};
|
|
52
|
+
type HostedAgentToolManifest = {
|
|
53
|
+
description: string;
|
|
54
|
+
displayName?: string;
|
|
55
|
+
icon?: ClientToolIcon;
|
|
56
|
+
iconColor?: string;
|
|
57
|
+
inputSchema: Record<string, unknown>;
|
|
58
|
+
name: string;
|
|
59
|
+
needsApproval?: boolean;
|
|
60
|
+
};
|
|
61
|
+
type HostedAgentInit = {
|
|
62
|
+
restoreSession?: boolean;
|
|
63
|
+
localStorage: Record<string, string>;
|
|
64
|
+
sessionStorage: Record<string, string>;
|
|
65
|
+
props: Record<string, unknown>;
|
|
66
|
+
tools: HostedAgentToolManifest[];
|
|
67
|
+
};
|
|
68
|
+
type AgentPersistenceRequest = {
|
|
69
|
+
store: "composer-image-drafts" | "message-outboxes";
|
|
70
|
+
operation: "get" | "put" | "delete" | "deletePrefix";
|
|
71
|
+
key?: string;
|
|
72
|
+
prefix?: string;
|
|
73
|
+
value?: unknown;
|
|
74
|
+
};
|
|
75
|
+
type AgentBridgePayloads = {
|
|
76
|
+
"host.command": {
|
|
77
|
+
name: string;
|
|
78
|
+
payload?: unknown;
|
|
79
|
+
};
|
|
80
|
+
"host.init": HostedAgentInit;
|
|
81
|
+
"host.update": HostedAgentInit;
|
|
82
|
+
"host.rpc-result": {
|
|
83
|
+
value: unknown;
|
|
84
|
+
};
|
|
85
|
+
"host.rpc-error": {
|
|
86
|
+
error: string;
|
|
87
|
+
};
|
|
88
|
+
"host.upload-data-source": {
|
|
89
|
+
toolCallId: string;
|
|
90
|
+
upload: UploadAgentDataSourceInput;
|
|
91
|
+
};
|
|
92
|
+
"iframe.ready": undefined;
|
|
93
|
+
"iframe.reload": undefined;
|
|
94
|
+
"iframe.auth-request": undefined;
|
|
95
|
+
"iframe.context-request": undefined;
|
|
96
|
+
"iframe.feedback": AgentResponseFeedback;
|
|
97
|
+
"iframe.persistence": AgentPersistenceRequest;
|
|
98
|
+
"iframe.state": HostedFrameState;
|
|
99
|
+
"iframe.storage": {
|
|
100
|
+
operation: "set" | "remove" | "clear";
|
|
101
|
+
storage: "local" | "session";
|
|
102
|
+
key?: string;
|
|
103
|
+
value?: string;
|
|
104
|
+
};
|
|
105
|
+
"iframe.rpc-result": {
|
|
106
|
+
value: unknown;
|
|
107
|
+
};
|
|
108
|
+
"iframe.rpc-error": {
|
|
109
|
+
error: string;
|
|
110
|
+
};
|
|
111
|
+
"iframe.error": AgentError;
|
|
112
|
+
"iframe.status": AgentStatus;
|
|
113
|
+
"iframe.tool-cancel": {
|
|
114
|
+
idempotencyKey: string;
|
|
115
|
+
};
|
|
116
|
+
"iframe.tool-execute": {
|
|
117
|
+
args: unknown;
|
|
118
|
+
conversationId: string;
|
|
119
|
+
idempotencyKey: string;
|
|
120
|
+
name: string;
|
|
121
|
+
toolCallId: string;
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
type AgentBridgeMessageType = keyof AgentBridgePayloads;
|
|
125
|
+
type AgentBridgeEnvelope<T extends AgentBridgeMessageType = AgentBridgeMessageType> = T extends AgentBridgeMessageType ? {
|
|
126
|
+
nonce: string;
|
|
127
|
+
payload?: AgentBridgePayloads[T];
|
|
128
|
+
requestId: string;
|
|
129
|
+
sessionId: string;
|
|
130
|
+
type: T;
|
|
131
|
+
} : never;
|
|
132
|
+
declare function createAgentBridgeEnvelope<T extends AgentBridgeMessageType>(sessionId: string, nonce: string, type: T, payload?: AgentBridgePayloads[T], requestId?: string): AgentBridgeEnvelope<T>;
|
|
133
|
+
declare function parseAgentBridgeEnvelope(value: unknown): AgentBridgeEnvelope | null;
|
|
134
|
+
declare function isAgentBridgeJsonValue(value: unknown, seen?: Set<object>): value is AgentBridgeJsonValue;
|
|
135
|
+
declare function estimateAgentBridgeMessageBytes(value: unknown): number;
|
|
136
|
+
|
|
137
|
+
/** Bounds even callbacks that do not cooperate with cancellation. */
|
|
138
|
+
declare function abortable<T>(signal: AbortSignal, work: () => Promise<T>): Promise<T>;
|
|
139
|
+
declare function withDeadline<T>(milliseconds: number, work: (signal: AbortSignal) => Promise<T>, parent?: AbortSignal): Promise<T>;
|
|
140
|
+
|
|
141
|
+
declare function createAgentError(cause: unknown, phase?: AgentStatus): AgentError;
|
|
142
|
+
|
|
143
|
+
type AgentHostController = AgentController & {
|
|
144
|
+
destroy: () => void;
|
|
145
|
+
subscribe: (listener: () => void) => () => void;
|
|
146
|
+
update: (options: HeroUIAgentProps) => void;
|
|
147
|
+
};
|
|
148
|
+
type ClientToolManifestSerializer = (tools: ClientTool[]) => HostedAgentToolManifest[] | Promise<HostedAgentToolManifest[]>;
|
|
149
|
+
declare function mountAgent(initialOptions: HeroUIAgentProps, serializeTools: ClientToolManifestSerializer): AgentHostController;
|
|
150
|
+
|
|
81
151
|
/**
|
|
82
152
|
* Requests a short-lived HeroUI Agent credential through the host
|
|
83
153
|
* application's server callback. Refresh and request de-duplication are
|
|
@@ -90,6 +160,7 @@ declare class EmbedSessionManager {
|
|
|
90
160
|
private failure;
|
|
91
161
|
private generation;
|
|
92
162
|
private pending;
|
|
163
|
+
private controller;
|
|
93
164
|
constructor(agentId: string, getAuthToken: GetAuthToken);
|
|
94
165
|
clear(): void;
|
|
95
166
|
/**
|
|
@@ -105,4 +176,4 @@ declare class EmbedSessionManager {
|
|
|
105
176
|
private refresh;
|
|
106
177
|
}
|
|
107
178
|
|
|
108
|
-
export { type AgentBridgeEnvelope, type AgentBridgeJsonValue, type AgentHostController, type ClientToolManifestSerializer, EmbedSessionManager, HEROUI_AGENT_BRIDGE_MAX_MESSAGE_BYTES, HEROUI_AGENT_BRIDGE_MAX_PERSISTENCE_BYTES, HEROUI_AGENT_HOSTED_ORIGIN, HEROUI_AGENT_HOSTED_STAGING_ORIGIN, type HostPageLayout, type HostedAgentToolManifest, type HostedFrameState, createAgentBridgeEnvelope, estimateAgentBridgeMessageBytes, isAgentBridgeJsonValue, mountAgent, parseAgentBridgeEnvelope };
|
|
179
|
+
export { type AgentBridgeEnvelope, type AgentBridgeJsonValue, type AgentBridgeMessageType, type AgentBridgePayloads, type AgentHostController, type AgentPersistenceRequest, type ClientToolManifestSerializer, EmbedSessionManager, HEROUI_AGENT_BRIDGE_MAX_MESSAGE_BYTES, HEROUI_AGENT_BRIDGE_MAX_PERSISTENCE_BYTES, HEROUI_AGENT_HOSTED_ORIGIN, HEROUI_AGENT_HOSTED_STAGING_ORIGIN, type HostPageLayout, type HostedAgentInit, type HostedAgentToolManifest, type HostedFrameState, abortable, createAgentBridgeEnvelope, createAgentError, estimateAgentBridgeMessageBytes, isAgentBridgeJsonValue, mountAgent, parseAgentBridgeEnvelope, withDeadline };
|
package/dist/internal/host.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as r,b as t,c as a,d as l,e as n}from"../chunk-KMVOOEIK.js";import"../chunk-2W6CUSN3.js";import{c as o,d as e,e as m,f as p,g as s,h as i,i as f,j as x,k as g,l as A}from"../chunk-YPHOJDYK.js";export{l as EmbedSessionManager,s as HEROUI_AGENT_BRIDGE_MAX_MESSAGE_BYTES,i as HEROUI_AGENT_BRIDGE_MAX_PERSISTENCE_BYTES,m as HEROUI_AGENT_HOSTED_ORIGIN,p as HEROUI_AGENT_HOSTED_STAGING_ORIGIN,r as abortable,f as createAgentBridgeEnvelope,a as createAgentError,A as estimateAgentBridgeMessageBytes,g as isAgentBridgeJsonValue,n as mountAgent,x as parseAgentBridgeEnvelope,o as parseClientToolArgs,e as resolveDirectToolAction,t as withDeadline};
|
|
@@ -1,7 +1,7 @@
|
|
|
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-DDaVFBVG.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import {
|
|
4
|
-
export {
|
|
3
|
+
import { M as ClientTool } from '../types-Cuqd4_1K.js';
|
|
4
|
+
export { Q as DEFAULT_MARKDOWN_ANIMATION } from '../types-Cuqd4_1K.js';
|
|
5
5
|
import 'react';
|
|
6
6
|
|
|
7
7
|
declare const agentIdentityIdSchema: z.ZodString;
|
|
@@ -41,7 +41,7 @@ type AgentAuthProfile = z.infer<typeof agentAuthProfileSchema>;
|
|
|
41
41
|
type AgentAuthToken = z.infer<typeof agentAuthTokenSchema>;
|
|
42
42
|
type CreateAgentAuthTokenRequest = z.infer<typeof createAgentAuthTokenRequestSchema>;
|
|
43
43
|
|
|
44
|
-
declare const RESERVED_AGENT_TOOL_NAMES: readonly ["callMcpTool", "composeUI", "executeSandbox", "generateFile", "
|
|
44
|
+
declare const RESERVED_AGENT_TOOL_NAMES: readonly ["readConversationHistory", "callMcpTool", "composeUI", "executeSandbox", "generateFile", "getUIComponents", "readSkill", "renderComponent", "renderDocument", "searchKnowledge", "searchMcpTools", "searchWeb"];
|
|
45
45
|
declare const RESERVED_AGENT_TOOL_PREFIX = "mcp_";
|
|
46
46
|
declare const MAX_CLIENT_TOOLS = 20;
|
|
47
47
|
declare const MAX_CLIENT_TOOLS_BYTES: number;
|
package/dist/internal/shared.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as l}from"../chunk-AR424OVX.js";import{a,b as r}from"../chunk-
|
|
1
|
+
import{a as l}from"../chunk-AR424OVX.js";import{a,b as r}from"../chunk-2W6CUSN3.js";import{a as m,b as A,c as p,d as s,e as c,f as h,g as u}from"../chunk-KQ3FZPFS.js";import"../chunk-YPHOJDYK.js";import{z as e}from"zod";var g=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(i=>!g.has(i.toLowerCase()),{message:"Identity id is reserved"}),n=e.discriminatedUnion("type",[e.object({id:t,type:e.literal("anonymous")}),e.object({id:t,type:e.literal("user")})]),o=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()}),T=e.object({anonymousId:t.optional(),identity:n,profile:o.optional()}),S=e.object({expiresAt:e.number().int().positive(),token:e.string().trim().min(1)});export{l as DEFAULT_MARKDOWN_ANIMATION,r as HEROUI_AGENT_API_BASE_URL,a as HEROUI_AGENT_SDK_VERSION,p as MAX_CLIENT_TOOLS,s as MAX_CLIENT_TOOLS_BYTES,m as RESERVED_AGENT_TOOL_NAMES,A as RESERVED_AGENT_TOOL_PREFIX,n as agentAuthIdentitySchema,o as agentAuthProfileSchema,S as agentAuthTokenSchema,t as agentIdentityIdSchema,c as clientToolManifestEntrySchema,h as clientToolsSchema,T as createAgentAuthTokenRequestSchema,u as serializeClientTools};
|
package/dist/next.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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
|
|
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 DEFAULT_MARKDOWN_ANIMATION, R as GetAuthToken, S as GetAuthTokenContext, T as HeroUIAgentProps, U as UploadAgentDataSourceInput, V as createToolHelper } from './types-Cuqd4_1K.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-DDaVFBVG.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-MUJYIDA4.js";import"./chunk-KMVOOEIK.js";import{a as p}from"./chunk-AR424OVX.js";import{a as r,b as e}from"./chunk-2W6CUSN3.js";import{a as o}from"./chunk-YPHOJDYK.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};
|
|
@@ -35,6 +35,7 @@ type UploadAgentDataSourceInput = Readonly<{
|
|
|
35
35
|
* return the original result instead of applying the side effect twice.
|
|
36
36
|
*/
|
|
37
37
|
type ClientToolExecutionContext = Readonly<{
|
|
38
|
+
signal: AbortSignal;
|
|
38
39
|
conversationId: string;
|
|
39
40
|
idempotencyKey: string;
|
|
40
41
|
toolCallId: string;
|
|
@@ -164,7 +165,7 @@ type AgentPermissionMode = "ask" | "auto" | "full";
|
|
|
164
165
|
*/
|
|
165
166
|
type AgentAttachmentContentType = string;
|
|
166
167
|
/**
|
|
167
|
-
* Model id from the hosted HeroUI Agent catalog, e.g. `"google/gemini-3.
|
|
168
|
+
* Model id from the hosted HeroUI Agent catalog, e.g. `"google/gemini-3.8-flash"`.
|
|
168
169
|
* The hosted Agent owns the catalog: retired ids resolve to their replacement
|
|
169
170
|
* and unknown ids fall back to the default model, so new models never require
|
|
170
171
|
* an SDK update. See https://heroui.pro/docs/agents/api-reference/models.
|
|
@@ -425,11 +426,32 @@ type AgentAuthToken = {
|
|
|
425
426
|
};
|
|
426
427
|
/** Context supplied whenever the SDK needs a fresh browser credential. */
|
|
427
428
|
type GetAuthTokenContext = {
|
|
429
|
+
signal: AbortSignal;
|
|
428
430
|
anonymousId: string;
|
|
429
431
|
agentId: string;
|
|
430
432
|
};
|
|
431
433
|
type GetAuthToken = (context: GetAuthTokenContext) => Promise<AgentAuthToken>;
|
|
434
|
+
type AgentStatus = "loading" | "authenticating" | "connecting" | "ready" | "generating" | "finishing" | "reconnecting" | "failed";
|
|
435
|
+
type AgentError = {
|
|
436
|
+
category: "authentication" | "connection" | "configuration" | "chunk" | "rate_limit" | "credits" | "deleted" | "approval" | "unknown";
|
|
437
|
+
diagnosticId: string;
|
|
438
|
+
message: string;
|
|
439
|
+
phase: AgentStatus;
|
|
440
|
+
retryable: boolean;
|
|
441
|
+
};
|
|
432
442
|
type HeroUIAgentProps = {
|
|
443
|
+
/** Interface locale, or "auto" to match browser preferences. SDK override > agent default > English. */
|
|
444
|
+
locale?: string;
|
|
445
|
+
/** Copy by language tag, beneath explicit composer/startScreen text. Useful with locale="auto". */
|
|
446
|
+
translations?: Record<string, {
|
|
447
|
+
greeting?: string;
|
|
448
|
+
subtitle?: string;
|
|
449
|
+
placeholder?: string;
|
|
450
|
+
disclaimer?: string | false;
|
|
451
|
+
prompts?: string[];
|
|
452
|
+
}>;
|
|
453
|
+
onError?: (error: AgentError) => void;
|
|
454
|
+
onStatusChange?: (status: AgentStatus) => void;
|
|
433
455
|
/** Internal — for HeroUI platform development only. */
|
|
434
456
|
_api?: AgentApiOverrides;
|
|
435
457
|
appearance?: AgentAppearance;
|
|
@@ -444,7 +466,7 @@ type HeroUIAgentProps = {
|
|
|
444
466
|
context?: AgentSharedContext;
|
|
445
467
|
/**
|
|
446
468
|
* Fetches a short-lived browser credential from the host application's
|
|
447
|
-
* server. Never expose a
|
|
469
|
+
* server. Never expose a workspace API key in browser code.
|
|
448
470
|
*/
|
|
449
471
|
getAuthToken: GetAuthToken;
|
|
450
472
|
/** Streaming Markdown animation and caret preferences. */
|
|
@@ -546,4 +568,4 @@ type AgentController = {
|
|
|
546
568
|
toggle: () => void;
|
|
547
569
|
};
|
|
548
570
|
|
|
549
|
-
export { type AgentApiOverrides as A, type
|
|
571
|
+
export { type AgentApiOverrides as A, type AgentResponseFeedback as B, type AgentSharedContext as C, type AgentShouldCloseOnInteractOutside as D, type AgentStartScreenOptions as E, type AgentStatus as F, type AgentSurfaceVariant as G, type AgentThemeColor as H, type AgentThemeColors as I, type AgentThemeOptions as J, type AgentTypography as K, type AgentViewMode as L, type ClientTool as M, type ClientToolExecutionContext as N, type ClientToolIcon as O, type ClientToolStatus as P, DEFAULT_MARKDOWN_ANIMATION as Q, type GetAuthToken as R, type GetAuthTokenContext as S, type HeroUIAgentProps as T, type UploadAgentDataSourceInput as U, createToolHelper as V, parseClientToolArgs as W, resolveDirectToolAction as X, type AgentAppearance as a, type AgentAttachmentContentType as b, type AgentAuthToken as c, type AgentCapabilities as d, type AgentColorScheme as e, type AgentComponentExportFormat as f, type AgentComposerOptions as g, type AgentContext as h, type AgentController as i, type AgentDataSource as j, type AgentDataSourceFormat as k, type AgentDesignTheme as l, type AgentError as m, type AgentFeedbackReason as n, type AgentLauncherOptions as o, type AgentLauncherPosition as p, type AgentMarkdownAnimation as q, type AgentMarkdownAnimationOptions as r, type AgentMarkdownCaret as s, type AgentMarkdownOptions as t, type AgentMessageAction as u, type AgentModelId as v, type AgentPanelOptions as w, type AgentPermissionMode as x, type AgentPermissionOptions as y, type AgentRadius as z };
|
|
@@ -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.8";
|
|
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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@heroui/agent",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.8",
|
|
4
4
|
"description": "Embed a hosted HeroUI Agent that turns application data into interactive UI.",
|
|
5
5
|
"homepage": "https://heroui.pro/agents",
|
|
6
6
|
"bugs": {
|
|
@@ -97,7 +97,7 @@
|
|
|
97
97
|
"react-dom": "19.2.6",
|
|
98
98
|
"tsup": "8.5.0",
|
|
99
99
|
"typescript": "5.9.3",
|
|
100
|
-
"vitest": "
|
|
100
|
+
"vitest": "5.0.0",
|
|
101
101
|
"@heroui-pro/config": "0.0.0"
|
|
102
102
|
},
|
|
103
103
|
"scripts": {
|
package/dist/chunk-3UR3CJAJ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function u(){return function(t){return t}}function p(e){return!!(e&&typeof e=="object"&&typeof e.safeParse=="function")}function g(e,t){return p(e.parameters)?e.parameters.parse(t):t}function l(e,t){let n=e.get(t);return!n||n.needsApproval?null:n}var f="https://agent.heroui.pro",y="https://staging-agent.heroui.pro",T=262144,A=57671680;function E(e,t,n,o,r=crypto.randomUUID()){return{nonce:t,...o===void 0?{}:{payload:o},requestId:r,sessionId:e,type:n}}function m(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.sessionId!="string"||!i(t.sessionId)||typeof t.nonce!="string"||!i(t.nonce)||typeof t.requestId!="string"||!i(t.requestId)||typeof t.type!="string"||t.type.length===0||t.type.length>80)return null;let n=t.type==="iframe.persistence"||t.type==="host.upload-data-source"||t.type==="host.rpc-result"?57671680:262144;return c(e)>n?null:{nonce:t.nonce,...Object.hasOwn(t,"payload")?{payload:t.payload}:{},requestId:t.requestId,sessionId:t.sessionId,type:t.type}}function a(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);let n=r=>r===void 0||a(r,t),o=Array.isArray(e)?e.every(n):Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(n);return t.delete(e),o}function c(e){return s(e,new Set)}function s(e,t){if(e==null)return 4;if(typeof e=="string")return new TextEncoder().encode(e).byteLength+2;if(typeof e=="boolean"||typeof e=="number")return 8;if(typeof e!="object"||t.has(e))return Number.POSITIVE_INFINITY;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof Blob<"u"&&e instanceof Blob)return e.size;t.add(e);let n=2;for(let[o,r]of Object.entries(e))if(n+=s(o,t)+s(r,t),!Number.isFinite(n))break;return t.delete(e),n}function i(e){return e.length>0&&e.length<=128&&/^[A-Za-z0-9._:-]+$/.test(e)}export{u as a,p as b,g as c,l as d,f as e,y as f,T as g,A as h,E as i,m as j,a as k,c as l};
|
package/dist/chunk-BYV3XUCN.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as i,k as a}from"./chunk-3UR3CJAJ.js";import{z as t}from"zod";var c=["callMcpTool","composeUI","executeSandbox","generateFile","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],m="mcp_",p=20,l=16*1024,d=t.object({description:t.string().trim().min(1).max(1e3),inputSchema:t.record(t.string(),t.unknown()),name:t.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).refine(e=>!c.includes(e)&&!e.toLowerCase().startsWith(m),"Client tool name is reserved by the HeroUI Agent runtime"),needsApproval:t.boolean().optional()}),f=t.array(d).max(p).superRefine((e,n)=>{let o=new Set;for(let r of e)o.has(r.name)&&n.addIssue({code:"custom",message:`Duplicate client tool name: ${r.name}`}),o.add(r.name);new TextEncoder().encode(JSON.stringify(e)).byteLength>l&&n.addIssue({code:"custom",message:"Client tool manifest exceeds 16KB"})});function u(e){let n=i(e.parameters)?t.toJSONSchema(e.parameters):e.parameters;if(!a(n))throw new Error(`Client tool ${e.name} parameters must be a JSON-serializable schema`);return s(n)}function s(e){return Array.isArray(e)?e.map(s):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,s(o)])):e}function E(e){return f.parse(e.map(n=>({description:n.description,inputSchema:u(n),name:n.name,...n.needsApproval?{needsApproval:!0}:{}})))}export{c as a,m as b,p as c,l as d,d as e,f,E as g};
|
package/dist/chunk-L5DXTMC2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as B}from"./chunk-ZD5U6JIE.js";import{c as q,e as G,f as K,i as J,j as V,k as Y}from"./chunk-3UR3CJAJ.js";function X(e){return`heroui-agent:anonymous:${e}`}function de(e){return e instanceof Error?e:new Error("Auth token request failed")}var S=class{constructor(t,n){this.agentId=t;this.getAuthToken=n}cached=null;failure=null;generation=0;pending=null;clear(){this.generation+=1,this.cached=null,this.failure=null,this.pending=null}reset(){this.clear();try{localStorage.removeItem(X(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 r=await n;return t!==this.generation?this.get():(this.cached=r,this.failure=null,r.token)}catch(r){throw t===this.generation&&(this.failure={error:de(r),retryAt:Date.now()+5e3}),r}finally{this.pending===n&&(this.pending=null)}}async subjectHash(){let t=await this.get(),n=ce(t),r=typeof n.sub=="string"?n.sub:"anonymous",l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${this.agentId}:${r}`));return Array.from(new Uint8Array(l),u=>u.toString(16).padStart(2,"0")).join("").slice(0,24)}anonymousId(){let t=X(this.agentId);try{let n=localStorage.getItem(t);if(n)return n;let r=crypto.randomUUID();return localStorage.setItem(t,r),r}catch{return crypto.randomUUID()}}expiresAt(t){return t.expiresAt}async refresh(){let t=await this.getAuthToken({agentId:this.agentId,anonymousId:this.anonymousId()});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 ce(e){try{let t=e.split(".")[1];if(!t)return{};let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=n.padEnd(Math.ceil(n.length/4)*4,"=");return JSON.parse(atob(r))}catch{return{}}}function Q(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 y(e,t,n){return{background:"transparent",border:"0",clipPath:ue(e,t,n),colorScheme:"normal",height:"100dvh",inset:"0",position:"fixed",width:"100vw",zIndex:t.appearance?.zIndex??40}}function Z(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!=="floating"&&t.viewMode!=="sidebar"?null:{bounds:pe(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:H(t.sidebarWidth)?t.sidebarWidth:null,viewMode:t.viewMode}}function ee(){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 x(e,t,n,r){let l=t.open||t.closing;if(!l&&!e.active)return;l&&(e.active=!0);let u=l&&(r||t.viewMode==="sidebar"&&t.expanded);ne(e,u);let a=l&&t.viewMode==="sidebar"&&!t.expanded&&!r?ge(t,n):e.original.rootMarginRight;e.root.style.transition=e.original.rootTransition,e.root.style.marginRight=a,l||(e.active=!1)}function te(e){ne(e,!1),e.root.style.marginRight=e.original.rootMarginRight,e.root.style.transition=e.original.rootTransition,e.active=!1}function ue(e,t,n){let r=e.open||e.closing;if(r&&(n||e.overlayOpen))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)`;let l=t.appearance?.launcher,u=l?.position==="bottom-left",p=(l?.offset?.x??24)+60,a=(l?.offset?.y??24)+60;if(!r)return u?`inset(calc(100% - ${a}px) calc(100% - ${p}px) 0px 0px)`:`inset(calc(100% - ${a}px) 0px 0px calc(100% - ${p}px))`;if(e.viewMode==="sidebar")return`inset(0px 0px 0px calc(100% - (${M(t.appearance?.panel?.initialWidth??420)} + 16px)))`;let h=M(t.appearance?.panel?.initialWidth??440),E=`calc(100% - min(calc(${M(t.appearance?.panel?.initialHeight??"max(420px, 56dvh)")} + 32px), 100dvh))`;return u?`inset(${E} calc(100% - min(calc(${h} + 32px), 100vw)) 0px 0px)`:`inset(${E} 0px 0px calc(100% - min(calc(${h} + 32px), 100vw)))`}function pe(e){if(!e||typeof e!="object")return null;let t=e;return!H(t.top)||!H(t.right)||!H(t.bottom)||!H(t.left)||t.right<t.left||t.bottom<t.top?null:{bottom:t.bottom,left:t.left,right:t.right,top:t.top}}function H(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1e5}function ge(e,t){return e.sidebarWidth===null?M(t.appearance?.panel?.initialWidth??420):`${Math.round(e.sidebarWidth)}px`}function M(e){return typeof e=="number"?`${Math.round(e)}px`:e}function ne(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:r}=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,r)}catch{}}}var fe=16*1024,he=64*1024;function Oe(e,t){let n=e;if(!n?.agentId||typeof n.getAuthToken!="function")throw new Error("HeroUIAgent.mount requires agentId and getAuthToken");let r=crypto.randomUUID(),l=crypto.randomUUID(),u=(n._api?.baseUrl??B).replace(/\/$/,""),p=Ie(u,n._api?.embedOrigin),a=document.createElement("iframe"),h=new Map,w=[],E=new Set,b=new Map,k=new Set,v=ee(),P=new S(n.agentId,n.getAuthToken),s=Q(n),W=null,m=!1,A=!1,I=null,U=!1,C=!1,_=new URL("/embed",p);_.searchParams.set("agentId",n.agentId),_.hash=new URLSearchParams({nonce:l,parentOrigin:window.location.origin,sessionId:r}).toString(),a.allow="microphone; clipboard-write",a.referrerPolicy="origin",a.setAttribute("sandbox","allow-downloads allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),a.src=_.toString(),a.title="HeroUI Agent",Object.assign(a.style,y(s,n,window.innerWidth<640)),document.body.append(a);let g=(o,i,d)=>{C||a.contentWindow?.postMessage(J(r,l,o,i,d),p)},ie=(o,i)=>{let d=crypto.randomUUID();return new Promise((c,f)=>{let F=window.setTimeout(()=>{h.delete(d),f(new Error(`HeroUI Agent iframe request timed out: ${o}`))},3e4);h.set(d,{reject:f,resolve:c,timer:F}),g(o,i,d)})},$=0,N="",z=async(o,i=!1)=>{let d=++$,c=await ye(n,t);if(C||d!==$)return;let f=JSON.stringify({props:c.props,tools:c.tools});!i&&f===N||(N=f,g(o,c))},T=(o,i)=>{if(!s.mounted){w.push({name:o,payload:i}),w.length>32&&w.shift();return}g("host.command",{name:o,payload:i})},O=o=>{m=o,o||(A=!1),T(o?"show":"hide")},se=()=>{if(s.mounted)for(let o of w.splice(0))g("host.command",o)},ae=()=>{A=s.mounted&&m&&!s.closing,s={...s,bounds:null,closing:!1,mounted:!1,open:A,ready:!1},U=!1;for(let o of k)o();Object.assign(a.style,y(s,n,window.innerWidth<640)),x(v,s,n,window.innerWidth<640)},j=o=>{if(o.origin!==p||o.source!==a.contentWindow)return;let i=V(o.data);if(!(!i||i.sessionId!==r||i.nonce!==l)){if(i.type==="iframe.rpc-result"||i.type==="iframe.rpc-error"){we(i,h);return}Ae(E,i.requestId)&&le(i)}},le=async o=>{try{if(o.type==="iframe.ready"){(s.mounted||s.ready)&&ae(),await z("host.init",!0);return}if(o.type==="iframe.state"){let i=Z(o.payload);if(i){let d=s.open||s.closing,c=i;A?i.mounted?(A=!1,i.open||(g("host.command",{name:"show"}),c={...i,bounds:null,closing:!1,open:!0,sidebarWidth:i.sidebarWidth??s.sidebarWidth})):c={...i,bounds:null,closing:!1,open:!0,sidebarWidth:i.sidebarWidth??s.sidebarWidth}:i.open?m=!0:(i.closing||s.open||s.closing)&&(m=!1);let f=c.open||c.closing;f&&!d&&(W=document.activeElement),!f&&d&&W?.focus({preventScroll:!0}),s=c,f&&s.expanded?a.dataset.expanded="true":a.removeAttribute("data-expanded");for(let F of k)F();Object.assign(a.style,y(s,n,window.innerWidth<640)),x(v,s,n,window.innerWidth<640),se(),s.ready&&!U&&(U=!0,n.onReady?.())}return}if(o.type==="iframe.auth-request"){let i=await P.get(),d=await fetch(`${u}/v1/agents/${encodeURIComponent(n.agentId)}/embed-sessions`,{body:JSON.stringify({iframeOrigin:p,sessionId:r}),cache:"no-store",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},method:"POST"});if(!d.ok)throw new Error("Unable to create HeroUI Agent iframe session");g("host.rpc-result",{value:await d.json()},o.requestId);return}if(o.type==="iframe.context-request"){let i=re(await n.context?.page?.()??{},fe,"Agent page context");g("host.rpc-result",{value:i},o.requestId);return}if(o.type==="iframe.tool-execute"){let i=be(o.payload),d=n.tools?.find(f=>f.name===i.name);if(!d)throw new Error(`Unknown client tool: ${i.name}`);let c=b.get(i.idempotencyKey);c||(c=me(d,i,n,ie),b.set(i.idempotencyKey,c),b.size>2048&&b.delete(b.keys().next().value)),g("host.rpc-result",{value:await c},o.requestId);return}if(o.type==="iframe.feedback"){await n.onFeedback?.(o.payload);return}if(o.type==="iframe.storage"){ve(o.payload);return}if(o.type==="iframe.persistence"){let i=await import("./persistence-YI6JSYCT.js").then(({executeAgentHostPersistence:d})=>d(n.agentId,o.payload));g("host.rpc-result",{value:i},o.requestId)}}catch(i){console.error("HeroUI Agent bridge request failed",i),g("host.rpc-error",{error:i instanceof Error?i.message:"Request failed"},o.requestId)}},D=o=>{o.composedPath().includes(a)||s.open&&s.viewMode==="floating"&&(n.appearance?.shouldCloseOnInteractOutside??!0)&&O(!1)},L=()=>{s={...s,bounds:null},Object.assign(a.style,y(s,n,window.innerWidth<640)),x(v,s,n,window.innerWidth<640)},R=()=>{document.visibilityState==="visible"&&(s={...s,bounds:null},Object.assign(a.style,y(s,n,window.innerWidth<640)),x(v,s,n,window.innerWidth<640),m&&s.mounted&&g("host.command",{name:"show"}),I!==null&&window.cancelAnimationFrame(I),I=window.requestAnimationFrame(()=>{I=null,Object.assign(a.style,y(s,n,window.innerWidth<640))}))};return window.addEventListener("message",j),window.addEventListener("pointerdown",D,!0),window.addEventListener("resize",L),window.addEventListener("pageshow",R),window.visualViewport?.addEventListener("resize",L),document.addEventListener("visibilitychange",R),{destroy:()=>{C=!0,window.removeEventListener("message",j),window.removeEventListener("pointerdown",D,!0),window.removeEventListener("resize",L),window.removeEventListener("pageshow",R),window.visualViewport?.removeEventListener("resize",L),document.removeEventListener("visibilitychange",R),I!==null&&window.cancelAnimationFrame(I);for(let o of h.values())window.clearTimeout(o.timer),o.reject(new Error("HeroUI Agent iframe was removed"));h.clear(),w.length=0,k.clear(),te(v),a.remove()},hide:()=>O(!1),newConversation:o=>{m=!0,T("newConversation",{prompt:o})},preload:()=>T("preload"),get ready(){return s.ready},refreshAuth:()=>{P.clear(),T("refreshAuth")},show:()=>O(!0),shutdown:()=>{m=!1,A=!1,P.reset(),T("shutdown")},subscribe:o=>(k.add(o),()=>k.delete(o)),toggle:()=>O(!m),update:o=>{if(o.agentId!==n.agentId)throw new Error("HeroUI Agent agentId cannot change without remounting");o.getAuthToken!==n.getAuthToken&&(P=new S(o.agentId,o.getAuthToken)),n=o,Object.assign(a.style,y(s,n,window.innerWidth<640)),x(v,s,n,window.innerWidth<640),s.ready&&z("host.update")}}}async function me(e,t,n,r){let l={conversationId:t.conversationId,idempotencyKey:t.idempotencyKey,toolCallId:t.toolCallId,uploadDataSource:async p=>await r("host.upload-data-source",{toolCallId:t.toolCallId,upload:p})},u=await e.execute(q(e,t.args),n.context??{},l)??null;return re(u,he,`Client tool ${e.name} result`)}async function ye(e,t){let{context:n,getAuthToken:r,onFeedback:l,onReady:u,tools:p,...a}=e,h=await t(p??[]);return{localStorage:oe(window.localStorage),props:JSON.parse(JSON.stringify(a)),sessionStorage:oe(window.sessionStorage),tools:h}}function we(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 r=e.payload;n.reject(new Error(typeof r?.error=="string"?r.error:"Iframe request failed"))}else{let r=e.payload;n.resolve(r?.value)}}function be(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 re(e,t,n){if(!Y(e))throw new Error(`${n} must be JSON-serializable`);let r=JSON.stringify(e);if(new TextEncoder().encode(r).byteLength>t)throw new Error(`${n} exceeds ${Math.round(t/1024)} KiB`);return JSON.parse(r)}function oe(e){let t={};try{for(let n=0;n<e.length;n+=1){let r=e.key(n);r?.startsWith("heroui-agent:")&&(t[r]=e.getItem(r)??"")}}catch{}return t}function ve(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 r=n.length-1;r>=0;r-=1){let l=n.key(r);l?.startsWith("heroui-agent:")&&n.removeItem(l)}}catch{}}function Ae(e,t){return e.has(t)?!1:(e.add(t),e.size>2048&&e.delete(e.values().next().value),!0)}function Ie(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")?K:G}export{S as a,Oe as b};
|
package/dist/chunk-LMNV4H5B.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as C}from"./chunk-L5DXTMC2.js";import{b as A}from"./chunk-3UR3CJAJ.js";import{useEffect as k,useLayoutEffect as d,useMemo as x,useRef as p,useState as O,useSyncExternalStore as w}from"react";var i=new Map,f=new Set;function m(){for(let e of f)e()}function H(e){return f.add(e),()=>f.delete(e)}function a(e,n,r){let o=e?i.get(e):[...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 R(e){let n=w(H,()=>(e?i.get(e):[...i.values()].at(-1))?.ready??!1,()=>!1);return x(()=>({hide:()=>a(e,"hide"),newConversation:r=>a(e,"newConversation",r),preload:()=>a(e,"preload"),ready:n,refreshAuth:()=>a(e,"refreshAuth"),show:()=>a(e,"show"),shutdown:()=>a(e,"shutdown"),toggle:()=>a(e,"toggle")}),[e,n])}async function P(e){let{serializeClientTools:n}=await import("./client-tools-manifest-2T23ADUM.js");return n(e).map(o=>{let s=e.find(l=>l.name===o.name);return{...o,...s?.displayName?{displayName:s.displayName}:{},...s?.icon?{icon:s.icon}:{},...s?.iconColor?{iconColor:s.iconColor}:{}}})}function I(e){let n=p(e),r=p(null),o=p(null);d(()=>{n.current=e}),o.current||(o.current={getAuthToken:t=>n.current.getAuthToken(t),onFeedback:t=>n.current.onFeedback?.(t),onReady:()=>n.current.onReady?.()},Object.defineProperties(o.current,{context:{enumerable:!0,get(){return n.current.context}},tools:{enumerable:!0,get(){return n.current.tools}}}));let s=T(e),l=o.current;for(let t of Object.keys(l))t!=="context"&&t!=="getAuthToken"&&t!=="onFeedback"&&t!=="onReady"&&t!=="tools"&&!(t in s)&&delete l[t];Object.assign(l,s,{agentId:e.agentId});let c=o.current;d(()=>{let t=C(c,P),u=t.subscribe(m);return r.current=t,i.set(e.agentId,t),m(),()=>{u(),t.destroy(),i.get(e.agentId)===t&&i.delete(e.agentId),r.current===t&&(r.current=null),m()}},[e.agentId]);let[S,y]=O("");k(()=>{let t=e.tools??[];if(!t.some(g=>A(g.parameters))){y("");return}let u=!1;return import("./client-tools-manifest-2T23ADUM.js").then(({serializeClientTools:g})=>{u||y(JSON.stringify(g(t).map(h=>({inputSchema:h.inputSchema,name:h.name}))))}),()=>{u=!0}},[e.tools]);let b=JSON.stringify({props:T(e),tools:(e.tools??[]).map(t=>({description:t.description,displayName:t.displayName,icon:t.icon,iconColor:t.iconColor,name:t.name,needsApproval:t.needsApproval===!0,parameters:A(t.parameters)?null:t.parameters})),zodToolsSchemasKey:S});return d(()=>{r.current?.update(c)},[b]),null}function T(e){let{context:n,getAuthToken:r,onFeedback:o,onReady:s,tools:l,...c}=e;return JSON.parse(JSON.stringify(c))}export{R as a,I as b};
|
package/dist/chunk-ZD5U6JIE.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var t="1.0.0-beta.6",o="https://api.heroui.pro";export{t as a,o as b};
|