@runtypelabs/persona 4.31.0 → 4.32.0
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/activity-ui.cjs +2 -2
- package/dist/activity-ui.d.cts +11 -3
- package/dist/activity-ui.d.ts +11 -3
- package/dist/activity-ui.js +1 -1
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/approval-ui.d.cts +2 -2
- package/dist/approval-ui.d.ts +2 -2
- package/dist/artifacts-ui.d.cts +3 -3
- package/dist/artifacts-ui.d.ts +3 -3
- package/dist/background-runtime.d.cts +1 -1
- package/dist/background-runtime.d.ts +1 -1
- package/dist/chunk-CkE90FtA.js +2 -0
- package/dist/{chunk-Co4LmTFv.js → chunk-CzZBmTLd.js} +1 -1
- package/dist/chunk-DDAwu89-.js +1 -0
- package/dist/{chunk-WA9UucGf.js → chunk-DZg9bFK6.js} +1 -1
- package/dist/{chunk-BBtVdcKU.js → chunk-FEzOcZof.js} +1 -1
- package/dist/client-dispatch.js +1 -1
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/composer-actions-runtime.d.cts +2 -2
- package/dist/composer-actions-runtime.d.ts +2 -2
- package/dist/{composer-input-C2_WizXV.d.cts → composer-input-dwg_o9Z-.d.cts} +1 -1
- package/dist/{composer-input-C2_WizXV.d.ts → composer-input-dwg_o9Z-.d.ts} +1 -1
- package/dist/{composer-store-BV6kTlKv.d.cts → composer-store-Dw7Zbqxr.d.cts} +1 -1
- package/dist/{composer-store-BV6kTlKv.d.ts → composer-store-Dw7Zbqxr.d.ts} +1 -1
- package/dist/{context-mention-manager-BfZzcydV.d.cts → context-mention-manager-D2p0-JH-.d.cts} +2 -2
- package/dist/{context-mention-manager-BfZzcydV.d.ts → context-mention-manager-D2p0-JH-.d.ts} +2 -2
- package/dist/context-mentions-inline.d.cts +2 -2
- package/dist/context-mentions-inline.d.ts +2 -2
- package/dist/context-mentions.d.cts +3 -3
- package/dist/context-mentions.d.ts +3 -3
- package/dist/{defaults-DiTeXyr3.d.cts → defaults-CjX0kKzb.d.cts} +1 -1
- package/dist/{defaults-DiTeXyr3.d.ts → defaults-CjX0kKzb.d.ts} +1 -1
- package/dist/dictation-runtime.d.cts +2 -2
- package/dist/dictation-runtime.d.ts +2 -2
- package/dist/event-stream-view.d.cts +1 -1
- package/dist/event-stream-view.d.ts +1 -1
- package/dist/{fallback-speech-engine-DZ6Of7VU.d.cts → fallback-speech-engine-DmF7MczI.d.cts} +1 -1
- package/dist/{fallback-speech-engine-DZ6Of7VU.d.ts → fallback-speech-engine-DmF7MczI.d.ts} +1 -1
- package/dist/{feature-preferences-BT549D_E.d.cts → feature-preferences-CVFDt9Xf.d.cts} +1 -1
- package/dist/{feature-preferences-BT549D_E.d.ts → feature-preferences-CVFDt9Xf.d.ts} +1 -1
- package/dist/forms-ui.d.cts +2 -2
- package/dist/forms-ui.d.ts +2 -2
- package/dist/{history-confirm-dialog-Cm4oK4am.d.cts → history-confirm-dialog-DJEXsTyE.d.cts} +1 -1
- package/dist/{history-confirm-dialog-Cm4oK4am.d.ts → history-confirm-dialog-DJEXsTyE.d.ts} +1 -1
- package/dist/history-shell.d.cts +6 -6
- package/dist/history-shell.d.ts +6 -6
- package/dist/history-view.d.cts +1 -1
- package/dist/history-view.d.ts +1 -1
- package/dist/index.cjs +10 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +23 -22
- package/dist/index.js.map +1 -1
- package/dist/{loading-label-runtime-loader-DmiPDkBu.d.cts → loading-label-runtime-loader-CPxnoaoi.d.cts} +1 -1
- package/dist/{loading-label-runtime-loader-DmiPDkBu.d.ts → loading-label-runtime-loader-CPxnoaoi.d.ts} +1 -1
- package/dist/loading-label-runtime.d.cts +1 -1
- package/dist/loading-label-runtime.d.ts +1 -1
- package/dist/{message-bubble-D0rosKuK.d.cts → message-bubble-CkZGlCLC.d.cts} +1 -1
- package/dist/{message-bubble-D0rosKuK.d.ts → message-bubble-CkZGlCLC.d.ts} +1 -1
- package/dist/preferences-runtime.d.cts +1 -1
- package/dist/preferences-runtime.d.ts +1 -1
- package/dist/{preview-DRU27q-X.d.cts → preview-DdUvoLb4.d.cts} +2 -2
- package/dist/{preview-DRU27q-X.d.ts → preview-DdUvoLb4.d.ts} +2 -2
- package/dist/{registry-DRk3VMFc.d.cts → registry-Dz4iHNST.d.cts} +1 -1
- package/dist/{registry-DRk3VMFc.d.ts → registry-Dz4iHNST.d.ts} +1 -1
- package/dist/{session-Dj4bOm5y.d.cts → session-Baxp9iRK.d.cts} +14 -8
- package/dist/{session-Dj4bOm5y.d.ts → session-Baxp9iRK.d.ts} +14 -8
- package/dist/session-reconnect.d.cts +2 -2
- package/dist/session-reconnect.d.ts +2 -2
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +46 -45
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +19 -18
- package/dist/theme-editor.d.cts +2 -2
- package/dist/theme-editor.d.ts +2 -2
- package/dist/theme-reference.d.cts +2 -2
- package/dist/theme-reference.d.ts +2 -2
- package/dist/{tool-loading-animation-D1MS5Ace.d.cts → tool-loading-animation-un3kA5Ur.d.cts} +1 -1
- package/dist/{tool-loading-animation-D1MS5Ace.d.ts → tool-loading-animation-un3kA5Ur.d.ts} +1 -1
- package/dist/{turn-activity-ui-CorwdlI0.d.cts → turn-activity-ui-BGNhtMcH.d.cts} +2 -2
- package/dist/{turn-activity-ui-CorwdlI0.d.ts → turn-activity-ui-BGNhtMcH.d.ts} +2 -2
- package/dist/turn-activity-ui.d.cts +1 -1
- package/dist/turn-activity-ui.d.ts +1 -1
- package/dist/{types-CSXHl5cN.d.cts → types-BOZHQIk0.d.cts} +8 -1
- package/dist/{types-CSXHl5cN.d.ts → types-BOZHQIk0.d.ts} +8 -1
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.d.cts +2 -2
- package/dist/voice-runtime.d.ts +2 -2
- package/dist/voice-runtime.js +1 -1
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-DpDN6k-6.d.cts → webmcp-runtime-entry-DuAG1_yF.d.cts} +1 -1
- package/dist/{webmcp-runtime-entry-DpDN6k-6.d.ts → webmcp-runtime-entry-DuAG1_yF.d.ts} +1 -1
- package/dist/webmcp-runtime.d.cts +1 -1
- package/dist/webmcp-runtime.d.ts +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/activity-ui.ts +23 -0
- package/src/components/disclosure-animation.ts +5 -0
- package/src/components/tool-bubble.ts +1 -0
- package/src/index-core.ts +1 -0
- package/src/styles/widget.css +6 -0
- package/src/types.ts +8 -0
- package/src/ui.footer-visibility.test.ts +54 -0
- package/src/ui.reveal-tool-call.test.ts +258 -0
- package/src/ui.ts +127 -5
- package/dist/chunk-B3OrH9Ng.js +0 -2
- package/dist/chunk-CjhA_5Jk.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-DDAwu89-.js";const t=32768,n=49152,r=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},i=`The identity proof was not admitted; account history is unavailable`,a=`The identity proof was rejected`,o=`The request carried no visitor credential`,s=`The stored visitor belongs to a different signed-in user`;function c(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function l(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function u(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function d(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let a=await e.reinitWithProof(n);if(a.visitor?.identityStatus!==`admitted`||a.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);return a}async function f(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function p(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,o);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,s);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function m(e,t,n){let r=await f(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,o):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,s):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function h(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function g(t,n,r){_(t);let i=r.trackIdentity!==!1,a=await t.initSession(),o=null;l(t,r.scope)===`verified-user`&&(o=await u(t,a,i),o&&(a=await d(t,a,o,i)));let s=t.historyInternals.visitorStore,g=!1;for(;;){let l=s?.revision()??0,u=await t.readVisitorToken();if(!u&&!r.visitorTokenOptional)throw new t.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let d=await fetch(c(t,n,{...r.query,sessionId:a.sessionId}),{method:r.method,headers:{"X-Persona-Version":e,...u?{"X-Visitor-Token":u}:{},...o?{"X-Identity-Proof":o}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(d.status===401&&!g){g=!0,a=await p(t,await f(t,d),o,i);continue}if(!d.ok)throw await m(t,d,i);let _=d.headers.get(`X-History-Identity-Status`),v=await d.json().catch(()=>void 0);if(s&&s.revision()!==l)throw new t.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return h(t,_,o!==null,i),v}}function _(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function v(e,t){let n=await g(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(r),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function y(e,t,n){let i=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:r(i),messages:Array.isArray(i?.messages)?i.messages:[],nextMessageCursor:typeof i?.nextMessageCursor==`string`?i.nextMessageCursor:null,conversationRevision:typeof i?.conversationRevision==`string`?i.conversationRevision:null}}async function b(e,r,i){_(e);let a=0;for(let n of i){let r=n.displayContent.length;if(r>t)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${t} character limit`);a+=r}if(a>n)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${n} character limit`);await e.initSession();let o=e.historyInternals.visitorStore,s=o?.revision()??0,c=await g(e,`conversations/${encodeURIComponent(r)}/display-projections`,{method:`PATCH`,body:{messages:i},scope:`browser`,keepalive:a<=n,trackIdentity:!1}),l=typeof c?.conversationRevision==`string`?c.conversationRevision:null;return l&&e.clientSession?.conversationId===r&&(o?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function x(e,t,n){let r=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function S(e,t){let n=await g(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function C(e){_(e),e.setHistoryIdentityStatus({state:`resetting`});try{await g(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}export{S as deleteAllConversations,x as deleteConversation,b as finalizeDisplayProjections,y as getConversation,m as historyErrorFor,v as listConversations,f as readErrorCode,p as recoverFromUnauthorized,C as resetVisitor};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=`4.32.0`;export{e as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-DDAwu89-.js";import{t}from"./chunk-DqbzUVEI.js";const n=16e3,r=/* @__PURE__ */ new Map([[`idle_timeout`,`Voice call ended after a quiet period.`],[`max_duration`,`This voice call reached its time limit.`],[`provider_ended`,`The voice session ended.`],[`quota`,`Voice is unavailable right now.`],[`auth_expired`,`Voice session expired. Tap the mic to reconnect.`]]),i=[`provider_error`,`server_restart`],a=`Voice connection lost.`;function o(e,t){let n=t.slice(0,4e3).trim(),r=8e3-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>2e3&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
|
|
2
2
|
`)}`]:[];return n&&a.push(n),a.join(`
|
|
3
3
|
|
|
4
4
|
`)}function s(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===1380533830?new Uint8Array(e,44):new Uint8Array(e)}function c(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function l(e){return c(e).replace(/^ws/i,`http`)}function u(e){return typeof e!=`number`||!Number.isFinite(e)?3e4:Math.min(6e5,Math.max(3e4,Math.round(e)))}var d=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<3e4)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${l(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=u(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,5e3)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(t,n,r){let i=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(i+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(i+=`,client_tools,prior_tool_results`)),r&&(i=`attach,${i}`);let a=new URLSearchParams({voiceProtocol:`runtype-browser-v1`,clientVersion:`persona/${e}`,voiceCapabilities:`full-duplex-v1`,clientCapabilities:i});return r?.forEach((e,t)=>a.set(t,e)),`${c(t)}/ws/agents/${encodeURIComponent(n)}/voice?${a}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let r=this.config?.agentId,i=this.config?.clientToken,o=this.config?.host;if(!r)throw Error(`Runtype voice requires an agentId`);if(!i)throw Error(`Runtype voice requires a clientToken`);if(!o)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let s=++this.#d;this.#f=!1,this.#l=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:n,channelCount:1,echoCancellation:!0}});if(s!==this.#d){c.getTracks().forEach(e=>e.stop());return}this.#r=c;let l=new(window.AudioContext||window.webkitAudioContext)({sampleRate:n});if(this.#t=l,l.state===`suspended`){if(await Promise.race([l.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:1e3))]),s!==this.#d)return;if(l.state!==`running`)throw Error(e?this.#D=`${a} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new t(24e3);if(s!==this.#d){u.destroy(),c.getTracks().forEach(e=>e.stop()),l.close().catch(()=>{});return}this.#c=u,this.#he(),this.#ie(l,c,s);let d=await this.#ee();if(s!==this.#d){d?.ws.close(1e3,`client ended call`);return}if(d){let{ws:e}=d;this.#e=e,this.#ne(e,s),d.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let f=new WebSocket(this.#te(o,r),[`runtype.bearer`,i]);f.binaryType=`arraybuffer`,this.#e=f,f.onopen=()=>{s===this.#d&&(this.#ae(f),this.#be(`listening`))},this.#ne(f,s)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=i.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${a} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(i.includes(e))return this.#D=a,this.#xe(/* @__PURE__ */ Error(a)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||r.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||`You're talking to an AI assistant. Voice is processed by OpenAI.`:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+2e3,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(4096,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>256e3;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*4));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return o(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),2e3)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,54e4),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=s(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+300)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}},f=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}};function p(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new d(e.runtype);case`browser`:if(!f.isSupported())throw Error(`Browser speech recognition not supported`);return new f(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function m(e){if(e?.type===`custom`&&e.custom)return p({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return p({type:`runtype`,runtype:e.runtype});if(f.isSupported())return p({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function h(e){try{return m(e),!0}catch{return!1}}const g=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,``);var _=class{constructor(e){this.host=e,this.turns=/* @__PURE__ */ new Map,this.latestId=null,this.cancelled=/* @__PURE__ */ new Set}apply(e,t,n,r,i,a){let o=this.host;t=t.trim();let s=this.turns.get(r);if(s||(s={},this.turns.set(r,s),this.latestId=r),e===`user`){s.userFinal=n;let e=s.userId?o.find(s.userId):void 0;if(e){let r=s.userStartMs===void 0&&i!==void 0;r&&(s.userStartMs=i),o.upsert({...e,content:t,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else{s.userStartMs=i;let e=s.assistantId?o.find(s.assistantId):void 0;s.userId=o.inject({role:`user`,content:t,streaming:!1,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i)??e)}).id}}else if(!this.cancelled.has(r)){s.assistantFinal=n;let e=s.assistantId?o.find(s.assistantId):void 0;if(e){let r=s.assistantStartMs===void 0&&i!==void 0;r&&(s.assistantStartMs=i),o.upsert({...e,content:t,streaming:!n,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else t&&(s.assistantStartMs=i,s.assistantId=o.inject({role:`assistant`,content:t,streaming:!n,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i))}).id);n&&s.assistantId&&o.markSpoken(s.assistantId)}this.sync()}claimUserTurn(e,t=[]){let n=t[t.length-1];for(let e of t)e!==n&&(this.turns.has(e)||this.turns.set(e,{}),this.turns.get(e).claimed=!0);let r;if(n){if(r=this.turns.get(n),r||(r={},this.turns.set(n,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:`user`,content:e.trim()}).id)}else{let t=g(e),n=[...this.turns.values()].reverse().flatMap(e=>{let t=e.userId&&!e.claimed?this.host.find(e.userId):void 0;return t?[{turn:e,text:g(t.content)}]:[]}).filter(({text:e})=>e&&t);r=(n.find(({text:e})=>e===t)??n.find(({text:e})=>e.startsWith(t)||t.startsWith(e)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let e=this.inFlight();if(e.length===0){let t=this.awaiting();if(!t)return;e=[t]}for(let t of e)this.cancelled.add(t);this.closeReplies(e),this.sync()}fail(e){let t=this.awaiting(),n=this.inFlight();if(!t&&n.length===0)return;for(let e of n)this.turns.get(e).assistantFinal=!0;this.closeReplies(n);let r=this.host.inject({role:`assistant`,content:e,streaming:!1,voiceProcessing:!1}),i=t?this.turns.get(t):void 0;i&&(i.assistantId=r.id,i.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let e=this.pending(),t=/* @__PURE__ */ new Set;for(let e of this.turns.values())e.userId&&t.add(e.userId),e.assistantId&&(t.add(e.assistantId),this.host.markSpoken(e.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(t),e&&this.host.setStreaming(!1)}startedAfter(e){if(e===void 0)return;let t;for(let n of this.turns.values())for(let[r,i]of[[n.userId,n.userStartMs],[n.assistantId,n.assistantStartMs]])r&&i!==void 0&&i>e&&(!t||i<t.start)&&(t={start:i,id:r});return t&&this.host.find(t.id)}placeBefore(e){if(!e)return;let t=e.sequence??0,n=t-1;for(let r of this.turns.values())for(let i of[r.userId,r.assistantId]){let r=i?this.host.find(i):void 0,a=r?.sequence;r?.createdAt===e.createdAt&&a!==void 0&&a>n&&a<t&&(n=a)}return{createdAt:e.createdAt,sequence:(n+t)/2}}closeReplies(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.turns.get(n)?.assistantId;e&&(t.add(e),this.host.markSpoken(e))}t.size>0&&this.host.settle(t)}inFlight(){let e=[];for(let[t,n]of this.turns)n.assistantId&&!n.assistantFinal&&!this.cancelled.has(t)&&e.push(t);return e}awaiting(){let e=this.latestId;if(!e)return null;let t=this.turns.get(e);return t?.userFinal&&!t.assistantId&&!t.claimed&&!this.cancelled.has(e)?e:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}};const v=/* @__PURE__ */ new Set(/* @__PURE__ */ `mr,mrs,ms,dr,prof,sr,jr,st,mt,vs,etc,approx,inc,ltd,co,corp,no,nos,fig,ft,dept,est,min,max,e.g,i.e,a.m,p.m,u.s,u.k`.split(`,`)),y=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g;function b(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,``).toLowerCase();if(v.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let n=e.length-t.length;return n===0||/\n\s*$/.test(e.slice(0,n))}return!1}function*x(e,t){let n=new RegExp(y.source,`g`);for(let r=n.exec(e);r;r=n.exec(e)){let n=r[1];if(!e.slice(0,r.index+(n?.length??0)).trim()||n!==void 0&&(/^[,;:]$/.test(n)&&!t||n===`.`&&b(e.slice(0,r.index))))continue;let i=r.index+r[0].length;i<e.length&&(yield i)}}function S(e,t){let n=e.slice(0,t),r=0;for(let e of n.matchAll(/\s+/g))n.slice(0,e.index).trim()&&(r=e.index+e[0].length);return r}function C(e){let t=0;for(let n of x(e.slice(0,220),!0))t=n;if(t)return t;let n=S(e,220);if(n)return n;let r=e.charCodeAt(219);return r>=55296&&r<=56319?219:220}var w=class{#e=``;#t=!0;push(e){return this.#e+=e,this.#n()}flush(){let e=this.#n(),t=this.#e;if(this.#e=``,t.trim()){for(let n=0;n<t.length;){let r=t.slice(n),i=r.length>220?C(r):r.length;e.push(r.slice(0,i)),n+=i}this.#t=!1}return e}idle(){let e=this.#e;if(!e.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(e))return[];this.#e=``,this.#t=!1;let t=[];for(let n=0;n<e.length;){let r=e.slice(n),i=r.length>220?C(r):r.length;t.push(r.slice(0,i)),n+=i}return t}#n(){let e=[];for(let t=this.#r();t>0;t=this.#r())e.push(this.#e.slice(0,t)),this.#e=this.#e.slice(t),this.#t=!1;return e}#r(){let e=this.#e;if(!e.trim())return 0;let t=x(e,this.#t).next().value??0;if(t&&t<=220)return t;let n=/[.!?]["'”’)\]*_]*$/.test(e);if(this.#t&&!n){let t=e.match(/\S+\s+/g)?.length??0;if(e.trim().length>=30||t>=6){let t=S(e,220);if(t)return t}}return e.length>220?C(e):0}};const T=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n},E=`no|nope|never ?mind|decline(?: it| that)?|cancel(?: it| that| this)?(?: (?:the|my|that|this) (?:[a-z]+ )?(?:order|request))?|don'?t (?:do|place) (?:it|that|the (?:[a-z]+ )?order)`,D=RegExp(`^(?:${E})(?: (?:${E}))?(?: thanks| thank you)?$`),O=e=>D.test(e.toLowerCase().replace(/[^a-z' ]+/g,` `).replace(/\s+/g,` `).trim()),k=()=>new Promise(e=>setTimeout(e,50)),A=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e,j=e=>e.replace(/^webmcp:/,``).replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_\-.]+/g,` `).trim().toLowerCase();function M(e,t=0){if(e==null||e===``)return``;if(typeof e!=`object`)return String(e);if(t>2)return``;if(Array.isArray(e))return e.map(e=>M(e,t+1)).filter(Boolean).join(`, `);let n=e,r=n.quantity??n.qty??n.count,i=n.name??n.item??n.product??n.title;return r!=null&&i!=null&&typeof i!=`object`?`${r} ${i}`:Object.entries(n).filter(([e])=>!e.startsWith(`_`)).map(([e,n])=>{let r=M(n,t+1);return r&&(t?`${j(e)} ${r}`:`${j(e)}: ${r}`)}).filter(Boolean).join(t?`, `:`; `)}function N(e){let t=e.length>1?`These actions need the user's approval in the chat before they happen:`:`This action needs the user's approval in the chat before it happens:`,n=1e3-t.length-119-2;return`${t}\n${e.map(t=>{let r=[j(t.toolName)];t.description&&r.push(`(${A(t.description.trim(),160)})`);let i=M(t.parameters);return i&&r.push(`with ${i}`),t.reason&&r.push(`because: ${A(t.reason.trim(),160)}`),A(`- ${r.join(` `)}`,Math.floor(n/e.length)-1)}).join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BAdIgC5d.js";import{t}from"./chunk-CjhA_5Jk.js";import{t as n}from"./chunk-Bz9jAgba.js";import{n as r}from"./chunk-DTDHeUsG.js";const i=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=i(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:a(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},s=(e,t)=>{let n=[],r=[],i=[],a=``,s,c=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let l of e){let e=o(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==s)&&c(),r.length===0&&(a=l.createdAt,s=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let u=t(l);u&&(c(),n.push(u))}return c(),n},c=e=>e.voiceCaption||r(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),l=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),u=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},d=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...u(e)});var f=class{constructor(e){this.host=e}async initializeSession(){await this.host.historyInternals.historyBootstrapReady;let e=this.host.config.getStoredConversationId?.()||null,t=this.host.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.host.isHistoryCapable()&&!t)return this.#e(e,!1);let n=await this.host.readVisitorToken();if(e&&n)try{let n=await this.createClientSession({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.host.historyInternals.setStoredResumableHandle?.(null),this.host.finishInit(n,e,!1)}catch(n){if(!(n instanceof this.host.HistoryClientError&&n.code===`not_found`)&&!(n instanceof this.host.HistoryClientError&&n.code===`visitor_required`)&&!(n instanceof this.host.HistoryClientError&&n.code===`history_disabled`))throw n;return t&&this.host.historyInternals.setStoredResumableHandle?.(null),this.#e(e,!0)}return this.#e(e,!1)}async#e(e,t){let n=this.host.historyInternals.visitorStore;return n&&!await this.host.readVisitorToken()?n.withFirstInitLock(()=>this.#t(e,t)):this.#t(e,t)}async#t(e,t){let n=this.host.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),i=await this.#n(r);return this.host.finishInit(i,e,t)}async#n(e){if(!e.visitor?.token||this.host.claimInFlight||!this.host.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.host.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.host.claimInFlight=!1}}async sendWithClientToolsDiff(t,n,r,i){let a=!!(n&&n.length>0),o=a?e(n):void 0,s=this.host.clientToolsFingerprintSessionId===t,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===t,u=!1,d;for(let e=0;d=await r({...a&&(u||!c)&&n?{clientTools:n}:{},...l?{clientTools:[]}:{},...o?{clientToolsFingerprint:o}:{}}),d.status===409&&e===0&&a&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.host.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.host.lastSentClientToolsFingerprint=o??null,this.host.clientToolsFingerprintSessionId=t,a?this.host.sentNonEmptyClientToolsSessionId=t:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let n=this.host.isHistoryCapable()&&!e.omitVisitorFields,r=!e.omitVisitorFields,i=null;(n||r)&&(await this.host.historyInternals.historyBootstrapReady,i=await this.host.readVisitorToken());let a=this.host.routing(),o=a.agentId??a.flowId,s=n||e.durableResume?e.conversationId:void 0,c={token:this.host.config.clientToken,...o&&{flowId:o},...n&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(n||r)&&i?{visitorToken:i}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(c),signal:e.signal});if(!l.ok){let t=await l.json().catch(()=>({error:`Session initialization failed`}));if(n&&l.status===403&&t.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),s)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw l.status===403&&t.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(n||e.durableResume)&&l.status===401&&t.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):s&&l.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):l.status===401?Error(`Invalid client token: ${t.hint||t.error}`):l.status===403?Error(`Origin not allowed: ${t.hint||t.error}`):Error(t.error||`Failed to initialize session`)}let u=await l.json();return u.visitor?.token&&await this.host.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async sendFeedback(e){if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.host.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let n={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},r=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:`Feedback submission failed`}));throw r.status===401?(this.host.clientSession=null,this.host.resetSessionWarmLatch(),this.host.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async dispatchClientToken(e,r,i){let{HistoryClientError:a}=this.host,o=()=>this.host.isCurrentTurn(i),s=e=>{o()&&r(e)};try{let r=()=>{if(e.signal?.throwIfAborted(),!o())throw new DOMException(`Turn superseded`,`AbortError`)},l=this.host.clientSession??await this.host.initSession();r();let u=async()=>{r();let t=l,n=t.durableRecovery?.enabled===!0;if(n&&(!t.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);r();let i=await this.host.createClientSession({...n||this.host.isHistoryCapable()?{conversationId:t.conversationId,durableResume:n}:{storedSessionId:t.sessionId},signal:e.signal});if(r(),t.conversationId&&i.conversationId!==t.conversationId||n&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);l=this.host.finishInit(i,t.conversationId??null,!1),this.host.clientSession=l,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await u();let d=await this.#c(e.messages),f=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,p=this.host.isHistoryCapable(),m={sessionId:l.sessionId,messages:e.messages.filter(c).map(e=>{let t=p?n(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:i,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},h=async()=>{r();let n=l.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return r(),this.host.sendWithClientToolsDiff(l.sessionId,d.clientTools,async i=>{r();let a=await this.host.resolveChatIdentityProof(e.signal);r();let o={...m,sessionId:l.sessionId,...i,...a&&{identityProof:a}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...a&&{identityProof:{provider:a.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},g=await h();if(r(),g.response.status===401){let e=await g.response.clone().json().catch(()=>null);r(),e?.error===`Session not found or expired`&&(await u(),g=await h(),r())}let{response:_,commit:v}=g;if(!_.ok){let e=await _.json().catch(()=>({error:`Chat request failed`}));if(_.status===401&&e.error===`invalid_identity_proof`){let e=new a(`invalid_identity_proof`,`The identity proof was rejected`);throw s({type:`error`,error:e}),e}if(_.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw s({type:`error`,error:e}),e}if(_.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw s({type:`error`,error:t}),t}if(_.status===410&&e.error===`conversation_deleted`){let e=new a(`conversation_deleted`,`This conversation was deleted`);throw s({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw s({type:`error`,error:t}),t}if(!_.body){let e=/* @__PURE__ */ Error(`No response body received`);throw s({type:`error`,error:e}),e}v(),s({type:`status`,status:`connected`});try{await this.host.streamResponse(_.body,s,e.assistantMessageId,void 0,e.signal)}finally{s({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof a)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&s({type:`error`,error:t}),t}}async dispatchProxy(e,t){let n=await this.#c(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,void 0,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}async dispatchAgent(e,t){let n=await this.#s(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,e.assistantMessageId,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}#r(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#i(e){let t={};this.host.contextProviders.length&&await Promise.all(this.host.contextProviders.map(async n=>{try{let r=await n({messages:e,config:this.host.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#r(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#a(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#o(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.host.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#s(e,t){let n=this.host.routing().agentId;if(!this.host.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=s(l(e),e=>c(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?d(e):null),i=this.#a(t),a={agent:this.#o(this.host.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.host.config.agentOptions}};i&&(a.composerOptions=i);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let u=await this.#i(e);return u&&(a.context=u),a}async#c(e,t){let n=s(l(e),e=>c(e)?d(e):null),r=this.host.routing(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#i(e);o&&(i.context=o);let u=this.#a(t);if(u&&(i.composerOptions=u),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...i},config:this.host.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}};export{f as ClientDispatch};
|
|
1
|
+
import{n as e}from"./chunk-BAdIgC5d.js";import{t}from"./chunk-DDAwu89-.js";import{t as n}from"./chunk-Bz9jAgba.js";import{n as r}from"./chunk-DTDHeUsG.js";const i=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=i(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:a(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},s=(e,t)=>{let n=[],r=[],i=[],a=``,s,c=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let l of e){let e=o(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==s)&&c(),r.length===0&&(a=l.createdAt,s=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let u=t(l);u&&(c(),n.push(u))}return c(),n},c=e=>e.voiceCaption||r(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),l=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),u=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},d=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...u(e)});var f=class{constructor(e){this.host=e}async initializeSession(){await this.host.historyInternals.historyBootstrapReady;let e=this.host.config.getStoredConversationId?.()||null,t=this.host.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.host.isHistoryCapable()&&!t)return this.#e(e,!1);let n=await this.host.readVisitorToken();if(e&&n)try{let n=await this.createClientSession({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.host.historyInternals.setStoredResumableHandle?.(null),this.host.finishInit(n,e,!1)}catch(n){if(!(n instanceof this.host.HistoryClientError&&n.code===`not_found`)&&!(n instanceof this.host.HistoryClientError&&n.code===`visitor_required`)&&!(n instanceof this.host.HistoryClientError&&n.code===`history_disabled`))throw n;return t&&this.host.historyInternals.setStoredResumableHandle?.(null),this.#e(e,!0)}return this.#e(e,!1)}async#e(e,t){let n=this.host.historyInternals.visitorStore;return n&&!await this.host.readVisitorToken()?n.withFirstInitLock(()=>this.#t(e,t)):this.#t(e,t)}async#t(e,t){let n=this.host.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),i=await this.#n(r);return this.host.finishInit(i,e,t)}async#n(e){if(!e.visitor?.token||this.host.claimInFlight||!this.host.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.host.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.host.claimInFlight=!1}}async sendWithClientToolsDiff(t,n,r,i){let a=!!(n&&n.length>0),o=a?e(n):void 0,s=this.host.clientToolsFingerprintSessionId===t,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===t,u=!1,d;for(let e=0;d=await r({...a&&(u||!c)&&n?{clientTools:n}:{},...l?{clientTools:[]}:{},...o?{clientToolsFingerprint:o}:{}}),d.status===409&&e===0&&a&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.host.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.host.lastSentClientToolsFingerprint=o??null,this.host.clientToolsFingerprintSessionId=t,a?this.host.sentNonEmptyClientToolsSessionId=t:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let n=this.host.isHistoryCapable()&&!e.omitVisitorFields,r=!e.omitVisitorFields,i=null;(n||r)&&(await this.host.historyInternals.historyBootstrapReady,i=await this.host.readVisitorToken());let a=this.host.routing(),o=a.agentId??a.flowId,s=n||e.durableResume?e.conversationId:void 0,c={token:this.host.config.clientToken,...o&&{flowId:o},...n&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(n||r)&&i?{visitorToken:i}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(c),signal:e.signal});if(!l.ok){let t=await l.json().catch(()=>({error:`Session initialization failed`}));if(n&&l.status===403&&t.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),s)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw l.status===403&&t.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(n||e.durableResume)&&l.status===401&&t.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):s&&l.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):l.status===401?Error(`Invalid client token: ${t.hint||t.error}`):l.status===403?Error(`Origin not allowed: ${t.hint||t.error}`):Error(t.error||`Failed to initialize session`)}let u=await l.json();return u.visitor?.token&&await this.host.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async sendFeedback(e){if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.host.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let n={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},r=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:`Feedback submission failed`}));throw r.status===401?(this.host.clientSession=null,this.host.resetSessionWarmLatch(),this.host.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async dispatchClientToken(e,r,i){let{HistoryClientError:a}=this.host,o=()=>this.host.isCurrentTurn(i),s=e=>{o()&&r(e)};try{let r=()=>{if(e.signal?.throwIfAborted(),!o())throw new DOMException(`Turn superseded`,`AbortError`)},l=this.host.clientSession??await this.host.initSession();r();let u=async()=>{r();let t=l,n=t.durableRecovery?.enabled===!0;if(n&&(!t.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);r();let i=await this.host.createClientSession({...n||this.host.isHistoryCapable()?{conversationId:t.conversationId,durableResume:n}:{storedSessionId:t.sessionId},signal:e.signal});if(r(),t.conversationId&&i.conversationId!==t.conversationId||n&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);l=this.host.finishInit(i,t.conversationId??null,!1),this.host.clientSession=l,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await u();let d=await this.#c(e.messages),f=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,p=this.host.isHistoryCapable(),m={sessionId:l.sessionId,messages:e.messages.filter(c).map(e=>{let t=p?n(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:i,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},h=async()=>{r();let n=l.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return r(),this.host.sendWithClientToolsDiff(l.sessionId,d.clientTools,async i=>{r();let a=await this.host.resolveChatIdentityProof(e.signal);r();let o={...m,sessionId:l.sessionId,...i,...a&&{identityProof:a}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...a&&{identityProof:{provider:a.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},g=await h();if(r(),g.response.status===401){let e=await g.response.clone().json().catch(()=>null);r(),e?.error===`Session not found or expired`&&(await u(),g=await h(),r())}let{response:_,commit:v}=g;if(!_.ok){let e=await _.json().catch(()=>({error:`Chat request failed`}));if(_.status===401&&e.error===`invalid_identity_proof`){let e=new a(`invalid_identity_proof`,`The identity proof was rejected`);throw s({type:`error`,error:e}),e}if(_.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw s({type:`error`,error:e}),e}if(_.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw s({type:`error`,error:t}),t}if(_.status===410&&e.error===`conversation_deleted`){let e=new a(`conversation_deleted`,`This conversation was deleted`);throw s({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw s({type:`error`,error:t}),t}if(!_.body){let e=/* @__PURE__ */ Error(`No response body received`);throw s({type:`error`,error:e}),e}v(),s({type:`status`,status:`connected`});try{await this.host.streamResponse(_.body,s,e.assistantMessageId,void 0,e.signal)}finally{s({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof a)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&s({type:`error`,error:t}),t}}async dispatchProxy(e,t){let n=await this.#c(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,void 0,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}async dispatchAgent(e,t){let n=await this.#s(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,e.assistantMessageId,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}#r(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#i(e){let t={};this.host.contextProviders.length&&await Promise.all(this.host.contextProviders.map(async n=>{try{let r=await n({messages:e,config:this.host.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#r(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#a(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#o(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.host.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#s(e,t){let n=this.host.routing().agentId;if(!this.host.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=s(l(e),e=>c(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?d(e):null),i=this.#a(t),a={agent:this.#o(this.host.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.host.config.agentOptions}};i&&(a.composerOptions=i);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let u=await this.#i(e);return u&&(a.context=u),a}async#c(e,t){let n=s(l(e),e=>c(e)?d(e):null),r=this.host.routing(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#i(e);o&&(i.context=o);let u=this.#a(t);if(u&&(i.composerOptions=u),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...i},config:this.host.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}};export{f as ClientDispatch};
|
package/dist/client-dispatch.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}};function t(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${r(t.join(``))}`}function n(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function r(e){return`${n(e,0).toString(36)}.${n(e,2654435761).toString(36)}`}var i=e((()=>{})),a,o,s,c,l=e((()=>{a=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),o=e=>typeof e==`object`&&!!e&&!Array.isArray(e),s=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=a(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:o(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},c=(e,t)=>{let n=[],r=[],i=[],a=``,o,c=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let l of e){let e=s(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&c(),r.length===0&&(a=l.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let u=t(l);u&&(c(),n.push(u))}return c(),n}})),u,d,f=e((()=>{u=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],d=[`application/pdf`,`text/plain`,`text/markdown`,`text/csv`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/json`],[...u,...d]}));function p(e){let t=e.content;if(typeof t!=`string`||t===``)return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(typeof n!=`string`||n!==t)return t}var m=e((()=>{f()})),h,g=e((()=>{h=e=>e.localOnly===!0||e.role===`assistant`&&typeof e.id==`string`&&e.id.startsWith(`reconnect-failed-`)})),_=`4.31.0`,v,y=e((()=>{v=_})),b,x,S,C,w;e((()=>{i(),l(),m(),g(),y(),b=e=>e.voiceCaption||h(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),x=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),S=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},C=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...S(e)}),w=class{constructor(e){this.host=e}async initializeSession(){await this.host.historyInternals.historyBootstrapReady;let e=this.host.config.getStoredConversationId?.()||null,t=this.host.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.host.isHistoryCapable()&&!t)return this.#e(e,!1);let n=await this.host.readVisitorToken();if(e&&n)try{let n=await this.createClientSession({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.host.historyInternals.setStoredResumableHandle?.(null),this.host.finishInit(n,e,!1)}catch(n){if(!(n instanceof this.host.HistoryClientError&&n.code===`not_found`)&&!(n instanceof this.host.HistoryClientError&&n.code===`visitor_required`)&&!(n instanceof this.host.HistoryClientError&&n.code===`history_disabled`))throw n;return t&&this.host.historyInternals.setStoredResumableHandle?.(null),this.#e(e,!0)}return this.#e(e,!1)}async#e(e,t){let n=this.host.historyInternals.visitorStore;return n&&!await this.host.readVisitorToken()?n.withFirstInitLock(()=>this.#t(e,t)):this.#t(e,t)}async#t(e,t){let n=this.host.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),i=await this.#n(r);return this.host.finishInit(i,e,t)}async#n(e){if(!e.visitor?.token||this.host.claimInFlight||!this.host.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.host.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.host.claimInFlight=!1}}async sendWithClientToolsDiff(e,n,r,i){let a=!!(n&&n.length>0),o=a?t(n):void 0,s=this.host.clientToolsFingerprintSessionId===e,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===e,u=!1,d;for(let e=0;d=await r({...a&&(u||!c)&&n?{clientTools:n}:{},...l?{clientTools:[]}:{},...o?{clientToolsFingerprint:o}:{}}),d.status===409&&e===0&&a&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.host.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.host.lastSentClientToolsFingerprint=o??null,this.host.clientToolsFingerprintSessionId=e,a?this.host.sentNonEmptyClientToolsSessionId=e:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let t=this.host.isHistoryCapable()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.host.historyInternals.historyBootstrapReady,r=await this.host.readVisitorToken());let i=this.host.routing(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.host.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),o)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.host.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async sendFeedback(e){if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.host.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},n=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.host.clientSession=null,this.host.resetSessionWarmLatch(),this.host.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async dispatchClientToken(e,t,n){let{HistoryClientError:r}=this.host,i=()=>this.host.isCurrentTurn(n),a=e=>{i()&&t(e)};try{let t=()=>{if(e.signal?.throwIfAborted(),!i())throw new DOMException(`Turn superseded`,`AbortError`)},o=this.host.clientSession??await this.host.initSession();t();let s=async()=>{t();let n=o,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.host.createClientSession({...r||this.host.isHistoryCapable()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);o=this.host.finishInit(i,n.conversationId??null,!1),this.host.clientSession=o,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(o)};Date.now()>=o.expiresAt.getTime()-6e4&&await s();let c=await this.#c(e.messages),l=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,u=this.host.isHistoryCapable(),d={sessionId:o.sessionId,messages:e.messages.filter(b).map(e=>{let t=u?p(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...l&&Object.keys(l).length>0&&{metadata:l},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},f=async()=>{t();let n=o.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return t(),this.host.sendWithClientToolsDiff(o.sessionId,c.clientTools,async r=>{t();let i=await this.host.resolveChatIdentityProof(e.signal);t();let a={...d,sessionId:o.sessionId,...r,...i&&{identityProof:i}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...a,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(a),signal:e.signal})})},m=await f();if(t(),m.response.status===401){let e=await m.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await s(),m=await f(),t())}let{response:h,commit:g}=m;if(!h.ok){let e=await h.json().catch(()=>({error:`Chat request failed`}));if(h.status===401&&e.error===`invalid_identity_proof`){let e=new r(`invalid_identity_proof`,`The identity proof was rejected`);throw a({type:`error`,error:e}),e}if(h.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw a({type:`error`,error:e}),e}if(h.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw a({type:`error`,error:t}),t}if(h.status===410&&e.error===`conversation_deleted`){let e=new r(`conversation_deleted`,`This conversation was deleted`);throw a({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw a({type:`error`,error:t}),t}if(!h.body){let e=/* @__PURE__ */ Error(`No response body received`);throw a({type:`error`,error:e}),e}g(),a({type:`status`,status:`connected`});try{await this.host.streamResponse(h.body,a,e.assistantMessageId,void 0,e.signal)}finally{a({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof r)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&a({type:`error`,error:t}),t}}async dispatchProxy(e,t){let n=await this.#c(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,void 0,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}async dispatchAgent(e,t){let n=await this.#s(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,e.assistantMessageId,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}#r(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#i(e){let t={};this.host.contextProviders.length&&await Promise.all(this.host.contextProviders.map(async n=>{try{let r=await n({messages:e,config:this.host.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#r(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#a(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#o(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.host.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#s(e,t){let n=this.host.routing().agentId;if(!this.host.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=c(x(e),e=>b(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?C(e):null),i=this.#a(t),a={agent:this.#o(this.host.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.host.config.agentOptions}};i&&(a.composerOptions=i);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#i(e);return s&&(a.context=s),a}async#c(e,t){let n=c(x(e),e=>b(e)?C(e):null),r=this.host.routing(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#i(e);o&&(i.context=o);let s=this.#a(t);if(s&&(i.composerOptions=s),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...i},config:this.host.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}}}))();export{w as ClientDispatch};
|
|
1
|
+
var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}};function t(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${r(t.join(``))}`}function n(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function r(e){return`${n(e,0).toString(36)}.${n(e,2654435761).toString(36)}`}var i=e((()=>{})),a,o,s,c,l=e((()=>{a=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),o=e=>typeof e==`object`&&!!e&&!Array.isArray(e),s=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=a(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:o(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},c=(e,t)=>{let n=[],r=[],i=[],a=``,o,c=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let l of e){let e=s(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&c(),r.length===0&&(a=l.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let u=t(l);u&&(c(),n.push(u))}return c(),n}})),u,d,f=e((()=>{u=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],d=[`application/pdf`,`text/plain`,`text/markdown`,`text/csv`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/json`],[...u,...d]}));function p(e){let t=e.content;if(typeof t!=`string`||t===``)return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(typeof n!=`string`||n!==t)return t}var m=e((()=>{f()})),h,g=e((()=>{h=e=>e.localOnly===!0||e.role===`assistant`&&typeof e.id==`string`&&e.id.startsWith(`reconnect-failed-`)})),_=`4.32.0`,v,y=e((()=>{v=_})),b,x,S,C,w;e((()=>{i(),l(),m(),g(),y(),b=e=>e.voiceCaption||h(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),x=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),S=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},C=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...S(e)}),w=class{constructor(e){this.host=e}async initializeSession(){await this.host.historyInternals.historyBootstrapReady;let e=this.host.config.getStoredConversationId?.()||null,t=this.host.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.host.isHistoryCapable()&&!t)return this.#e(e,!1);let n=await this.host.readVisitorToken();if(e&&n)try{let n=await this.createClientSession({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.host.historyInternals.setStoredResumableHandle?.(null),this.host.finishInit(n,e,!1)}catch(n){if(!(n instanceof this.host.HistoryClientError&&n.code===`not_found`)&&!(n instanceof this.host.HistoryClientError&&n.code===`visitor_required`)&&!(n instanceof this.host.HistoryClientError&&n.code===`history_disabled`))throw n;return t&&this.host.historyInternals.setStoredResumableHandle?.(null),this.#e(e,!0)}return this.#e(e,!1)}async#e(e,t){let n=this.host.historyInternals.visitorStore;return n&&!await this.host.readVisitorToken()?n.withFirstInitLock(()=>this.#t(e,t)):this.#t(e,t)}async#t(e,t){let n=this.host.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),i=await this.#n(r);return this.host.finishInit(i,e,t)}async#n(e){if(!e.visitor?.token||this.host.claimInFlight||!this.host.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.host.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.host.claimInFlight=!1}}async sendWithClientToolsDiff(e,n,r,i){let a=!!(n&&n.length>0),o=a?t(n):void 0,s=this.host.clientToolsFingerprintSessionId===e,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===e,u=!1,d;for(let e=0;d=await r({...a&&(u||!c)&&n?{clientTools:n}:{},...l?{clientTools:[]}:{},...o?{clientToolsFingerprint:o}:{}}),d.status===409&&e===0&&a&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.host.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.host.lastSentClientToolsFingerprint=o??null,this.host.clientToolsFingerprintSessionId=e,a?this.host.sentNonEmptyClientToolsSessionId=e:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let t=this.host.isHistoryCapable()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.host.historyInternals.historyBootstrapReady,r=await this.host.readVisitorToken());let i=this.host.routing(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.host.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),o)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.host.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async sendFeedback(e){if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.host.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},n=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.host.clientSession=null,this.host.resetSessionWarmLatch(),this.host.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async dispatchClientToken(e,t,n){let{HistoryClientError:r}=this.host,i=()=>this.host.isCurrentTurn(n),a=e=>{i()&&t(e)};try{let t=()=>{if(e.signal?.throwIfAborted(),!i())throw new DOMException(`Turn superseded`,`AbortError`)},o=this.host.clientSession??await this.host.initSession();t();let s=async()=>{t();let n=o,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.host.createClientSession({...r||this.host.isHistoryCapable()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);o=this.host.finishInit(i,n.conversationId??null,!1),this.host.clientSession=o,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(o)};Date.now()>=o.expiresAt.getTime()-6e4&&await s();let c=await this.#c(e.messages),l=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,u=this.host.isHistoryCapable(),d={sessionId:o.sessionId,messages:e.messages.filter(b).map(e=>{let t=u?p(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...l&&Object.keys(l).length>0&&{metadata:l},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},f=async()=>{t();let n=o.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return t(),this.host.sendWithClientToolsDiff(o.sessionId,c.clientTools,async r=>{t();let i=await this.host.resolveChatIdentityProof(e.signal);t();let a={...d,sessionId:o.sessionId,...r,...i&&{identityProof:i}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...a,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(a),signal:e.signal})})},m=await f();if(t(),m.response.status===401){let e=await m.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await s(),m=await f(),t())}let{response:h,commit:g}=m;if(!h.ok){let e=await h.json().catch(()=>({error:`Chat request failed`}));if(h.status===401&&e.error===`invalid_identity_proof`){let e=new r(`invalid_identity_proof`,`The identity proof was rejected`);throw a({type:`error`,error:e}),e}if(h.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw a({type:`error`,error:e}),e}if(h.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw a({type:`error`,error:t}),t}if(h.status===410&&e.error===`conversation_deleted`){let e=new r(`conversation_deleted`,`This conversation was deleted`);throw a({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw a({type:`error`,error:t}),t}if(!h.body){let e=/* @__PURE__ */ Error(`No response body received`);throw a({type:`error`,error:e}),e}g(),a({type:`status`,status:`connected`});try{await this.host.streamResponse(h.body,a,e.assistantMessageId,void 0,e.signal)}finally{a({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof r)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&a({type:`error`,error:t}),t}}async dispatchProxy(e,t){let n=await this.#c(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,void 0,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}async dispatchAgent(e,t){let n=await this.#s(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,e.assistantMessageId,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}#r(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#i(e){let t={};this.host.contextProviders.length&&await Promise.all(this.host.contextProviders.map(async n=>{try{let r=await n({messages:e,config:this.host.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#r(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#a(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#o(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.host.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#s(e,t){let n=this.host.routing().agentId;if(!this.host.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=c(x(e),e=>b(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?C(e):null),i=this.#a(t),a={agent:this.#o(this.host.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.host.config.agentOptions}};i&&(a.composerOptions=i);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#i(e);return s&&(a.context=s),a}async#c(e,t){let n=c(x(e),e=>b(e)?C(e):null),r=this.host.routing(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#i(e);o&&(i.context=o);let s=this.#a(t);if(s&&(i.composerOptions=s),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...i},config:this.host.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}}}))();export{w as ClientDispatch};
|
package/dist/client-history.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},t=`4.
|
|
1
|
+
var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},t=`4.32.0`,n,r=e((()=>{n=t}));function i(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function a(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function o(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function s(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,C);return i}async function c(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function l(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,w);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,T);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,E);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function u(e,t,n){let r=await c(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,C);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,w)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,T):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,E):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function d(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function f(e,t,r){p(e);let f=r.trackIdentity!==!1,m=await e.initSession(),h=null;a(e,r.scope)===`verified-user`&&(h=await o(e,m,f),h&&(m=await s(e,m,h,f)));let g=e.historyInternals.visitorStore,_=!1;for(;;){let a=g?.revision()??0,o=await e.readVisitorToken();if(!o&&!r.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let s=await fetch(i(e,t,{...r.query,sessionId:m.sessionId}),{method:r.method,headers:{"X-Persona-Version":n,...o?{"X-Visitor-Token":o}:{},...h?{"X-Identity-Proof":h}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(s.status===401&&!_){_=!0,m=await l(e,await c(e,s),h,f);continue}if(!s.ok)throw await u(e,s,f);let p=s.headers.get(`X-History-Identity-Status`),v=await s.json().catch(()=>void 0);if(g&&g.revision()!==a)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return d(e,p,h!==null,f),v}}function p(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function m(e,t){let n=await f(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(S),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function h(e,t,n){let r=await f(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:S(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function g(e,t,n){p(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>b)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${b} character limit`);r+=n}if(r>x)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${x} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await f(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=x,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function _(e,t,n){let r=await f(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function v(e,t){let n=await f(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function y(e){p(e),e.setHistoryIdentityStatus({state:`resetting`});try{await f(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var b,x,S,C,w,T,E;e((()=>{r(),b=32768,x=49152,S=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},C=`The identity proof was not admitted; account history is unavailable`,w=`The identity proof was rejected`,T=`The request carried no visitor credential`,E=`The stored visitor belongs to a different signed-in user`}))();export{v as deleteAllConversations,_ as deleteConversation,g as finalizeDisplayProjections,h as getConversation,u as historyErrorFor,m as listConversations,c as readErrorCode,l as recoverFromUnauthorized,y as resetVisitor};
|
package/dist/codegen.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e){return e?.cdnBase?.trim().replace(/\/+$/,``).replace(/[\\'"<>`]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`)}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@4.
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e){return e?.cdnBase?.trim().replace(/\/+$/,``).replace(/[\\'"<>`]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`)}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@4.32.0/dist`}function t(e){if(e!==void 0)return typeof e==`string`?e:Array.isArray(e)?`[${e.map(e=>e.toString()).join(`, `)}]`:e.toString()}function n(e){if(e)return{getHeaders:t(e.getHeaders),onFeedback:t(e.onFeedback),onCopy:t(e.onCopy),requestMiddleware:t(e.requestMiddleware),actionHandlers:t(e.actionHandlers),actionParsers:t(e.actionParsers),postprocessMessage:t(e.postprocessMessage),contextProviders:t(e.contextProviders),streamParser:t(e.streamParser)}}const r=`({ text, message }: any) => {
|
|
2
2
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
3
3
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
4
4
|
let cleanJson = jsonSource
|
package/dist/codegen.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function e(e){return e?.cdnBase?.trim().replace(/\/+$/,``).replace(/[\\'"<>`]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`)}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@4.
|
|
1
|
+
function e(e){return e?.cdnBase?.trim().replace(/\/+$/,``).replace(/[\\'"<>`]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`)}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@4.32.0/dist`}function t(e){if(e!==void 0)return typeof e==`string`?e:Array.isArray(e)?`[${e.map(e=>e.toString()).join(`, `)}]`:e.toString()}function n(e){if(e)return{getHeaders:t(e.getHeaders),onFeedback:t(e.onFeedback),onCopy:t(e.onCopy),requestMiddleware:t(e.requestMiddleware),actionHandlers:t(e.actionHandlers),actionParsers:t(e.actionParsers),postprocessMessage:t(e.postprocessMessage),contextProviders:t(e.contextProviders),streamParser:t(e.streamParser)}}const r=`({ text, message }: any) => {
|
|
2
2
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
3
3
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
4
4
|
let cleanJson = jsonSource
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Cr as ComposerModeGroup, Ea as renderLucideIcon, Mo as AgentWidgetPlugin, Nr as ComposerState, Tr as ComposerModel, ar as ComposerActionContributionContext, cr as ComposerActionPresentation, ir as ComposerActionContext, k as AgentWidgetConfig, mr as ComposerCustomAction, nr as ComposerAction, or as ComposerActionOverflowConfig, sr as ComposerActionPlacement, xr as ComposerMode } from "./types-BOZHQIk0.cjs";
|
|
2
2
|
import { i as createPopover, s as isEditableEventTarget } from "./plugin-kit-C1mRjLgW.cjs";
|
|
3
3
|
import { i as hideTooltipFor, r as attachTooltip } from "./tooltip-BkW-8MnD.cjs";
|
|
4
|
-
import { t as createComposerStore } from "./composer-store-
|
|
4
|
+
import { t as createComposerStore } from "./composer-store-Dw7Zbqxr.cjs";
|
|
5
5
|
//#region src/components/composer-bindings.d.ts
|
|
6
6
|
/**
|
|
7
7
|
* Atomic composer surface bindings.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Cr as ComposerModeGroup, Ea as renderLucideIcon, Mo as AgentWidgetPlugin, Nr as ComposerState, Tr as ComposerModel, ar as ComposerActionContributionContext, cr as ComposerActionPresentation, ir as ComposerActionContext, k as AgentWidgetConfig, mr as ComposerCustomAction, nr as ComposerAction, or as ComposerActionOverflowConfig, sr as ComposerActionPlacement, xr as ComposerMode } from "./types-BOZHQIk0.js";
|
|
2
2
|
import { i as createPopover, s as isEditableEventTarget } from "./plugin-kit-C1mRjLgW.js";
|
|
3
3
|
import { i as hideTooltipFor, r as attachTooltip } from "./tooltip-BkW-8MnD.js";
|
|
4
|
-
import { t as createComposerStore } from "./composer-store-
|
|
4
|
+
import { t as createComposerStore } from "./composer-store-Dw7Zbqxr.js";
|
|
5
5
|
//#region src/components/composer-bindings.d.ts
|
|
6
6
|
/**
|
|
7
7
|
* Atomic composer surface bindings.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as AgentWidgetContextMentionRef, P as AgentWidgetContextMentionComposerCapability } from "./types-
|
|
1
|
+
import { B as AgentWidgetContextMentionRef, P as AgentWidgetContextMentionComposerCapability } from "./types-BOZHQIk0.cjs";
|
|
2
2
|
//#region src/utils/mention-trigger.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* Pure `@`-trigger detection for the composer mention menu.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as AgentWidgetContextMentionRef, P as AgentWidgetContextMentionComposerCapability } from "./types-
|
|
1
|
+
import { B as AgentWidgetContextMentionRef, P as AgentWidgetContextMentionComposerCapability } from "./types-BOZHQIk0.js";
|
|
2
2
|
//#region src/utils/mention-trigger.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* Pure `@`-trigger detection for the composer mention menu.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as AgentWidgetContextMentionRef, Ir as ComposerSubmissionSnapshot, Nr as ComposerState, dr as ComposerAttachmentState, jr as ComposerQuote } from "./types-BOZHQIk0.cjs";
|
|
2
2
|
//#region src/utils/composer-store.d.ts
|
|
3
3
|
type ComposerStateListener = (state: Readonly<ComposerState>) => void;
|
|
4
4
|
interface ComposerStore {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as AgentWidgetContextMentionRef, Ir as ComposerSubmissionSnapshot, Nr as ComposerState, dr as ComposerAttachmentState, jr as ComposerQuote } from "./types-BOZHQIk0.js";
|
|
2
2
|
//#region src/utils/composer-store.d.ts
|
|
3
3
|
type ComposerStateListener = (state: Readonly<ComposerState>) => void;
|
|
4
4
|
interface ComposerStore {
|
package/dist/{context-mention-manager-BfZzcydV.d.cts → context-mention-manager-D2p0-JH-.d.cts}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as AgentWidgetContextMentionRef, I as AgentWidgetContextMentionItem,
|
|
2
|
-
import "./composer-input-
|
|
1
|
+
import { B as AgentWidgetContextMentionRef, I as AgentWidgetContextMentionItem, Rr as ContentPart, U as AgentWidgetContextMentionSource, z as AgentWidgetContextMentionPayload } from "./types-BOZHQIk0.cjs";
|
|
2
|
+
import "./composer-input-dwg_o9Z-.cjs";
|
|
3
3
|
//#region src/components/context-mention-chip.d.ts
|
|
4
4
|
type MentionChipStatus = "resolving" | "ready" | "error";
|
|
5
5
|
interface MentionChipParts {
|
package/dist/{context-mention-manager-BfZzcydV.d.ts → context-mention-manager-D2p0-JH-.d.ts}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as AgentWidgetContextMentionRef, I as AgentWidgetContextMentionItem,
|
|
2
|
-
import "./composer-input-
|
|
1
|
+
import { B as AgentWidgetContextMentionRef, I as AgentWidgetContextMentionItem, Rr as ContentPart, U as AgentWidgetContextMentionSource, z as AgentWidgetContextMentionPayload } from "./types-BOZHQIk0.js";
|
|
2
|
+
import "./composer-input-dwg_o9Z-.js";
|
|
3
3
|
//#region src/components/context-mention-chip.d.ts
|
|
4
4
|
type MentionChipStatus = "resolving" | "ready" | "error";
|
|
5
5
|
interface MentionChipParts {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as AgentWidgetContextMentionRef } from "./types-
|
|
2
|
-
import { t as ComposerInputCapability } from "./composer-input-
|
|
1
|
+
import { B as AgentWidgetContextMentionRef } from "./types-BOZHQIk0.cjs";
|
|
2
|
+
import { t as ComposerInputCapability } from "./composer-input-dwg_o9Z-.cjs";
|
|
3
3
|
//#region src/context-mentions-inline-entry.d.ts
|
|
4
4
|
interface InlineComposerMountContext {
|
|
5
5
|
/** The live composer textarea to migrate from (value + caret + look). */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as AgentWidgetContextMentionRef } from "./types-
|
|
2
|
-
import { t as ComposerInputCapability } from "./composer-input-
|
|
1
|
+
import { B as AgentWidgetContextMentionRef } from "./types-BOZHQIk0.js";
|
|
2
|
+
import { t as ComposerInputCapability } from "./composer-input-dwg_o9Z-.js";
|
|
3
3
|
//#region src/context-mentions-inline-entry.d.ts
|
|
4
4
|
interface InlineComposerMountContext {
|
|
5
5
|
/** The live composer textarea to migrate from (value + caret + look). */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { B as AgentWidgetContextMentionRef, Ct as AgentWidgetMessage, F as AgentWidgetContextMentionConfig, k as AgentWidgetConfig } from "./types-
|
|
2
|
-
import { t as ComposerInputCapability } from "./composer-input-
|
|
3
|
-
import { n as MentionSubmitBundle, t as ContextMentionDraft } from "./context-mention-manager-
|
|
1
|
+
import { B as AgentWidgetContextMentionRef, Ct as AgentWidgetMessage, F as AgentWidgetContextMentionConfig, k as AgentWidgetConfig } from "./types-BOZHQIk0.cjs";
|
|
2
|
+
import { t as ComposerInputCapability } from "./composer-input-dwg_o9Z-.cjs";
|
|
3
|
+
import { n as MentionSubmitBundle, t as ContextMentionDraft } from "./context-mention-manager-D2p0-JH-.cjs";
|
|
4
4
|
//#region src/utils/context-mention-controller.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Outcome of dispatching an inline slash command at submit (Slack-style). The UI
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { B as AgentWidgetContextMentionRef, Ct as AgentWidgetMessage, F as AgentWidgetContextMentionConfig, k as AgentWidgetConfig } from "./types-
|
|
2
|
-
import { t as ComposerInputCapability } from "./composer-input-
|
|
3
|
-
import { n as MentionSubmitBundle, t as ContextMentionDraft } from "./context-mention-manager-
|
|
1
|
+
import { B as AgentWidgetContextMentionRef, Ct as AgentWidgetMessage, F as AgentWidgetContextMentionConfig, k as AgentWidgetConfig } from "./types-BOZHQIk0.js";
|
|
2
|
+
import { t as ComposerInputCapability } from "./composer-input-dwg_o9Z-.js";
|
|
3
|
+
import { n as MentionSubmitBundle, t as ContextMentionDraft } from "./context-mention-manager-D2p0-JH-.js";
|
|
4
4
|
//#region src/utils/context-mention-controller.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Outcome of dispatching an inline slash command at submit (Slack-style). The UI
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Oo as ThemeValidationResult, So as SemanticTokens, do as CreateThemeOptions, fo as DeepPartial, go as PersonaTheme, k as AgentWidgetConfig, lo as ComponentTokens, yo as ResolvedToken } from "./types-BOZHQIk0.cjs";
|
|
2
2
|
//#region src/utils/tokens.d.ts
|
|
3
3
|
declare const DEFAULT_PALETTE: {
|
|
4
4
|
spacing: Record<0 | 1 | 2 | 3 | 4 | 5 | 6 | 8 | 10 | 12 | 16 | 20 | 24 | 32 | 40 | 48 | 56 | 64, string>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Oo as ThemeValidationResult, So as SemanticTokens, do as CreateThemeOptions, fo as DeepPartial, go as PersonaTheme, k as AgentWidgetConfig, lo as ComponentTokens, yo as ResolvedToken } from "./types-BOZHQIk0.js";
|
|
2
2
|
//#region src/utils/tokens.d.ts
|
|
3
3
|
declare const DEFAULT_PALETTE: {
|
|
4
4
|
spacing: Record<0 | 1 | 2 | 3 | 4 | 5 | 6 | 8 | 10 | 12 | 16 | 20 | 24 | 32 | 40 | 48 | 56 | 64, string>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Br as
|
|
2
|
-
import { t as ComposerInputCapability } from "./composer-input-
|
|
1
|
+
import { Br as DictationPhase, Ea as renderLucideIcon, Hr as DictationRenderContext, Mo as AgentWidgetPlugin, Ur as DictationRenderHandle, Vr as DictationProviderConfig, Wr as DictationState, k as AgentWidgetConfig } from "./types-BOZHQIk0.cjs";
|
|
2
|
+
import { t as ComposerInputCapability } from "./composer-input-dwg_o9Z-.cjs";
|
|
3
3
|
import { r as attachTooltip } from "./tooltip-BkW-8MnD.cjs";
|
|
4
4
|
//#region src/voice/dictation.d.ts
|
|
5
5
|
type DictationCallbacks = {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Br as
|
|
2
|
-
import { t as ComposerInputCapability } from "./composer-input-
|
|
1
|
+
import { Br as DictationPhase, Ea as renderLucideIcon, Hr as DictationRenderContext, Mo as AgentWidgetPlugin, Ur as DictationRenderHandle, Vr as DictationProviderConfig, Wr as DictationState, k as AgentWidgetConfig } from "./types-BOZHQIk0.js";
|
|
2
|
+
import { t as ComposerInputCapability } from "./composer-input-dwg_o9Z-.js";
|
|
3
3
|
import { r as attachTooltip } from "./tooltip-BkW-8MnD.js";
|
|
4
4
|
//#region src/voice/dictation.d.ts
|
|
5
5
|
type DictationCallbacks = {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Mo as AgentWidgetPlugin, k as AgentWidgetConfig, zi as SSEEventRecord } from "./types-BOZHQIk0.cjs";
|
|
2
2
|
//#region src/utils/scroll-animation.d.ts
|
|
3
3
|
/** Explicit jump only: automatic following keeps its separate policy and animation. */
|
|
4
4
|
declare function createScrollToLatest(element: HTMLElement, keyboardScope: HTMLElement, onFrame: () => void, onComplete: () => void, onCancel: () => void): {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Mo as AgentWidgetPlugin, k as AgentWidgetConfig, zi as SSEEventRecord } from "./types-BOZHQIk0.js";
|
|
2
2
|
//#region src/utils/scroll-animation.d.ts
|
|
3
3
|
/** Explicit jump only: automatic following keeps its separate policy and animation. */
|
|
4
4
|
declare function createScrollToLatest(element: HTMLElement, keyboardScope: HTMLElement, onFrame: () => void, onComplete: () => void, onCancel: () => void): {
|
package/dist/{fallback-speech-engine-DZ6Of7VU.d.cts → fallback-speech-engine-DmF7MczI.d.cts}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Gi as SpeechRequest, Ui as SpeechCallbacks, Wi as SpeechEngine } from "./types-BOZHQIk0.cjs";
|
|
2
2
|
//#region src/voice/fallback-speech-engine.d.ts
|
|
3
3
|
interface FallbackSpeechEngineOptions {
|
|
4
4
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Gi as SpeechRequest, Ui as SpeechCallbacks, Wi as SpeechEngine } from "./types-BOZHQIk0.js";
|
|
2
2
|
//#region src/voice/fallback-speech-engine.d.ts
|
|
3
3
|
interface FallbackSpeechEngineOptions {
|
|
4
4
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ca as WidgetPreferenceSlice, Mi as PersonaArtifactRecord, Ti as PersonaArtifactDisplayModeInput, _ as AgentWidgetArtifactsFeature, k as AgentWidgetConfig, ki as PersonaArtifactKind, nt as AgentWidgetFeatureFlags, wi as PersonaArtifactDisplayMode } from "./types-BOZHQIk0.cjs";
|
|
2
2
|
//#region src/utils/artifact-display.d.ts
|
|
3
3
|
/** Canonicalize the deprecated `"card"` alias to `"collapsed"`. */
|
|
4
4
|
declare function canonicalArtifactDisplayMode(mode: PersonaArtifactDisplayModeInput): PersonaArtifactDisplayMode;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ca as WidgetPreferenceSlice, Mi as PersonaArtifactRecord, Ti as PersonaArtifactDisplayModeInput, _ as AgentWidgetArtifactsFeature, k as AgentWidgetConfig, ki as PersonaArtifactKind, nt as AgentWidgetFeatureFlags, wi as PersonaArtifactDisplayMode } from "./types-BOZHQIk0.js";
|
|
2
2
|
//#region src/utils/artifact-display.d.ts
|
|
3
3
|
/** Canonicalize the deprecated `"card"` alias to `"collapsed"`. */
|
|
4
4
|
declare function canonicalArtifactDisplayMode(mode: PersonaArtifactDisplayModeInput): PersonaArtifactDisplayMode;
|
package/dist/forms-ui.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Ct as AgentWidgetMessage, k as AgentWidgetConfig } from "./types-
|
|
2
|
-
import { t as AgentWidgetSession } from "./session-
|
|
1
|
+
import { Ct as AgentWidgetMessage, k as AgentWidgetConfig } from "./types-BOZHQIk0.cjs";
|
|
2
|
+
import { t as AgentWidgetSession } from "./session-Baxp9iRK.cjs";
|
|
3
3
|
//#region src/components/forms.d.ts
|
|
4
4
|
export declare const formDefinitions: Record<string, {
|
|
5
5
|
title: string;
|
package/dist/forms-ui.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Ct as AgentWidgetMessage, k as AgentWidgetConfig } from "./types-
|
|
2
|
-
import { t as AgentWidgetSession } from "./session-
|
|
1
|
+
import { Ct as AgentWidgetMessage, k as AgentWidgetConfig } from "./types-BOZHQIk0.js";
|
|
2
|
+
import { t as AgentWidgetSession } from "./session-Baxp9iRK.js";
|
|
3
3
|
//#region src/components/forms.d.ts
|
|
4
4
|
export declare const formDefinitions: Record<string, {
|
|
5
5
|
title: string;
|
package/dist/{history-confirm-dialog-Cm4oK4am.d.cts → history-confirm-dialog-DJEXsTyE.d.cts}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Aa as HistoryOperationContext, Na as HistoryProvider, ct as AgentWidgetHistoryListAction, ii as HistoryIdentityStatus, lt as AgentWidgetHistoryRenderActions, ni as HistoryConversationSummary, ot as AgentWidgetHistoryCopy } from "./types-BOZHQIk0.cjs";
|
|
2
2
|
import { n as TooltipOptions, t as TooltipHandle } from "./tooltip-BkW-8MnD.cjs";
|
|
3
3
|
//#region src/components/history-view/copy.d.ts
|
|
4
4
|
type HistoryViewCopyInput = AgentWidgetHistoryCopy;
|