@runtypelabs/persona 4.29.0 → 4.29.1
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/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.cjs +3 -3
- package/dist/approval-ui.d.cts +1 -1
- package/dist/approval-ui.d.ts +1 -1
- package/dist/approval-ui.js +3 -3
- package/dist/artifacts-ui.d.cts +2 -2
- package/dist/artifacts-ui.d.ts +2 -2
- package/dist/chunk-B1-_pp-Y.js +4 -0
- package/dist/{chunk-DjOvgFsn.js → chunk-BcLIgi1h.js} +1 -1
- package/dist/chunk-Bm2-bemv.js +1 -0
- package/dist/chunk-BvhTpG6k.js +1 -0
- package/dist/chunk-Csks3Qw1.js +1 -0
- package/dist/chunk-D5B629Mj.js +1 -0
- package/dist/chunk-DGlFKA0r.js +9 -0
- package/dist/chunk-DO9_WSpy.js +1 -0
- package/dist/chunk-DTDHeUsG.js +1 -0
- package/dist/chunk-DjFpGFGA.js +1 -0
- package/dist/{chunk-dRBlrLd7.js → chunk-DtmtfIkd.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/client-stream.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/{composer-input-D3sB8_P_.d.cts → composer-input-B0P4OtNi.d.cts} +1 -1
- package/dist/{composer-input-D3sB8_P_.d.ts → composer-input-B0P4OtNi.d.ts} +1 -1
- package/dist/{context-mention-manager-D2qxE5op.d.cts → context-mention-manager-DmLI_RM6.d.cts} +1 -1
- package/dist/{context-mention-manager-D2qxE5op.d.ts → context-mention-manager-DmLI_RM6.d.ts} +1 -1
- 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-Dsw66XqE.d.cts → defaults-DVo1wbZs.d.cts} +1 -1
- package/dist/{defaults-Dsw66XqE.d.ts → defaults-DVo1wbZs.d.ts} +1 -1
- package/dist/event-stream-view.d.cts +1 -1
- package/dist/event-stream-view.d.ts +1 -1
- package/dist/{fallback-speech-engine-DJpJcWAk.d.cts → fallback-speech-engine-BMnlmKnY.d.cts} +1 -1
- package/dist/{fallback-speech-engine-DJpJcWAk.d.ts → fallback-speech-engine-BMnlmKnY.d.ts} +1 -1
- package/dist/forms-ui.d.cts +2 -2
- package/dist/forms-ui.d.ts +2 -2
- package/dist/history-view.d.cts +1 -1
- package/dist/history-view.d.ts +1 -1
- package/dist/index.cjs +56 -56
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.global.js +2 -3
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +38 -38
- package/dist/index.js.map +1 -1
- package/dist/{markdown-parsers-loader-CCY7T4Up.d.cts → markdown-parsers-loader-CeovcyYf.d.cts} +1 -1
- package/dist/{markdown-parsers-loader-CCY7T4Up.d.ts → markdown-parsers-loader-CeovcyYf.d.ts} +1 -1
- package/dist/{preview-DKKpfTo7.d.cts → preview-Bkb4UrQC.d.cts} +2 -2
- package/dist/{preview-DKKpfTo7.d.ts → preview-Bkb4UrQC.d.ts} +2 -2
- package/dist/session-actions.js +1 -1
- package/dist/{session-DleMr9dZ.d.ts → session-iLyKipoM.d.cts} +21 -9
- package/dist/{session-DleMr9dZ.d.cts → session-iLyKipoM.d.ts} +21 -9
- package/dist/session-reconnect.cjs +1 -1
- package/dist/session-reconnect.d.cts +8 -2
- package/dist/session-reconnect.d.ts +8 -2
- package/dist/session-reconnect.js +1 -1
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +61 -61
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +40 -40
- 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/{types-oAZ1VReS.d.cts → types-BuDirJkQ.d.cts} +35 -3
- package/dist/{types-oAZ1VReS.d.ts → types-BuDirJkQ.d.ts} +35 -3
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +3 -3
- package/dist/voice-runtime.d.cts +10 -4
- package/dist/voice-runtime.d.ts +10 -4
- package/dist/voice-runtime.js +5 -5
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-Deg0NfmB.d.cts → webmcp-runtime-entry-CXLjRt1k.d.cts} +1 -1
- package/dist/{webmcp-runtime-entry-Deg0NfmB.d.ts → webmcp-runtime-entry-CXLjRt1k.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/client-approve.test.ts +17 -1
- package/src/client-resume.ts +15 -3
- package/src/client.interrupt.test.ts +21 -0
- package/src/client.ts +24 -4
- package/src/components/activity-row.ts +3 -2
- package/src/components/approval-actions.test.ts +8 -0
- package/src/components/approval-actions.ts +6 -2
- package/src/components/approval-bubble.test.ts +14 -0
- package/src/components/approval-bubble.ts +8 -1
- package/src/components/tool-bubble.ts +8 -5
- package/src/generated/runtype-openapi-contract.ts +1 -1
- package/src/resume-dedupe-local-only.test.ts +273 -0
- package/src/runtime/persist-state.test.ts +86 -0
- package/src/session-actions.ts +20 -6
- package/src/session-reconnect.ts +18 -1
- package/src/session.restored-browser-tools.test.ts +272 -0
- package/src/session.ts +176 -29
- package/src/session.voice.test.ts +169 -0
- package/src/styles/widget.css +4 -2
- package/src/types.ts +37 -2
- package/src/ui.restored-browser-tools.test.ts +128 -0
- package/src/ui.ts +32 -18
- package/src/utils/formatting.test.ts +9 -1
- package/src/utils/formatting.ts +4 -0
- package/src/utils/local-only-message.ts +15 -0
- package/src/utils/restored-browser-state.ts +50 -0
- package/src/utils/storage.ts +12 -1
- package/src/utils/voice-prior-tool-results.ts +37 -0
- package/src/voice/runtype-voice-provider.ts +13 -8
- package/src/voice/session-voice-wiring.ts +1 -2
- package/src/voice/voice-delegation.ts +10 -3
- package/src/voice/voice.test.ts +38 -2
- package/dist/chunk-B6zZsT6F.js +0 -1
- package/dist/chunk-CIVsNcrk.js +0 -1
- package/dist/chunk-CKdlNyzM.js +0 -9
- package/dist/chunk-DbhxjyOB.js +0 -4
- package/dist/chunk-DsdqLStH.js +0 -1
- package/dist/chunk-GIqbL2Eg.js +0 -1
package/dist/approval-ui.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const t=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var
|
|
2
|
-
\r `.includes(e[
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const t=`The chat restarted and this browser tool was interrupted. Request a fresh proposal to try again.`,n=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},r=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r};var i=/* @__PURE__ */ e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow}));(/* @__PURE__ */ e((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let r=i();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(i(),e);var a=class extends Error{};e.PartialJSON=a;var o=class extends Error{};e.MalformedJSON=o;function s(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return c(e.trim(),t)}e.parseJSON=s;let c=(e,t)=>{let n=e.length,i=0,s=e=>{throw new a(`${e} at position ${i}`)},c=e=>{throw new o(`${e} at position ${i}`)},l=()=>(m(),i>=n&&s(`Unexpected end of input`),e[i]===`"`?u():e[i]===`{`?d():e[i]===`[`?f():e.substring(i,i+4)===`null`||r.Allow.NULL&t&&n-i<4&&`null`.startsWith(e.substring(i))?(i+=4,null):e.substring(i,i+4)===`true`||r.Allow.BOOL&t&&n-i<4&&`true`.startsWith(e.substring(i))?(i+=4,!0):e.substring(i,i+5)===`false`||r.Allow.BOOL&t&&n-i<5&&`false`.startsWith(e.substring(i))?(i+=5,!1):e.substring(i,i+8)===`Infinity`||r.Allow.INFINITY&t&&n-i<8&&`Infinity`.startsWith(e.substring(i))?(i+=8,1/0):e.substring(i,i+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-i&&n-i<9&&`-Infinity`.startsWith(e.substring(i))?(i+=9,-1/0):e.substring(i,i+3)===`NaN`||r.Allow.NAN&t&&n-i<3&&`NaN`.startsWith(e.substring(i))?(i+=3,NaN):p()),u=()=>{let a=i,o=!1;for(i++;i<n&&(e[i]!==`"`||o&&e[i-1]===`\\`);)o=e[i]===`\\`&&!o,i++;if(e.charAt(i)==`"`)try{return JSON.parse(e.substring(a,++i-Number(o)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(a,i-Number(o))+`"`)}catch{return JSON.parse(e.substring(a,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{i++,m();let a={};try{for(;e[i]!==`}`;){if(m(),i>=n&&r.Allow.OBJ&t)return a;let o=u();m(),i++;try{a[o]=l()}catch(e){if(r.Allow.OBJ&t)return a;throw e}m(),e[i]===`,`&&i++}}catch{if(r.Allow.OBJ&t)return a;s(`Expected '}' at end of object`)}return i++,a},f=()=>{i++;let n=[];try{for(;e[i]!==`]`;)n.push(l()),m(),e[i]===`,`&&i++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return i++,n},p=()=>{if(i===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let a=i;for(e[i]===`-`&&i++;e[i]&&`,]}`.indexOf(e[i])===-1;)i++;i==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(a,i))}catch{e.substring(a,i)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(a,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;i<n&&`
|
|
2
|
+
\r `.includes(e[i]);)i++};return l()};e.parse=s})))();const a=e=>{if(e===null)return`null`;if(e===void 0)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}};let o=()=>void 0;const s=e=>{o=e.webMcpToolTitle},c=e=>o(e)
|
|
3
3
|
/**
|
|
4
4
|
* @license lucide v1.18.0 - ISC
|
|
5
5
|
*
|
|
6
6
|
* This source code is licensed under the ISC license.
|
|
7
7
|
* See the LICENSE file in the root directory of this source tree.
|
|
8
8
|
*/
|
|
9
|
-
;var s=(/* @__PURE__ */ e((e=>{e.Ban=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`M4.929 4.929 19.07 19.071`}]],e.ChevronDown=[[`path`,{d:`m6 9 6 6 6-6`}]],e.ChevronUp=[[`path`,{d:`m18 15-6-6-6 6`}]],e.ShieldAlert=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`M12 8v4`}],[`path`,{d:`M12 16h.01`}]],e.ShieldCheck=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`m9 12 2 2 4-4`}]],e.ShieldX=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`m14.5 9.5-5 5`}],[`path`,{d:`m9.5 9.5 5 5`}]]})))();const c=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i},l=e=>{let t=(e.startsWith(`webmcp:`)?e.slice(7):e).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return e;let n=t.join(` `).toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},u=e=>e?.approval===!1?void 0:e?.approval,d=(e,t,n)=>{let r=u(n)?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},f=(e,t,n)=>{let r=u(n);e.setAttribute(`aria-expanded`,t?`true`:`false`);let i=e.querySelector(`[data-approval-details-label]`);i&&(i.textContent=t?r?.hideDetailsLabel??`Hide details`:r?.showDetailsLabel??`Show details`);let a=e.querySelector(`[data-approval-details-chevron]`);if(a){a.innerHTML=``;let e=c(t?s.ChevronUp:s.ChevronDown,14,`currentColor`,2);e&&a.appendChild(e)}},p=(e,t,n,r=/* @__PURE__ */ new Map)=>{let i=t.querySelector(`button[data-bubble-type="approval"]`),a=t.querySelector(`[data-approval-details]`);if(!i||!a)return;let o=d(e,r,n);f(i,o,n),a.style.display=o?``:`none`},m=(e,n,i=/* @__PURE__ */ new Map)=>{let a=e.approval,u=n?.approval===!1?void 0:n?.approval,p=a?.status===`pending`,m=t(`div`,[`persona-approval-bubble`,`persona-w-full`,`persona-rounded-2xl`,`persona-border`,`persona-shadow-sm`,`persona-overflow-hidden`].join(` `));if(m.id=`bubble-${e.id}`,m.setAttribute(`data-message-id`,e.id),m.style.backgroundColor=u?.backgroundColor??`var(--persona-approval-bg)`,m.style.borderColor=u?.borderColor??`var(--persona-approval-border)`,m.style.boxShadow=u?.shadow===void 0?`var(--persona-approval-shadow)`:u.shadow.trim()===``?`none`:u.shadow,!a)return m;let h=t(`div`,`persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3`),g=t(`div`,`persona-flex-shrink-0 persona-mt-0.5`);g.setAttribute(`data-approval-icon`,`true`);let _=a.status===`denied`?s.ShieldX:a.status===`timeout`?s.ShieldAlert:s.ShieldCheck,v=a.status===`approved`?`var(--persona-feedback-success, var(--persona-palette-colors-success-600))`:a.status===`denied`?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:a.status===`timeout`?`var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))`:u?.titleColor??`currentColor`,y=c(_,20,v,2);y&&g.appendChild(y);let b=t(`div`,`persona-flex-1 persona-min-w-0`),x=t(`div`,`persona-flex persona-items-center persona-gap-2`),S=t(`span`,`persona-text-sm persona-font-medium persona-text-persona-primary`);if(u?.titleColor&&(S.style.color=u.titleColor),S.textContent=u?.title??`Approval Required`,x.appendChild(S),!p){let e=t(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`);e.setAttribute(`data-approval-status`,a.status),a.status===`approved`?(e.style.backgroundColor=`var(--persona-palette-colors-success-100)`,e.style.color=`var(--persona-palette-colors-success-700)`,e.textContent=`Approved`):a.status===`denied`?(e.style.backgroundColor=`var(--persona-palette-colors-error-100)`,e.style.color=`var(--persona-palette-colors-error-700)`,e.textContent=`Denied`):a.status===`timeout`&&(e.style.backgroundColor=`var(--persona-palette-colors-warning-100)`,e.style.color=`var(--persona-palette-colors-warning-700)`,e.textContent=`Timeout`),x.appendChild(e)}b.appendChild(x);let C=a.toolType===`webmcp`||a.toolName.startsWith(`webmcp:`)?o(a.toolName):void 0,w=u?.formatDescription?.({toolName:a.toolName,toolType:a.toolType,description:a.description,parameters:a.parameters,...C?{displayTitle:C}:{},...a.reason?{reason:a.reason}:{}}),T=!a.toolName,E=w||(T?a.description:`The assistant wants to use “${C??l(a.toolName)}”.`),D=t(`p`,`persona-text-sm persona-mt-0.5 persona-text-persona-muted`);if(D.setAttribute(`data-approval-summary`,`true`),u?.descriptionColor&&(D.style.color=u.descriptionColor),D.textContent=E,b.appendChild(D),a.reason){let e=t(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-reason`,`true`),u?.reasonColor?e.style.color=u.reasonColor:u?.descriptionColor&&(e.style.color=u.descriptionColor);let n=t(`span`,`persona-font-medium`);n.textContent=`${u?.reasonLabel??`Agent's stated reason:`} `,e.appendChild(n),e.appendChild(document.createTextNode(a.reason)),b.appendChild(e)}let O=u?.detailsDisplay??`collapsed`,k=!!a.description&&!T,A=k||!!a.parameters;if(O!==`hidden`&&A){let o=d(e.id,i,n),s=t(`button`,`persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted`);s.type=`button`,s.setAttribute(`data-expand-header`,`true`),s.setAttribute(`data-bubble-type`,`approval`),u?.descriptionColor&&(s.style.color=u.descriptionColor);let c=t(`span`);c.setAttribute(`data-approval-details-label`,`true`);let l=t(`span`,`persona-inline-flex persona-items-center`);l.setAttribute(`data-approval-details-chevron`,`true`),s.append(c,l),f(s,o,n),b.appendChild(s);let p=t(`div`);if(p.setAttribute(`data-approval-details`,`true`),p.style.display=o?``:`none`,k){let e=t(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);u?.descriptionColor&&(e.style.color=u.descriptionColor),e.textContent=a.description,p.appendChild(e)}if(a.parameters){let e=t(`pre`,`persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary`);u?.parameterBackgroundColor&&(e.style.backgroundColor=u.parameterBackgroundColor),u?.parameterTextColor&&(e.style.color=u.parameterTextColor),e.style.fontSize=`0.75rem`,e.style.lineHeight=`1rem`,e.textContent=r(a.parameters),p.appendChild(e)}b.appendChild(p)}if(p){let e=t(`div`,`persona-flex persona-gap-2 persona-mt-2`);e.setAttribute(`data-approval-buttons`,`true`);let n=t(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer`);n.type=`button`,n.style.backgroundColor=u?.approveButtonColor??`var(--persona-approval-approve-bg)`,n.style.color=u?.approveButtonTextColor??`var(--persona-button-primary-fg)`,n.setAttribute(`data-approval-action`,`approve`);let r=c(s.ShieldCheck,14,u?.approveButtonTextColor??`var(--persona-button-primary-fg)`,2);r&&(r.style.marginRight=`4px`,n.appendChild(r));let i=document.createTextNode(u?.approveLabel??`Approve`);n.appendChild(i);let a=t(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer`);a.type=`button`,a.style.backgroundColor=u?.denyButtonColor??`transparent`,a.style.color=u?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,a.style.border=`1px solid ${u?.denyButtonTextColor?u.denyButtonTextColor:`var(--persona-palette-colors-error-200)`}`,a.setAttribute(`data-approval-action`,`deny`);let o=c(s.ShieldX,14,u?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,2);o&&(o.style.marginRight=`4px`,a.appendChild(o));let l=document.createTextNode(u?.denyLabel??`Deny`);a.appendChild(l),e.append(n,a),b.appendChild(e)}return h.append(g,b),m.appendChild(h),m};function h(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function g(e){let{anchor:t,content:n,placement:r=`bottom-start`,offset:i=6,matchAnchorWidth:a=!1,horizontalOffset:o,verticalOffset:s,zIndex:c=2147483e3,onOpen:l,onDismiss:u}=e,d=e.container??h(t),f=!1,p=null,m=()=>{if(!f)return;let e=t.getBoundingClientRect();n.style.position=`fixed`,a&&(n.style.minWidth=`${e.width}px`),o&&(n.style.maxWidth=`${e.width}px`);let c=n.getBoundingClientRect(),l=s?.()??null,u=l==null?e.top:e.top+l,d=r===`top-start`||r===`top-end`?u-i-c.height:e.bottom+i,p=r===`bottom-end`||r===`top-end`?e.right-c.width:e.left,m=o?.()??null;if(m!=null){let t=Math.max(e.left,e.right-c.width);p=Math.min(Math.max(e.left+m,e.left),t)}n.style.top=`${d}px`,n.style.left=`${p}px`},g=()=>{f&&(f=!1,p&&=(p(),null),n.remove())},_=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),d.appendChild(n),m();let e=(t.ownerDocument??document).defaultView??window,r=t.ownerDocument??document,i=()=>{t.isConnected?m():(g(),u?.(`anchor-removed`))},a=e=>{let r=typeof e.composedPath==`function`?e.composedPath():[];r.includes(n)||r.includes(t)||(g(),u?.(`outside`))},o=e.setTimeout(()=>{r.addEventListener(`pointerdown`,a,!0)},0);e.addEventListener(`scroll`,i,!0),e.addEventListener(`resize`,i),p=()=>{e.clearTimeout(o),r.removeEventListener(`pointerdown`,a,!0),e.removeEventListener(`scroll`,i,!0),e.removeEventListener(`resize`,i)},l?.()};return{get isOpen(){return f},open:_,close:g,toggle:()=>f?g():_(),reposition:m,destroy:g}}function _(e){return(typeof e.composedPath==`function`?e.composedPath():[]).some(e=>e instanceof HTMLElement&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable))}const v=()=>({keyHandlers:/* @__PURE__ */ new Map,popovers:/* @__PURE__ */ new Map,pendingOrder:[],latestPendingApprovalId:null}),y=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener(`keydown`,n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},b=(e,t)=>{y(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},x=e=>e?.approval===!1?void 0:e?.approval,S=(e,t,n)=>{let r=n?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},C=e=>{let n=t(`span`,`persona-approval-kbd`);return n.textContent=e,n},w=(e,n)=>{let r=t(`span`,`persona-approval-title`);n?.titleColor&&(r.style.color=n.titleColor);let i=e.toolType===`webmcp`||e.toolName.startsWith(`webmcp:`)?o(e.toolName):void 0,a=n?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??``,parameters:e.parameters,...i?{displayTitle:i}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let s=i??l(e.toolName),c=e.toolType&&e.toolType!==`webmcp`?e.toolType:null;r.append(`The assistant wants to use `);let u=document.createElement(`strong`);if(u.textContent=s,r.appendChild(u),c){r.append(` from `);let e=document.createElement(`strong`);e.textContent=c,r.appendChild(e)}return r},T=e=>{let n=t(`div`,`persona-approval-resolved`),r=c(s.Ban,15,`currentColor`,2);r&&n.appendChild(r);let i=t(`span`,`persona-approval-resolved-name`);return i.textContent=e.toolName?l(e.toolName):`Tool`,n.append(i,document.createTextNode(e.status===`timeout`?` timed out`:` denied`)),n},E=(e,n,i,a,o,l,u,d,f=!1)=>{let p=t(`div`,`persona-approval-card persona-shadow-sm`);p.id=`bubble-${i.id}`,p.setAttribute(`data-message-id`,i.id),p.setAttribute(`data-bubble-type`,`approval`),o?.backgroundColor&&(p.style.background=o.backgroundColor),o?.borderColor&&(p.style.borderColor=o.borderColor),o?.shadow!==void 0&&(p.style.boxShadow=o.shadow.trim()===``?`none`:o.shadow);let m=o?.detailsDisplay??`collapsed`,h=!!a.description&&m!==`hidden`,_=a.parameters!=null&&m!==`hidden`&&!f,v=h||_,y=v&&S(i.id,n,o),x=o?.showDetailsLabel??`Show details`,T=o?.hideDetailsLabel??`Hide details`,E=t(`button`,`persona-approval-head`);E.type=`button`,v?(E.setAttribute(`data-action`,`toggle-params`),E.setAttribute(`aria-expanded`,y?`true`:`false`),E.setAttribute(`aria-label`,y?T:x)):E.setAttribute(`data-static`,`true`);let D=t(`span`,`persona-approval-logo`),O=c(s.ShieldCheck,16,`currentColor`,2);O&&D.appendChild(O),E.appendChild(D);let k=w(a,o);if(v){let e=t(`span`,`persona-approval-toggle`);e.setAttribute(`aria-hidden`,`true`);let n=c(s.ChevronDown,14,`currentColor`,2);n&&e.appendChild(n),k.append(` `),k.appendChild(e)}E.appendChild(k),p.appendChild(E);let A=t(`div`,`persona-approval-body`);if(v){let e=t(`div`,`persona-approval-details`);if(e.setAttribute(`data-role`,`params`),e.hidden=!y,h){let n=t(`p`,`persona-approval-desc`);o?.descriptionColor&&(n.style.color=o.descriptionColor),n.textContent=a.description,e.appendChild(n)}if(_){let n=t(`pre`,`persona-approval-params`);o?.parameterBackgroundColor&&(n.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(n.style.color=o.parameterTextColor),n.textContent=r(a.parameters),e.appendChild(n)}A.appendChild(e)}if(f){let e=t(`div`,`persona-approval-call`);e.setAttribute(`data-role`,`raw-call`);let n=t(`code`,`persona-approval-tool-name`);if(n.textContent=a.toolName,e.appendChild(n),a.parameters!=null){let n=t(`pre`,`persona-approval-params`);o?.parameterBackgroundColor&&(n.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(n.style.color=o.parameterTextColor),n.textContent=r(a.parameters),e.appendChild(n)}A.appendChild(e)}if(a.reason){let e=t(`p`,`persona-approval-reason`);o?.reasonColor?e.style.color=o.reasonColor:o?.descriptionColor&&(e.style.color=o.descriptionColor);let n=t(`span`,`persona-approval-reason-label`);n.textContent=`${o?.reasonLabel??`Agent's stated reason:`} `,e.append(n,document.createTextNode(a.reason)),A.appendChild(e)}let j=t(`div`,`persona-approval-actions`),M=null,N=e=>{o?.approveButtonColor&&(e.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(e.style.color=o.approveButtonTextColor)},P=t(`button`,`persona-approval-deny`);if(P.type=`button`,P.setAttribute(`data-action`,`deny`),o?.denyButtonColor&&(P.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(P.style.color=o.denyButtonTextColor),P.append(o?.denyLabel??`Deny`),d){let n=t(`div`,`persona-approval-split`),r=t(`button`,`persona-approval-primary`);r.type=`button`,r.setAttribute(`data-action`,`always`),N(r),r.append(o?.approveLabel??`Always allow`,C(`⏎`));let a=t(`button`,`persona-approval-caret`);a.type=`button`,a.setAttribute(`data-action`,`toggle-menu`),a.setAttribute(`aria-label`,`More options`),N(a);let u=c(s.ChevronDown,15,`currentColor`,2);u&&a.appendChild(u),n.append(r,a),j.append(n,P),P.append(C(`Esc`));let d=t(`div`,`persona-approval-menu`),f=t(`button`,`persona-approval-menu-item`);f.type=`button`,f.append(`Allow once`,C(`⌘⏎`)),d.appendChild(f),M=g({anchor:n,content:d,placement:`bottom-start`,matchAnchorWidth:!0}),e.popovers.set(i.id,M),f.addEventListener(`click`,()=>{b(e,i.id),l()})}else{let e=t(`button`,`persona-approval-primary persona-approval-primary--solo`);e.type=`button`,e.setAttribute(`data-action`,`allow`),N(e),e.append(o?.approveLabel??`Allow`),j.append(e,P)}return A.appendChild(j),p.appendChild(A),p.addEventListener(`click`,t=>{let r=t.target instanceof Element?t.target.closest(`[data-action]`):null;if(!r)return;let a=r.getAttribute(`data-action`);if(a===`toggle-params`){let e=p.querySelector(`[data-role="params"]`);if(e){let t=!!e.hidden;e.hidden=!t,E.setAttribute(`aria-expanded`,t?`true`:`false`),E.setAttribute(`aria-label`,t?T:x),n.set(i.id,t)}}else a===`toggle-menu`?M?.toggle():a===`always`?(b(e,i.id),l({remember:!0})):a===`allow`?(b(e,i.id),l()):a===`deny`&&(b(e,i.id),u())}),p},D=(e=/* @__PURE__ */ new Map)=>{let t=v();return{plugin:{id:`persona-built-in-approval`,renderApproval:({message:n,approve:r,deny:i,config:a})=>{let o=n?.approval;if(!o)return null;let s=x(a);if(o.status!==`pending`){if(b(t,n.id),o.status===`approved`){let e=document.createElement(`div`);return e.style.display=`none`,e}return T(o)}y(t,n.id);let c=!!a?.clientToken,l=s?.enableAlwaysAllow===!0,u=E(t,e,n,o,s,r,i,l,c);if(l){t.pendingOrder.includes(n.id)||t.pendingOrder.push(n.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let e=e=>{_(e)||n.id===t.latestPendingApprovalId&&(e.key===`Escape`||e.key===`Enter`)&&(e.preventDefault(),e.stopImmediatePropagation(),b(t,n.id),e.key===`Escape`?i():e.metaKey||e.ctrlKey?r():r({remember:!0}))};t.keyHandlers.set(n.id,e),document.addEventListener(`keydown`,e)}return u}},teardown:()=>{for(let e of[...t.keyHandlers.keys(),...t.popovers.keys()])b(t,e);t.latestPendingApprovalId=null}}};exports.createApprovalBubble=m,exports.createBuiltInApprovalPlugin=D,exports.humanizeToolName=l,exports.initApprovalUi=a,exports.updateApprovalDetailsUI=p;
|
|
9
|
+
;var l=(/* @__PURE__ */ e((e=>{e.Ban=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`M4.929 4.929 19.07 19.071`}]],e.ChevronDown=[[`path`,{d:`m6 9 6 6 6-6`}]],e.ChevronUp=[[`path`,{d:`m18 15-6-6-6 6`}]],e.ShieldAlert=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`M12 8v4`}],[`path`,{d:`M12 16h.01`}]],e.ShieldCheck=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`m9 12 2 2 4-4`}]],e.ShieldX=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`m14.5 9.5-5 5`}],[`path`,{d:`m9.5 9.5 5 5`}]]})))();const u=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i},d=e=>{let t=(e.startsWith(`webmcp:`)?e.slice(7):e).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return e;let n=t.join(` `).toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},f=e=>e?.approval===!1?void 0:e?.approval,p=(e,t,n)=>{let r=f(n)?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},m=(e,t,n)=>{let r=f(n);e.setAttribute(`aria-expanded`,t?`true`:`false`);let i=e.querySelector(`[data-approval-details-label]`);i&&(i.textContent=t?r?.hideDetailsLabel??`Hide details`:r?.showDetailsLabel??`Show details`);let a=e.querySelector(`[data-approval-details-chevron]`);if(a){a.innerHTML=``;let e=u(t?l.ChevronUp:l.ChevronDown,14,`currentColor`,2);e&&a.appendChild(e)}},h=(e,t,n,r=/* @__PURE__ */ new Map)=>{let i=t.querySelector(`button[data-bubble-type="approval"]`),a=t.querySelector(`[data-approval-details]`);if(!i||!a)return;let o=p(e,r,n);m(i,o,n),a.style.display=o?``:`none`},g=(e,r,i=/* @__PURE__ */ new Map)=>{let o=e.approval,s=r?.approval===!1?void 0:r?.approval,f=o?.status===`pending`,h=n(`div`,[`persona-approval-bubble`,`persona-w-full`,`persona-rounded-2xl`,`persona-border`,`persona-shadow-sm`,`persona-overflow-hidden`].join(` `));if(h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.style.backgroundColor=s?.backgroundColor??`var(--persona-approval-bg)`,h.style.borderColor=s?.borderColor??`var(--persona-approval-border)`,h.style.boxShadow=s?.shadow===void 0?`var(--persona-approval-shadow)`:s.shadow.trim()===``?`none`:s.shadow,!o)return h;let g=n(`div`,`persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3`),_=n(`div`,`persona-flex-shrink-0 persona-mt-0.5`);_.setAttribute(`data-approval-icon`,`true`);let v=o.status===`denied`?l.ShieldX:o.status===`timeout`?l.ShieldAlert:l.ShieldCheck,y=o.status===`approved`?`var(--persona-feedback-success, var(--persona-palette-colors-success-600))`:o.status===`denied`?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:o.status===`timeout`?`var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))`:s?.titleColor??`currentColor`,b=u(v,20,y,2);b&&_.appendChild(b);let x=n(`div`,`persona-flex-1 persona-min-w-0`),S=n(`div`,`persona-flex persona-items-center persona-gap-2`),C=n(`span`,`persona-text-sm persona-font-medium persona-text-persona-primary`);if(s?.titleColor&&(C.style.color=s.titleColor),C.textContent=s?.title??`Approval Required`,S.appendChild(C),!f){let e=n(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`);e.setAttribute(`data-approval-status`,o.status),o.status===`approved`?(e.style.backgroundColor=`var(--persona-palette-colors-success-100)`,e.style.color=`var(--persona-palette-colors-success-700)`,e.textContent=`Approved`):o.status===`denied`?(e.style.backgroundColor=`var(--persona-palette-colors-error-100)`,e.style.color=`var(--persona-palette-colors-error-700)`,e.textContent=`Denied`):o.status===`timeout`&&(e.style.backgroundColor=`var(--persona-palette-colors-warning-100)`,e.style.color=`var(--persona-palette-colors-warning-700)`,e.textContent=o.status===`timeout`&&o.interrupted?`Interrupted`:`Timeout`),S.appendChild(e)}if(x.appendChild(S),o.status===`timeout`&&o.interrupted){let e=n(`p`,`persona-text-sm`);e.textContent=t,x.appendChild(e)}let w=o.toolType===`webmcp`||o.toolName.startsWith(`webmcp:`)?c(o.toolName):void 0,T=s?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...w?{displayTitle:w}:{},...o.reason?{reason:o.reason}:{}}),E=!o.toolName,D=T||(E?o.description:`The assistant wants to use “${w??d(o.toolName)}”.`),O=n(`p`,`persona-text-sm persona-mt-0.5 persona-text-persona-muted`);if(O.setAttribute(`data-approval-summary`,`true`),s?.descriptionColor&&(O.style.color=s.descriptionColor),O.textContent=D,x.appendChild(O),o.reason){let e=n(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-reason`,`true`),s?.reasonColor?e.style.color=s.reasonColor:s?.descriptionColor&&(e.style.color=s.descriptionColor);let t=n(`span`,`persona-font-medium`);t.textContent=`${s?.reasonLabel??`Agent's stated reason:`} `,e.appendChild(t),e.appendChild(document.createTextNode(o.reason)),x.appendChild(e)}let k=s?.detailsDisplay??`collapsed`,A=!!o.description&&!E,j=A||!!o.parameters;if(k!==`hidden`&&j){let t=p(e.id,i,r),c=n(`button`,`persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted`);c.type=`button`,c.setAttribute(`data-expand-header`,`true`),c.setAttribute(`data-bubble-type`,`approval`),s?.descriptionColor&&(c.style.color=s.descriptionColor);let l=n(`span`);l.setAttribute(`data-approval-details-label`,`true`);let u=n(`span`,`persona-inline-flex persona-items-center`);u.setAttribute(`data-approval-details-chevron`,`true`),c.append(l,u),m(c,t,r),x.appendChild(c);let d=n(`div`);if(d.setAttribute(`data-approval-details`,`true`),d.style.display=t?``:`none`,A){let e=n(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);s?.descriptionColor&&(e.style.color=s.descriptionColor),e.textContent=o.description,d.appendChild(e)}if(o.parameters){let e=n(`pre`,`persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary`);s?.parameterBackgroundColor&&(e.style.backgroundColor=s.parameterBackgroundColor),s?.parameterTextColor&&(e.style.color=s.parameterTextColor),e.style.fontSize=`0.75rem`,e.style.lineHeight=`1rem`,e.textContent=a(o.parameters),d.appendChild(e)}x.appendChild(d)}if(f){let e=n(`div`,`persona-flex persona-gap-2 persona-mt-2`);e.setAttribute(`data-approval-buttons`,`true`);let t=n(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer`);t.type=`button`,t.style.backgroundColor=s?.approveButtonColor??`var(--persona-approval-approve-bg)`,t.style.color=s?.approveButtonTextColor??`var(--persona-button-primary-fg)`,t.setAttribute(`data-approval-action`,`approve`);let r=u(l.ShieldCheck,14,s?.approveButtonTextColor??`var(--persona-button-primary-fg)`,2);r&&(r.style.marginRight=`4px`,t.appendChild(r));let i=document.createTextNode(s?.approveLabel??`Approve`);t.appendChild(i);let a=n(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer`);a.type=`button`,a.style.backgroundColor=s?.denyButtonColor??`transparent`,a.style.color=s?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,a.style.border=`1px solid ${s?.denyButtonTextColor?s.denyButtonTextColor:`var(--persona-palette-colors-error-200)`}`,a.setAttribute(`data-approval-action`,`deny`);let o=u(l.ShieldX,14,s?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,2);o&&(o.style.marginRight=`4px`,a.appendChild(o));let c=document.createTextNode(s?.denyLabel??`Deny`);a.appendChild(c),e.append(t,a),x.appendChild(e)}return g.append(_,x),h.appendChild(g),h};function _(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function v(e){let{anchor:t,content:n,placement:r=`bottom-start`,offset:i=6,matchAnchorWidth:a=!1,horizontalOffset:o,verticalOffset:s,zIndex:c=2147483e3,onOpen:l,onDismiss:u}=e,d=e.container??_(t),f=!1,p=null,m=()=>{if(!f)return;let e=t.getBoundingClientRect();n.style.position=`fixed`,a&&(n.style.minWidth=`${e.width}px`),o&&(n.style.maxWidth=`${e.width}px`);let c=n.getBoundingClientRect(),l=s?.()??null,u=l==null?e.top:e.top+l,d=r===`top-start`||r===`top-end`?u-i-c.height:e.bottom+i,p=r===`bottom-end`||r===`top-end`?e.right-c.width:e.left,m=o?.()??null;if(m!=null){let t=Math.max(e.left,e.right-c.width);p=Math.min(Math.max(e.left+m,e.left),t)}n.style.top=`${d}px`,n.style.left=`${p}px`},h=()=>{f&&(f=!1,p&&=(p(),null),n.remove())},g=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),d.appendChild(n),m();let e=(t.ownerDocument??document).defaultView??window,r=t.ownerDocument??document,i=()=>{t.isConnected?m():(h(),u?.(`anchor-removed`))},a=e=>{let r=typeof e.composedPath==`function`?e.composedPath():[];r.includes(n)||r.includes(t)||(h(),u?.(`outside`))},o=e.setTimeout(()=>{r.addEventListener(`pointerdown`,a,!0)},0);e.addEventListener(`scroll`,i,!0),e.addEventListener(`resize`,i),p=()=>{e.clearTimeout(o),r.removeEventListener(`pointerdown`,a,!0),e.removeEventListener(`scroll`,i,!0),e.removeEventListener(`resize`,i)},l?.()};return{get isOpen(){return f},open:g,close:h,toggle:()=>f?h():g(),reposition:m,destroy:h}}function y(e){return(typeof e.composedPath==`function`?e.composedPath():[]).some(e=>e instanceof HTMLElement&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable))}const b=()=>({keyHandlers:/* @__PURE__ */ new Map,popovers:/* @__PURE__ */ new Map,pendingOrder:[],latestPendingApprovalId:null}),x=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener(`keydown`,n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},S=(e,t)=>{x(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},C=e=>e?.approval===!1?void 0:e?.approval,w=(e,t,n)=>{let r=n?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},T=e=>{let t=n(`span`,`persona-approval-kbd`);return t.textContent=e,t},E=(e,t)=>{let r=n(`span`,`persona-approval-title`);t?.titleColor&&(r.style.color=t.titleColor);let i=e.toolType===`webmcp`||e.toolName.startsWith(`webmcp:`)?c(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??``,parameters:e.parameters,...i?{displayTitle:i}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let o=i??d(e.toolName),s=e.toolType&&e.toolType!==`webmcp`?e.toolType:null;r.append(`The assistant wants to use `);let l=document.createElement(`strong`);if(l.textContent=o,r.appendChild(l),s){r.append(` from `);let e=document.createElement(`strong`);e.textContent=s,r.appendChild(e)}return r},D=e=>{let i=n(`div`,`persona-approval-resolved`),a=u(l.Ban,15,`currentColor`,2);a&&i.appendChild(a);let o=n(`span`,`persona-approval-resolved-name`);o.textContent=e.toolName?d(e.toolName):`Tool`;let s=e.status===`timeout`&&e.interrupted?` approval expired. ${t}`:e.status===`timeout`?` timed out`:` denied`;return i.appendChild(r(`span`,{className:`persona-approval-resolved-text`},o,s)),i},O=(e,t,r,i,o,s,c,d,f=!1)=>{let p=n(`div`,`persona-approval-card persona-shadow-sm`);p.id=`bubble-${r.id}`,p.setAttribute(`data-message-id`,r.id),p.setAttribute(`data-bubble-type`,`approval`),o?.backgroundColor&&(p.style.background=o.backgroundColor),o?.borderColor&&(p.style.borderColor=o.borderColor),o?.shadow!==void 0&&(p.style.boxShadow=o.shadow.trim()===``?`none`:o.shadow);let m=o?.detailsDisplay??`collapsed`,h=!!i.description&&m!==`hidden`,g=i.parameters!=null&&m!==`hidden`&&!f,_=h||g,y=_&&w(r.id,t,o),b=o?.showDetailsLabel??`Show details`,x=o?.hideDetailsLabel??`Hide details`,C=n(`button`,`persona-approval-head`);C.type=`button`,_?(C.setAttribute(`data-action`,`toggle-params`),C.setAttribute(`aria-expanded`,y?`true`:`false`),C.setAttribute(`aria-label`,y?x:b)):C.setAttribute(`data-static`,`true`);let D=n(`span`,`persona-approval-logo`),O=u(l.ShieldCheck,16,`currentColor`,2);O&&D.appendChild(O),C.appendChild(D);let k=E(i,o);if(_){let e=n(`span`,`persona-approval-toggle`);e.setAttribute(`aria-hidden`,`true`);let t=u(l.ChevronDown,14,`currentColor`,2);t&&e.appendChild(t),k.append(` `),k.appendChild(e)}C.appendChild(k),p.appendChild(C);let A=n(`div`,`persona-approval-body`);if(_){let e=n(`div`,`persona-approval-details`);if(e.setAttribute(`data-role`,`params`),e.hidden=!y,h){let t=n(`p`,`persona-approval-desc`);o?.descriptionColor&&(t.style.color=o.descriptionColor),t.textContent=i.description,e.appendChild(t)}if(g){let t=n(`pre`,`persona-approval-params`);o?.parameterBackgroundColor&&(t.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(t.style.color=o.parameterTextColor),t.textContent=a(i.parameters),e.appendChild(t)}A.appendChild(e)}if(f){let e=n(`div`,`persona-approval-call`);e.setAttribute(`data-role`,`raw-call`);let t=n(`code`,`persona-approval-tool-name`);if(t.textContent=i.toolName,e.appendChild(t),i.parameters!=null){let t=n(`pre`,`persona-approval-params`);o?.parameterBackgroundColor&&(t.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(t.style.color=o.parameterTextColor),t.textContent=a(i.parameters),e.appendChild(t)}A.appendChild(e)}if(i.reason){let e=n(`p`,`persona-approval-reason`);o?.reasonColor?e.style.color=o.reasonColor:o?.descriptionColor&&(e.style.color=o.descriptionColor);let t=n(`span`,`persona-approval-reason-label`);t.textContent=`${o?.reasonLabel??`Agent's stated reason:`} `,e.append(t,document.createTextNode(i.reason)),A.appendChild(e)}let j=n(`div`,`persona-approval-actions`),M=null,N=e=>{o?.approveButtonColor&&(e.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(e.style.color=o.approveButtonTextColor)},P=n(`button`,`persona-approval-deny`);if(P.type=`button`,P.setAttribute(`data-action`,`deny`),o?.denyButtonColor&&(P.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(P.style.color=o.denyButtonTextColor),P.append(o?.denyLabel??`Deny`),d){let t=n(`div`,`persona-approval-split`),i=n(`button`,`persona-approval-primary`);i.type=`button`,i.setAttribute(`data-action`,`always`),N(i),i.append(o?.approveLabel??`Always allow`,T(`⏎`));let a=n(`button`,`persona-approval-caret`);a.type=`button`,a.setAttribute(`data-action`,`toggle-menu`),a.setAttribute(`aria-label`,`More options`),N(a);let c=u(l.ChevronDown,15,`currentColor`,2);c&&a.appendChild(c),t.append(i,a),j.append(t,P),P.append(T(`Esc`));let d=n(`div`,`persona-approval-menu`),f=n(`button`,`persona-approval-menu-item`);f.type=`button`,f.append(`Allow once`,T(`⌘⏎`)),d.appendChild(f),M=v({anchor:t,content:d,placement:`bottom-start`,matchAnchorWidth:!0}),e.popovers.set(r.id,M),f.addEventListener(`click`,()=>{S(e,r.id),s()})}else{let e=n(`button`,`persona-approval-primary persona-approval-primary--solo`);e.type=`button`,e.setAttribute(`data-action`,`allow`),N(e),e.append(o?.approveLabel??`Allow`),j.append(e,P)}return A.appendChild(j),p.appendChild(A),p.addEventListener(`click`,n=>{let i=n.target instanceof Element?n.target.closest(`[data-action]`):null;if(!i)return;let a=i.getAttribute(`data-action`);if(a===`toggle-params`){let e=p.querySelector(`[data-role="params"]`);if(e){let n=!!e.hidden;e.hidden=!n,C.setAttribute(`aria-expanded`,n?`true`:`false`),C.setAttribute(`aria-label`,n?x:b),t.set(r.id,n)}}else a===`toggle-menu`?M?.toggle():a===`always`?(S(e,r.id),s({remember:!0})):a===`allow`?(S(e,r.id),s()):a===`deny`&&(S(e,r.id),c())}),p},k=(e=/* @__PURE__ */ new Map)=>{let t=b();return{plugin:{id:`persona-built-in-approval`,renderApproval:({message:n,approve:r,deny:i,config:a})=>{let o=n?.approval;if(!o)return null;let s=C(a);if(o.status!==`pending`){if(S(t,n.id),o.status===`approved`){let e=document.createElement(`div`);return e.style.display=`none`,e}return D(o)}x(t,n.id);let c=!!a?.clientToken,l=s?.enableAlwaysAllow===!0,u=O(t,e,n,o,s,r,i,l,c);if(l){t.pendingOrder.includes(n.id)||t.pendingOrder.push(n.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let e=e=>{y(e)||n.id===t.latestPendingApprovalId&&(e.key===`Escape`||e.key===`Enter`)&&(e.preventDefault(),e.stopImmediatePropagation(),S(t,n.id),e.key===`Escape`?i():e.metaKey||e.ctrlKey?r():r({remember:!0}))};t.keyHandlers.set(n.id,e),document.addEventListener(`keydown`,e)}return u}},teardown:()=>{for(let e of[...t.keyHandlers.keys(),...t.popovers.keys()])S(t,e);t.latestPendingApprovalId=null}}};exports.createApprovalBubble=g,exports.createBuiltInApprovalPlugin=k,exports.humanizeToolName=d,exports.initApprovalUi=s,exports.updateApprovalDetailsUI=h;
|
package/dist/approval-ui.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { T as AgentWidgetConfig, Va as AgentWidgetPlugin, mt as AgentWidgetMessage } from "./types-BuDirJkQ.cjs";
|
|
2
2
|
//#region src/components/approval-bubble.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* Turn a wire tool name into a user-facing label: strips the `webmcp:`
|
package/dist/approval-ui.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { T as AgentWidgetConfig, Va as AgentWidgetPlugin, mt as AgentWidgetMessage } from "./types-BuDirJkQ.js";
|
|
2
2
|
//#region src/components/approval-bubble.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* Turn a wire tool name into a user-facing label: strips the `webmcp:`
|
package/dist/approval-ui.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const t=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var
|
|
2
|
-
\r `.includes(e[
|
|
1
|
+
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const t=`The chat restarted and this browser tool was interrupted. Request a fresh proposal to try again.`,n=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},r=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r};var i=/* @__PURE__ */ e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow}));(/* @__PURE__ */ e((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let r=i();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(i(),e);var a=class extends Error{};e.PartialJSON=a;var o=class extends Error{};e.MalformedJSON=o;function s(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return c(e.trim(),t)}e.parseJSON=s;let c=(e,t)=>{let n=e.length,i=0,s=e=>{throw new a(`${e} at position ${i}`)},c=e=>{throw new o(`${e} at position ${i}`)},l=()=>(m(),i>=n&&s(`Unexpected end of input`),e[i]===`"`?u():e[i]===`{`?d():e[i]===`[`?f():e.substring(i,i+4)===`null`||r.Allow.NULL&t&&n-i<4&&`null`.startsWith(e.substring(i))?(i+=4,null):e.substring(i,i+4)===`true`||r.Allow.BOOL&t&&n-i<4&&`true`.startsWith(e.substring(i))?(i+=4,!0):e.substring(i,i+5)===`false`||r.Allow.BOOL&t&&n-i<5&&`false`.startsWith(e.substring(i))?(i+=5,!1):e.substring(i,i+8)===`Infinity`||r.Allow.INFINITY&t&&n-i<8&&`Infinity`.startsWith(e.substring(i))?(i+=8,1/0):e.substring(i,i+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-i&&n-i<9&&`-Infinity`.startsWith(e.substring(i))?(i+=9,-1/0):e.substring(i,i+3)===`NaN`||r.Allow.NAN&t&&n-i<3&&`NaN`.startsWith(e.substring(i))?(i+=3,NaN):p()),u=()=>{let a=i,o=!1;for(i++;i<n&&(e[i]!==`"`||o&&e[i-1]===`\\`);)o=e[i]===`\\`&&!o,i++;if(e.charAt(i)==`"`)try{return JSON.parse(e.substring(a,++i-Number(o)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(a,i-Number(o))+`"`)}catch{return JSON.parse(e.substring(a,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{i++,m();let a={};try{for(;e[i]!==`}`;){if(m(),i>=n&&r.Allow.OBJ&t)return a;let o=u();m(),i++;try{a[o]=l()}catch(e){if(r.Allow.OBJ&t)return a;throw e}m(),e[i]===`,`&&i++}}catch{if(r.Allow.OBJ&t)return a;s(`Expected '}' at end of object`)}return i++,a},f=()=>{i++;let n=[];try{for(;e[i]!==`]`;)n.push(l()),m(),e[i]===`,`&&i++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return i++,n},p=()=>{if(i===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let a=i;for(e[i]===`-`&&i++;e[i]&&`,]}`.indexOf(e[i])===-1;)i++;i==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(a,i))}catch{e.substring(a,i)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(a,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;i<n&&`
|
|
2
|
+
\r `.includes(e[i]);)i++};return l()};e.parse=s})))();const a=e=>{if(e===null)return`null`;if(e===void 0)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}};let o=()=>void 0;const s=e=>{o=e.webMcpToolTitle},c=e=>o(e)
|
|
3
3
|
/**
|
|
4
4
|
* @license lucide v1.18.0 - ISC
|
|
5
5
|
*
|
|
6
6
|
* This source code is licensed under the ISC license.
|
|
7
7
|
* See the LICENSE file in the root directory of this source tree.
|
|
8
8
|
*/
|
|
9
|
-
;var s=(/* @__PURE__ */ e((e=>{e.Ban=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`M4.929 4.929 19.07 19.071`}]],e.ChevronDown=[[`path`,{d:`m6 9 6 6 6-6`}]],e.ChevronUp=[[`path`,{d:`m18 15-6-6-6 6`}]],e.ShieldAlert=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`M12 8v4`}],[`path`,{d:`M12 16h.01`}]],e.ShieldCheck=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`m9 12 2 2 4-4`}]],e.ShieldX=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`m14.5 9.5-5 5`}],[`path`,{d:`m9.5 9.5 5 5`}]]})))();const c=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i},l=e=>{let t=(e.startsWith(`webmcp:`)?e.slice(7):e).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return e;let n=t.join(` `).toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},u=e=>e?.approval===!1?void 0:e?.approval,d=(e,t,n)=>{let r=u(n)?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},f=(e,t,n)=>{let r=u(n);e.setAttribute(`aria-expanded`,t?`true`:`false`);let i=e.querySelector(`[data-approval-details-label]`);i&&(i.textContent=t?r?.hideDetailsLabel??`Hide details`:r?.showDetailsLabel??`Show details`);let a=e.querySelector(`[data-approval-details-chevron]`);if(a){a.innerHTML=``;let e=c(t?s.ChevronUp:s.ChevronDown,14,`currentColor`,2);e&&a.appendChild(e)}},p=(e,t,n,r=/* @__PURE__ */ new Map)=>{let i=t.querySelector(`button[data-bubble-type="approval"]`),a=t.querySelector(`[data-approval-details]`);if(!i||!a)return;let o=d(e,r,n);f(i,o,n),a.style.display=o?``:`none`},m=(e,n,i=/* @__PURE__ */ new Map)=>{let a=e.approval,u=n?.approval===!1?void 0:n?.approval,p=a?.status===`pending`,m=t(`div`,[`persona-approval-bubble`,`persona-w-full`,`persona-rounded-2xl`,`persona-border`,`persona-shadow-sm`,`persona-overflow-hidden`].join(` `));if(m.id=`bubble-${e.id}`,m.setAttribute(`data-message-id`,e.id),m.style.backgroundColor=u?.backgroundColor??`var(--persona-approval-bg)`,m.style.borderColor=u?.borderColor??`var(--persona-approval-border)`,m.style.boxShadow=u?.shadow===void 0?`var(--persona-approval-shadow)`:u.shadow.trim()===``?`none`:u.shadow,!a)return m;let h=t(`div`,`persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3`),g=t(`div`,`persona-flex-shrink-0 persona-mt-0.5`);g.setAttribute(`data-approval-icon`,`true`);let _=a.status===`denied`?s.ShieldX:a.status===`timeout`?s.ShieldAlert:s.ShieldCheck,v=a.status===`approved`?`var(--persona-feedback-success, var(--persona-palette-colors-success-600))`:a.status===`denied`?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:a.status===`timeout`?`var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))`:u?.titleColor??`currentColor`,y=c(_,20,v,2);y&&g.appendChild(y);let b=t(`div`,`persona-flex-1 persona-min-w-0`),x=t(`div`,`persona-flex persona-items-center persona-gap-2`),S=t(`span`,`persona-text-sm persona-font-medium persona-text-persona-primary`);if(u?.titleColor&&(S.style.color=u.titleColor),S.textContent=u?.title??`Approval Required`,x.appendChild(S),!p){let e=t(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`);e.setAttribute(`data-approval-status`,a.status),a.status===`approved`?(e.style.backgroundColor=`var(--persona-palette-colors-success-100)`,e.style.color=`var(--persona-palette-colors-success-700)`,e.textContent=`Approved`):a.status===`denied`?(e.style.backgroundColor=`var(--persona-palette-colors-error-100)`,e.style.color=`var(--persona-palette-colors-error-700)`,e.textContent=`Denied`):a.status===`timeout`&&(e.style.backgroundColor=`var(--persona-palette-colors-warning-100)`,e.style.color=`var(--persona-palette-colors-warning-700)`,e.textContent=`Timeout`),x.appendChild(e)}b.appendChild(x);let C=a.toolType===`webmcp`||a.toolName.startsWith(`webmcp:`)?o(a.toolName):void 0,w=u?.formatDescription?.({toolName:a.toolName,toolType:a.toolType,description:a.description,parameters:a.parameters,...C?{displayTitle:C}:{},...a.reason?{reason:a.reason}:{}}),T=!a.toolName,E=w||(T?a.description:`The assistant wants to use “${C??l(a.toolName)}”.`),D=t(`p`,`persona-text-sm persona-mt-0.5 persona-text-persona-muted`);if(D.setAttribute(`data-approval-summary`,`true`),u?.descriptionColor&&(D.style.color=u.descriptionColor),D.textContent=E,b.appendChild(D),a.reason){let e=t(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-reason`,`true`),u?.reasonColor?e.style.color=u.reasonColor:u?.descriptionColor&&(e.style.color=u.descriptionColor);let n=t(`span`,`persona-font-medium`);n.textContent=`${u?.reasonLabel??`Agent's stated reason:`} `,e.appendChild(n),e.appendChild(document.createTextNode(a.reason)),b.appendChild(e)}let O=u?.detailsDisplay??`collapsed`,k=!!a.description&&!T,A=k||!!a.parameters;if(O!==`hidden`&&A){let o=d(e.id,i,n),s=t(`button`,`persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted`);s.type=`button`,s.setAttribute(`data-expand-header`,`true`),s.setAttribute(`data-bubble-type`,`approval`),u?.descriptionColor&&(s.style.color=u.descriptionColor);let c=t(`span`);c.setAttribute(`data-approval-details-label`,`true`);let l=t(`span`,`persona-inline-flex persona-items-center`);l.setAttribute(`data-approval-details-chevron`,`true`),s.append(c,l),f(s,o,n),b.appendChild(s);let p=t(`div`);if(p.setAttribute(`data-approval-details`,`true`),p.style.display=o?``:`none`,k){let e=t(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);u?.descriptionColor&&(e.style.color=u.descriptionColor),e.textContent=a.description,p.appendChild(e)}if(a.parameters){let e=t(`pre`,`persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary`);u?.parameterBackgroundColor&&(e.style.backgroundColor=u.parameterBackgroundColor),u?.parameterTextColor&&(e.style.color=u.parameterTextColor),e.style.fontSize=`0.75rem`,e.style.lineHeight=`1rem`,e.textContent=r(a.parameters),p.appendChild(e)}b.appendChild(p)}if(p){let e=t(`div`,`persona-flex persona-gap-2 persona-mt-2`);e.setAttribute(`data-approval-buttons`,`true`);let n=t(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer`);n.type=`button`,n.style.backgroundColor=u?.approveButtonColor??`var(--persona-approval-approve-bg)`,n.style.color=u?.approveButtonTextColor??`var(--persona-button-primary-fg)`,n.setAttribute(`data-approval-action`,`approve`);let r=c(s.ShieldCheck,14,u?.approveButtonTextColor??`var(--persona-button-primary-fg)`,2);r&&(r.style.marginRight=`4px`,n.appendChild(r));let i=document.createTextNode(u?.approveLabel??`Approve`);n.appendChild(i);let a=t(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer`);a.type=`button`,a.style.backgroundColor=u?.denyButtonColor??`transparent`,a.style.color=u?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,a.style.border=`1px solid ${u?.denyButtonTextColor?u.denyButtonTextColor:`var(--persona-palette-colors-error-200)`}`,a.setAttribute(`data-approval-action`,`deny`);let o=c(s.ShieldX,14,u?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,2);o&&(o.style.marginRight=`4px`,a.appendChild(o));let l=document.createTextNode(u?.denyLabel??`Deny`);a.appendChild(l),e.append(n,a),b.appendChild(e)}return h.append(g,b),m.appendChild(h),m};function h(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function g(e){let{anchor:t,content:n,placement:r=`bottom-start`,offset:i=6,matchAnchorWidth:a=!1,horizontalOffset:o,verticalOffset:s,zIndex:c=2147483e3,onOpen:l,onDismiss:u}=e,d=e.container??h(t),f=!1,p=null,m=()=>{if(!f)return;let e=t.getBoundingClientRect();n.style.position=`fixed`,a&&(n.style.minWidth=`${e.width}px`),o&&(n.style.maxWidth=`${e.width}px`);let c=n.getBoundingClientRect(),l=s?.()??null,u=l==null?e.top:e.top+l,d=r===`top-start`||r===`top-end`?u-i-c.height:e.bottom+i,p=r===`bottom-end`||r===`top-end`?e.right-c.width:e.left,m=o?.()??null;if(m!=null){let t=Math.max(e.left,e.right-c.width);p=Math.min(Math.max(e.left+m,e.left),t)}n.style.top=`${d}px`,n.style.left=`${p}px`},g=()=>{f&&(f=!1,p&&=(p(),null),n.remove())},_=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),d.appendChild(n),m();let e=(t.ownerDocument??document).defaultView??window,r=t.ownerDocument??document,i=()=>{t.isConnected?m():(g(),u?.(`anchor-removed`))},a=e=>{let r=typeof e.composedPath==`function`?e.composedPath():[];r.includes(n)||r.includes(t)||(g(),u?.(`outside`))},o=e.setTimeout(()=>{r.addEventListener(`pointerdown`,a,!0)},0);e.addEventListener(`scroll`,i,!0),e.addEventListener(`resize`,i),p=()=>{e.clearTimeout(o),r.removeEventListener(`pointerdown`,a,!0),e.removeEventListener(`scroll`,i,!0),e.removeEventListener(`resize`,i)},l?.()};return{get isOpen(){return f},open:_,close:g,toggle:()=>f?g():_(),reposition:m,destroy:g}}function _(e){return(typeof e.composedPath==`function`?e.composedPath():[]).some(e=>e instanceof HTMLElement&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable))}const v=()=>({keyHandlers:/* @__PURE__ */ new Map,popovers:/* @__PURE__ */ new Map,pendingOrder:[],latestPendingApprovalId:null}),y=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener(`keydown`,n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},b=(e,t)=>{y(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},x=e=>e?.approval===!1?void 0:e?.approval,S=(e,t,n)=>{let r=n?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},C=e=>{let n=t(`span`,`persona-approval-kbd`);return n.textContent=e,n},w=(e,n)=>{let r=t(`span`,`persona-approval-title`);n?.titleColor&&(r.style.color=n.titleColor);let i=e.toolType===`webmcp`||e.toolName.startsWith(`webmcp:`)?o(e.toolName):void 0,a=n?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??``,parameters:e.parameters,...i?{displayTitle:i}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let s=i??l(e.toolName),c=e.toolType&&e.toolType!==`webmcp`?e.toolType:null;r.append(`The assistant wants to use `);let u=document.createElement(`strong`);if(u.textContent=s,r.appendChild(u),c){r.append(` from `);let e=document.createElement(`strong`);e.textContent=c,r.appendChild(e)}return r},T=e=>{let n=t(`div`,`persona-approval-resolved`),r=c(s.Ban,15,`currentColor`,2);r&&n.appendChild(r);let i=t(`span`,`persona-approval-resolved-name`);return i.textContent=e.toolName?l(e.toolName):`Tool`,n.append(i,document.createTextNode(e.status===`timeout`?` timed out`:` denied`)),n},E=(e,n,i,a,o,l,u,d,f=!1)=>{let p=t(`div`,`persona-approval-card persona-shadow-sm`);p.id=`bubble-${i.id}`,p.setAttribute(`data-message-id`,i.id),p.setAttribute(`data-bubble-type`,`approval`),o?.backgroundColor&&(p.style.background=o.backgroundColor),o?.borderColor&&(p.style.borderColor=o.borderColor),o?.shadow!==void 0&&(p.style.boxShadow=o.shadow.trim()===``?`none`:o.shadow);let m=o?.detailsDisplay??`collapsed`,h=!!a.description&&m!==`hidden`,_=a.parameters!=null&&m!==`hidden`&&!f,v=h||_,y=v&&S(i.id,n,o),x=o?.showDetailsLabel??`Show details`,T=o?.hideDetailsLabel??`Hide details`,E=t(`button`,`persona-approval-head`);E.type=`button`,v?(E.setAttribute(`data-action`,`toggle-params`),E.setAttribute(`aria-expanded`,y?`true`:`false`),E.setAttribute(`aria-label`,y?T:x)):E.setAttribute(`data-static`,`true`);let D=t(`span`,`persona-approval-logo`),O=c(s.ShieldCheck,16,`currentColor`,2);O&&D.appendChild(O),E.appendChild(D);let k=w(a,o);if(v){let e=t(`span`,`persona-approval-toggle`);e.setAttribute(`aria-hidden`,`true`);let n=c(s.ChevronDown,14,`currentColor`,2);n&&e.appendChild(n),k.append(` `),k.appendChild(e)}E.appendChild(k),p.appendChild(E);let A=t(`div`,`persona-approval-body`);if(v){let e=t(`div`,`persona-approval-details`);if(e.setAttribute(`data-role`,`params`),e.hidden=!y,h){let n=t(`p`,`persona-approval-desc`);o?.descriptionColor&&(n.style.color=o.descriptionColor),n.textContent=a.description,e.appendChild(n)}if(_){let n=t(`pre`,`persona-approval-params`);o?.parameterBackgroundColor&&(n.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(n.style.color=o.parameterTextColor),n.textContent=r(a.parameters),e.appendChild(n)}A.appendChild(e)}if(f){let e=t(`div`,`persona-approval-call`);e.setAttribute(`data-role`,`raw-call`);let n=t(`code`,`persona-approval-tool-name`);if(n.textContent=a.toolName,e.appendChild(n),a.parameters!=null){let n=t(`pre`,`persona-approval-params`);o?.parameterBackgroundColor&&(n.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(n.style.color=o.parameterTextColor),n.textContent=r(a.parameters),e.appendChild(n)}A.appendChild(e)}if(a.reason){let e=t(`p`,`persona-approval-reason`);o?.reasonColor?e.style.color=o.reasonColor:o?.descriptionColor&&(e.style.color=o.descriptionColor);let n=t(`span`,`persona-approval-reason-label`);n.textContent=`${o?.reasonLabel??`Agent's stated reason:`} `,e.append(n,document.createTextNode(a.reason)),A.appendChild(e)}let j=t(`div`,`persona-approval-actions`),M=null,N=e=>{o?.approveButtonColor&&(e.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(e.style.color=o.approveButtonTextColor)},P=t(`button`,`persona-approval-deny`);if(P.type=`button`,P.setAttribute(`data-action`,`deny`),o?.denyButtonColor&&(P.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(P.style.color=o.denyButtonTextColor),P.append(o?.denyLabel??`Deny`),d){let n=t(`div`,`persona-approval-split`),r=t(`button`,`persona-approval-primary`);r.type=`button`,r.setAttribute(`data-action`,`always`),N(r),r.append(o?.approveLabel??`Always allow`,C(`⏎`));let a=t(`button`,`persona-approval-caret`);a.type=`button`,a.setAttribute(`data-action`,`toggle-menu`),a.setAttribute(`aria-label`,`More options`),N(a);let u=c(s.ChevronDown,15,`currentColor`,2);u&&a.appendChild(u),n.append(r,a),j.append(n,P),P.append(C(`Esc`));let d=t(`div`,`persona-approval-menu`),f=t(`button`,`persona-approval-menu-item`);f.type=`button`,f.append(`Allow once`,C(`⌘⏎`)),d.appendChild(f),M=g({anchor:n,content:d,placement:`bottom-start`,matchAnchorWidth:!0}),e.popovers.set(i.id,M),f.addEventListener(`click`,()=>{b(e,i.id),l()})}else{let e=t(`button`,`persona-approval-primary persona-approval-primary--solo`);e.type=`button`,e.setAttribute(`data-action`,`allow`),N(e),e.append(o?.approveLabel??`Allow`),j.append(e,P)}return A.appendChild(j),p.appendChild(A),p.addEventListener(`click`,t=>{let r=t.target instanceof Element?t.target.closest(`[data-action]`):null;if(!r)return;let a=r.getAttribute(`data-action`);if(a===`toggle-params`){let e=p.querySelector(`[data-role="params"]`);if(e){let t=!!e.hidden;e.hidden=!t,E.setAttribute(`aria-expanded`,t?`true`:`false`),E.setAttribute(`aria-label`,t?T:x),n.set(i.id,t)}}else a===`toggle-menu`?M?.toggle():a===`always`?(b(e,i.id),l({remember:!0})):a===`allow`?(b(e,i.id),l()):a===`deny`&&(b(e,i.id),u())}),p},D=(e=/* @__PURE__ */ new Map)=>{let t=v();return{plugin:{id:`persona-built-in-approval`,renderApproval:({message:n,approve:r,deny:i,config:a})=>{let o=n?.approval;if(!o)return null;let s=x(a);if(o.status!==`pending`){if(b(t,n.id),o.status===`approved`){let e=document.createElement(`div`);return e.style.display=`none`,e}return T(o)}y(t,n.id);let c=!!a?.clientToken,l=s?.enableAlwaysAllow===!0,u=E(t,e,n,o,s,r,i,l,c);if(l){t.pendingOrder.includes(n.id)||t.pendingOrder.push(n.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let e=e=>{_(e)||n.id===t.latestPendingApprovalId&&(e.key===`Escape`||e.key===`Enter`)&&(e.preventDefault(),e.stopImmediatePropagation(),b(t,n.id),e.key===`Escape`?i():e.metaKey||e.ctrlKey?r():r({remember:!0}))};t.keyHandlers.set(n.id,e),document.addEventListener(`keydown`,e)}return u}},teardown:()=>{for(let e of[...t.keyHandlers.keys(),...t.popovers.keys()])b(t,e);t.latestPendingApprovalId=null}}};export{m as createApprovalBubble,D as createBuiltInApprovalPlugin,l as humanizeToolName,a as initApprovalUi,p as updateApprovalDetailsUI};
|
|
9
|
+
;var l=(/* @__PURE__ */ e((e=>{e.Ban=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`M4.929 4.929 19.07 19.071`}]],e.ChevronDown=[[`path`,{d:`m6 9 6 6 6-6`}]],e.ChevronUp=[[`path`,{d:`m18 15-6-6-6 6`}]],e.ShieldAlert=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`M12 8v4`}],[`path`,{d:`M12 16h.01`}]],e.ShieldCheck=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`m9 12 2 2 4-4`}]],e.ShieldX=[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}],[`path`,{d:`m14.5 9.5-5 5`}],[`path`,{d:`m9.5 9.5 5 5`}]]})))();const u=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i},d=e=>{let t=(e.startsWith(`webmcp:`)?e.slice(7):e).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return e;let n=t.join(` `).toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},f=e=>e?.approval===!1?void 0:e?.approval,p=(e,t,n)=>{let r=f(n)?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},m=(e,t,n)=>{let r=f(n);e.setAttribute(`aria-expanded`,t?`true`:`false`);let i=e.querySelector(`[data-approval-details-label]`);i&&(i.textContent=t?r?.hideDetailsLabel??`Hide details`:r?.showDetailsLabel??`Show details`);let a=e.querySelector(`[data-approval-details-chevron]`);if(a){a.innerHTML=``;let e=u(t?l.ChevronUp:l.ChevronDown,14,`currentColor`,2);e&&a.appendChild(e)}},h=(e,t,n,r=/* @__PURE__ */ new Map)=>{let i=t.querySelector(`button[data-bubble-type="approval"]`),a=t.querySelector(`[data-approval-details]`);if(!i||!a)return;let o=p(e,r,n);m(i,o,n),a.style.display=o?``:`none`},g=(e,r,i=/* @__PURE__ */ new Map)=>{let o=e.approval,s=r?.approval===!1?void 0:r?.approval,f=o?.status===`pending`,h=n(`div`,[`persona-approval-bubble`,`persona-w-full`,`persona-rounded-2xl`,`persona-border`,`persona-shadow-sm`,`persona-overflow-hidden`].join(` `));if(h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.style.backgroundColor=s?.backgroundColor??`var(--persona-approval-bg)`,h.style.borderColor=s?.borderColor??`var(--persona-approval-border)`,h.style.boxShadow=s?.shadow===void 0?`var(--persona-approval-shadow)`:s.shadow.trim()===``?`none`:s.shadow,!o)return h;let g=n(`div`,`persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3`),_=n(`div`,`persona-flex-shrink-0 persona-mt-0.5`);_.setAttribute(`data-approval-icon`,`true`);let v=o.status===`denied`?l.ShieldX:o.status===`timeout`?l.ShieldAlert:l.ShieldCheck,y=o.status===`approved`?`var(--persona-feedback-success, var(--persona-palette-colors-success-600))`:o.status===`denied`?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:o.status===`timeout`?`var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))`:s?.titleColor??`currentColor`,b=u(v,20,y,2);b&&_.appendChild(b);let x=n(`div`,`persona-flex-1 persona-min-w-0`),S=n(`div`,`persona-flex persona-items-center persona-gap-2`),C=n(`span`,`persona-text-sm persona-font-medium persona-text-persona-primary`);if(s?.titleColor&&(C.style.color=s.titleColor),C.textContent=s?.title??`Approval Required`,S.appendChild(C),!f){let e=n(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`);e.setAttribute(`data-approval-status`,o.status),o.status===`approved`?(e.style.backgroundColor=`var(--persona-palette-colors-success-100)`,e.style.color=`var(--persona-palette-colors-success-700)`,e.textContent=`Approved`):o.status===`denied`?(e.style.backgroundColor=`var(--persona-palette-colors-error-100)`,e.style.color=`var(--persona-palette-colors-error-700)`,e.textContent=`Denied`):o.status===`timeout`&&(e.style.backgroundColor=`var(--persona-palette-colors-warning-100)`,e.style.color=`var(--persona-palette-colors-warning-700)`,e.textContent=o.status===`timeout`&&o.interrupted?`Interrupted`:`Timeout`),S.appendChild(e)}if(x.appendChild(S),o.status===`timeout`&&o.interrupted){let e=n(`p`,`persona-text-sm`);e.textContent=t,x.appendChild(e)}let w=o.toolType===`webmcp`||o.toolName.startsWith(`webmcp:`)?c(o.toolName):void 0,T=s?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...w?{displayTitle:w}:{},...o.reason?{reason:o.reason}:{}}),E=!o.toolName,D=T||(E?o.description:`The assistant wants to use “${w??d(o.toolName)}”.`),O=n(`p`,`persona-text-sm persona-mt-0.5 persona-text-persona-muted`);if(O.setAttribute(`data-approval-summary`,`true`),s?.descriptionColor&&(O.style.color=s.descriptionColor),O.textContent=D,x.appendChild(O),o.reason){let e=n(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-reason`,`true`),s?.reasonColor?e.style.color=s.reasonColor:s?.descriptionColor&&(e.style.color=s.descriptionColor);let t=n(`span`,`persona-font-medium`);t.textContent=`${s?.reasonLabel??`Agent's stated reason:`} `,e.appendChild(t),e.appendChild(document.createTextNode(o.reason)),x.appendChild(e)}let k=s?.detailsDisplay??`collapsed`,A=!!o.description&&!E,j=A||!!o.parameters;if(k!==`hidden`&&j){let t=p(e.id,i,r),c=n(`button`,`persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted`);c.type=`button`,c.setAttribute(`data-expand-header`,`true`),c.setAttribute(`data-bubble-type`,`approval`),s?.descriptionColor&&(c.style.color=s.descriptionColor);let l=n(`span`);l.setAttribute(`data-approval-details-label`,`true`);let u=n(`span`,`persona-inline-flex persona-items-center`);u.setAttribute(`data-approval-details-chevron`,`true`),c.append(l,u),m(c,t,r),x.appendChild(c);let d=n(`div`);if(d.setAttribute(`data-approval-details`,`true`),d.style.display=t?``:`none`,A){let e=n(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);s?.descriptionColor&&(e.style.color=s.descriptionColor),e.textContent=o.description,d.appendChild(e)}if(o.parameters){let e=n(`pre`,`persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary`);s?.parameterBackgroundColor&&(e.style.backgroundColor=s.parameterBackgroundColor),s?.parameterTextColor&&(e.style.color=s.parameterTextColor),e.style.fontSize=`0.75rem`,e.style.lineHeight=`1rem`,e.textContent=a(o.parameters),d.appendChild(e)}x.appendChild(d)}if(f){let e=n(`div`,`persona-flex persona-gap-2 persona-mt-2`);e.setAttribute(`data-approval-buttons`,`true`);let t=n(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer`);t.type=`button`,t.style.backgroundColor=s?.approveButtonColor??`var(--persona-approval-approve-bg)`,t.style.color=s?.approveButtonTextColor??`var(--persona-button-primary-fg)`,t.setAttribute(`data-approval-action`,`approve`);let r=u(l.ShieldCheck,14,s?.approveButtonTextColor??`var(--persona-button-primary-fg)`,2);r&&(r.style.marginRight=`4px`,t.appendChild(r));let i=document.createTextNode(s?.approveLabel??`Approve`);t.appendChild(i);let a=n(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer`);a.type=`button`,a.style.backgroundColor=s?.denyButtonColor??`transparent`,a.style.color=s?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,a.style.border=`1px solid ${s?.denyButtonTextColor?s.denyButtonTextColor:`var(--persona-palette-colors-error-200)`}`,a.setAttribute(`data-approval-action`,`deny`);let o=u(l.ShieldX,14,s?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,2);o&&(o.style.marginRight=`4px`,a.appendChild(o));let c=document.createTextNode(s?.denyLabel??`Deny`);a.appendChild(c),e.append(t,a),x.appendChild(e)}return g.append(_,x),h.appendChild(g),h};function _(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function v(e){let{anchor:t,content:n,placement:r=`bottom-start`,offset:i=6,matchAnchorWidth:a=!1,horizontalOffset:o,verticalOffset:s,zIndex:c=2147483e3,onOpen:l,onDismiss:u}=e,d=e.container??_(t),f=!1,p=null,m=()=>{if(!f)return;let e=t.getBoundingClientRect();n.style.position=`fixed`,a&&(n.style.minWidth=`${e.width}px`),o&&(n.style.maxWidth=`${e.width}px`);let c=n.getBoundingClientRect(),l=s?.()??null,u=l==null?e.top:e.top+l,d=r===`top-start`||r===`top-end`?u-i-c.height:e.bottom+i,p=r===`bottom-end`||r===`top-end`?e.right-c.width:e.left,m=o?.()??null;if(m!=null){let t=Math.max(e.left,e.right-c.width);p=Math.min(Math.max(e.left+m,e.left),t)}n.style.top=`${d}px`,n.style.left=`${p}px`},h=()=>{f&&(f=!1,p&&=(p(),null),n.remove())},g=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),d.appendChild(n),m();let e=(t.ownerDocument??document).defaultView??window,r=t.ownerDocument??document,i=()=>{t.isConnected?m():(h(),u?.(`anchor-removed`))},a=e=>{let r=typeof e.composedPath==`function`?e.composedPath():[];r.includes(n)||r.includes(t)||(h(),u?.(`outside`))},o=e.setTimeout(()=>{r.addEventListener(`pointerdown`,a,!0)},0);e.addEventListener(`scroll`,i,!0),e.addEventListener(`resize`,i),p=()=>{e.clearTimeout(o),r.removeEventListener(`pointerdown`,a,!0),e.removeEventListener(`scroll`,i,!0),e.removeEventListener(`resize`,i)},l?.()};return{get isOpen(){return f},open:g,close:h,toggle:()=>f?h():g(),reposition:m,destroy:h}}function y(e){return(typeof e.composedPath==`function`?e.composedPath():[]).some(e=>e instanceof HTMLElement&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable))}const b=()=>({keyHandlers:/* @__PURE__ */ new Map,popovers:/* @__PURE__ */ new Map,pendingOrder:[],latestPendingApprovalId:null}),x=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener(`keydown`,n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},S=(e,t)=>{x(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},C=e=>e?.approval===!1?void 0:e?.approval,w=(e,t,n)=>{let r=n?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},T=e=>{let t=n(`span`,`persona-approval-kbd`);return t.textContent=e,t},E=(e,t)=>{let r=n(`span`,`persona-approval-title`);t?.titleColor&&(r.style.color=t.titleColor);let i=e.toolType===`webmcp`||e.toolName.startsWith(`webmcp:`)?c(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??``,parameters:e.parameters,...i?{displayTitle:i}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let o=i??d(e.toolName),s=e.toolType&&e.toolType!==`webmcp`?e.toolType:null;r.append(`The assistant wants to use `);let l=document.createElement(`strong`);if(l.textContent=o,r.appendChild(l),s){r.append(` from `);let e=document.createElement(`strong`);e.textContent=s,r.appendChild(e)}return r},D=e=>{let i=n(`div`,`persona-approval-resolved`),a=u(l.Ban,15,`currentColor`,2);a&&i.appendChild(a);let o=n(`span`,`persona-approval-resolved-name`);o.textContent=e.toolName?d(e.toolName):`Tool`;let s=e.status===`timeout`&&e.interrupted?` approval expired. ${t}`:e.status===`timeout`?` timed out`:` denied`;return i.appendChild(r(`span`,{className:`persona-approval-resolved-text`},o,s)),i},O=(e,t,r,i,o,s,c,d,f=!1)=>{let p=n(`div`,`persona-approval-card persona-shadow-sm`);p.id=`bubble-${r.id}`,p.setAttribute(`data-message-id`,r.id),p.setAttribute(`data-bubble-type`,`approval`),o?.backgroundColor&&(p.style.background=o.backgroundColor),o?.borderColor&&(p.style.borderColor=o.borderColor),o?.shadow!==void 0&&(p.style.boxShadow=o.shadow.trim()===``?`none`:o.shadow);let m=o?.detailsDisplay??`collapsed`,h=!!i.description&&m!==`hidden`,g=i.parameters!=null&&m!==`hidden`&&!f,_=h||g,y=_&&w(r.id,t,o),b=o?.showDetailsLabel??`Show details`,x=o?.hideDetailsLabel??`Hide details`,C=n(`button`,`persona-approval-head`);C.type=`button`,_?(C.setAttribute(`data-action`,`toggle-params`),C.setAttribute(`aria-expanded`,y?`true`:`false`),C.setAttribute(`aria-label`,y?x:b)):C.setAttribute(`data-static`,`true`);let D=n(`span`,`persona-approval-logo`),O=u(l.ShieldCheck,16,`currentColor`,2);O&&D.appendChild(O),C.appendChild(D);let k=E(i,o);if(_){let e=n(`span`,`persona-approval-toggle`);e.setAttribute(`aria-hidden`,`true`);let t=u(l.ChevronDown,14,`currentColor`,2);t&&e.appendChild(t),k.append(` `),k.appendChild(e)}C.appendChild(k),p.appendChild(C);let A=n(`div`,`persona-approval-body`);if(_){let e=n(`div`,`persona-approval-details`);if(e.setAttribute(`data-role`,`params`),e.hidden=!y,h){let t=n(`p`,`persona-approval-desc`);o?.descriptionColor&&(t.style.color=o.descriptionColor),t.textContent=i.description,e.appendChild(t)}if(g){let t=n(`pre`,`persona-approval-params`);o?.parameterBackgroundColor&&(t.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(t.style.color=o.parameterTextColor),t.textContent=a(i.parameters),e.appendChild(t)}A.appendChild(e)}if(f){let e=n(`div`,`persona-approval-call`);e.setAttribute(`data-role`,`raw-call`);let t=n(`code`,`persona-approval-tool-name`);if(t.textContent=i.toolName,e.appendChild(t),i.parameters!=null){let t=n(`pre`,`persona-approval-params`);o?.parameterBackgroundColor&&(t.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(t.style.color=o.parameterTextColor),t.textContent=a(i.parameters),e.appendChild(t)}A.appendChild(e)}if(i.reason){let e=n(`p`,`persona-approval-reason`);o?.reasonColor?e.style.color=o.reasonColor:o?.descriptionColor&&(e.style.color=o.descriptionColor);let t=n(`span`,`persona-approval-reason-label`);t.textContent=`${o?.reasonLabel??`Agent's stated reason:`} `,e.append(t,document.createTextNode(i.reason)),A.appendChild(e)}let j=n(`div`,`persona-approval-actions`),M=null,N=e=>{o?.approveButtonColor&&(e.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(e.style.color=o.approveButtonTextColor)},P=n(`button`,`persona-approval-deny`);if(P.type=`button`,P.setAttribute(`data-action`,`deny`),o?.denyButtonColor&&(P.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(P.style.color=o.denyButtonTextColor),P.append(o?.denyLabel??`Deny`),d){let t=n(`div`,`persona-approval-split`),i=n(`button`,`persona-approval-primary`);i.type=`button`,i.setAttribute(`data-action`,`always`),N(i),i.append(o?.approveLabel??`Always allow`,T(`⏎`));let a=n(`button`,`persona-approval-caret`);a.type=`button`,a.setAttribute(`data-action`,`toggle-menu`),a.setAttribute(`aria-label`,`More options`),N(a);let c=u(l.ChevronDown,15,`currentColor`,2);c&&a.appendChild(c),t.append(i,a),j.append(t,P),P.append(T(`Esc`));let d=n(`div`,`persona-approval-menu`),f=n(`button`,`persona-approval-menu-item`);f.type=`button`,f.append(`Allow once`,T(`⌘⏎`)),d.appendChild(f),M=v({anchor:t,content:d,placement:`bottom-start`,matchAnchorWidth:!0}),e.popovers.set(r.id,M),f.addEventListener(`click`,()=>{S(e,r.id),s()})}else{let e=n(`button`,`persona-approval-primary persona-approval-primary--solo`);e.type=`button`,e.setAttribute(`data-action`,`allow`),N(e),e.append(o?.approveLabel??`Allow`),j.append(e,P)}return A.appendChild(j),p.appendChild(A),p.addEventListener(`click`,n=>{let i=n.target instanceof Element?n.target.closest(`[data-action]`):null;if(!i)return;let a=i.getAttribute(`data-action`);if(a===`toggle-params`){let e=p.querySelector(`[data-role="params"]`);if(e){let n=!!e.hidden;e.hidden=!n,C.setAttribute(`aria-expanded`,n?`true`:`false`),C.setAttribute(`aria-label`,n?x:b),t.set(r.id,n)}}else a===`toggle-menu`?M?.toggle():a===`always`?(S(e,r.id),s({remember:!0})):a===`allow`?(S(e,r.id),s()):a===`deny`&&(S(e,r.id),c())}),p},k=(e=/* @__PURE__ */ new Map)=>{let t=b();return{plugin:{id:`persona-built-in-approval`,renderApproval:({message:n,approve:r,deny:i,config:a})=>{let o=n?.approval;if(!o)return null;let s=C(a);if(o.status!==`pending`){if(S(t,n.id),o.status===`approved`){let e=document.createElement(`div`);return e.style.display=`none`,e}return D(o)}x(t,n.id);let c=!!a?.clientToken,l=s?.enableAlwaysAllow===!0,u=O(t,e,n,o,s,r,i,l,c);if(l){t.pendingOrder.includes(n.id)||t.pendingOrder.push(n.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let e=e=>{y(e)||n.id===t.latestPendingApprovalId&&(e.key===`Escape`||e.key===`Enter`)&&(e.preventDefault(),e.stopImmediatePropagation(),S(t,n.id),e.key===`Escape`?i():e.metaKey||e.ctrlKey?r():r({remember:!0}))};t.keyHandlers.set(n.id,e),document.addEventListener(`keydown`,e)}return u}},teardown:()=>{for(let e of[...t.keyHandlers.keys(),...t.popovers.keys()])S(t,e);t.latestPendingApprovalId=null}}};export{g as createApprovalBubble,k as createBuiltInApprovalPlugin,d as humanizeToolName,s as initApprovalUi,h as updateApprovalDetailsUI};
|
package/dist/artifacts-ui.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Hr as PersonaArtifactFileMeta, Rr as PersonaArtifactCustomAction, T as AgentWidgetConfig, qr as PersonaArtifactRecord } from "./types-
|
|
2
|
-
import { i as provideMarkdownParsers, s as ComponentRenderer } from "./markdown-parsers-loader-
|
|
1
|
+
import { Hr as PersonaArtifactFileMeta, Rr as PersonaArtifactCustomAction, T as AgentWidgetConfig, qr as PersonaArtifactRecord } from "./types-BuDirJkQ.cjs";
|
|
2
|
+
import { i as provideMarkdownParsers, s as ComponentRenderer } from "./markdown-parsers-loader-CeovcyYf.cjs";
|
|
3
3
|
import { IconNode } from "lucide";
|
|
4
4
|
//#region src/components/artifact-pane.d.ts
|
|
5
5
|
type ArtifactPaneApi = {
|
package/dist/artifacts-ui.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Hr as PersonaArtifactFileMeta, Rr as PersonaArtifactCustomAction, T as AgentWidgetConfig, qr as PersonaArtifactRecord } from "./types-
|
|
2
|
-
import { i as provideMarkdownParsers, s as ComponentRenderer } from "./markdown-parsers-loader-
|
|
1
|
+
import { Hr as PersonaArtifactFileMeta, Rr as PersonaArtifactCustomAction, T as AgentWidgetConfig, qr as PersonaArtifactRecord } from "./types-BuDirJkQ.js";
|
|
2
|
+
import { i as provideMarkdownParsers, s as ComponentRenderer } from "./markdown-parsers-loader-CeovcyYf.js";
|
|
3
3
|
import { IconNode } from "lucide";
|
|
4
4
|
//#region src/components/artifact-pane.d.ts
|
|
5
5
|
type ArtifactPaneApi = {
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{l as e,v as t}from"./chunk-DtmtfIkd.js";import{a as n,i as r,t as i}from"./chunk-CPdEltCR.js";import"./chunk-Bb41bKyp.js";async function a(e,t,n,r){let i={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(i,await e.getHeaders());let a={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:i,body:JSON.stringify({...n,...a})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:c}=await e.initSession(),l=await o(`/v1/client/approve`,{sessionId:c,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(l.status===404){let e=await l.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return o(s)}return l}async function o(e,t,r,i){let a=e.isClientTokenMode(),o=a?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,s,c=null;if(a){let t=await e.initSession();s=t.sessionId,t.durableRecovery?.enabled===!0&&(c=await e.readVisitorToken())}let l={"Content-Type":`application/json`,...c?{"X-Visitor-Token":c}:{},...e.headers};e.getHeaders&&Object.assign(l,await e.getHeaders());let u={executionId:t,toolOutputs:r,streamResponse:i?.streamResponse??!0,...i?.after?{after:i.after}:{}};if(s&&(u.sessionId=s,i?.assistantMessageId&&(u.assistantMessageId=i.assistantMessageId)),a&&s){let t=[...n(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:r,commit:a}=await e.sendWithClientToolsDiff(s,t,t=>{let n={...u,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(o,{method:`POST`,headers:l,body:JSON.stringify(n),signal:i?.signal})},{emptyMeansReplace:!0});return r.ok&&a(),r}return fetch(o,{method:`POST`,headers:l,body:JSON.stringify(u),signal:i?.signal})}function s(e){let t=e.toLowerCase(),n={"application/pdf":`pdf`,"application/json":`json`,"application/zip":`zip`,"text/plain":`txt`,"text/csv":`csv`,"text/markdown":`md`}[t];if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}const c=e=>e.startsWith(`{`)||e.startsWith(`[`)||e.startsWith(`<`);function l(t,n){if(!t)return n;let r=t.trim(),i=n.trim();if(r.length===0)return n;if(i.length===0)return t;let a=c(r);if(!c(i))return t;if(!a||i===r||i.startsWith(r))return n;let o=e(t);return e(n)!==null&&o===null?n:t}async function u(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function d(n,a,o,c,d){let f=a.getReader(),ee=new TextDecoder,p=``,m=Date.now(),te=0,h=()=>m+te++,g=e=>{let t=e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,n=e.toolCall?{...e.toolCall,chunks:e.toolCall.chunks?[...e.toolCall.chunks]:void 0}:void 0,r=e.tools?e.tools.map(e=>({...e,chunks:e.chunks?[...e.chunks]:void 0})):void 0;return{...e,reasoning:t,toolCall:n,tools:r}},ne=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},_=e=>{ne(e)&&o({type:`message`,message:g(e)})},v=null,y=null,b={current:null},re={current:null},x=null,S=``,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Map,T=/* @__PURE__ */ new Map,E=/* @__PURE__ */ new Map,D=/* @__PURE__ */ new Map,O=c,k=!1,A=()=>{if(v)return v;let e,t=``,n=x;return!k&&O?(e=O,k=!0,t=d??``):e=O&&n?`${O}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:h()},_(v),v},j=e=>{let t=E.get(e);if(t)return t;let n={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,sequence:h(),reasoning:{id:e,status:`streaming`,chunks:[]}};return E.set(e,n),_(n),n},M=/* @__PURE__ */ new Set,N=/* @__PURE__ */ new Map,P=/* @__PURE__ */ new Set,F=/* @__PURE__ */ new Map,I=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},L=e=>{let t=D.get(e);if(t)return t;let n={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,sequence:h(),toolCall:{id:e,status:`pending`}};return D.set(e,n),_(n),n},R=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(!Number.isNaN(t)&&Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},z=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},B=/* @__PURE__ */ new Map,V=/* @__PURE__ */ new Map,ie=(t,n)=>{let r=z(n),i=l(V.get(t.id),r);t.rawContent=i;let a=B.get(t.id),o=e=>{let n=t.content??``;e.trim()!==``&&(n.trim().length===0||e.startsWith(n)||e.trimStart().startsWith(n.trim()))&&(t.content=e)},s=()=>{if(a){let e=a.close?.();e instanceof Promise&&e.catch(()=>{})}B.delete(t.id),V.delete(t.id),t.streaming=!1,_(t)};if(!a){o(r),s();return}let c=e(i);if(c!==null&&c.trim()!==``){o(c),s();return}let u=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let n=a.getExtractedText();return n!==null&&n.trim()!==``?n:r},d;try{d=a.processChunk(i)}catch{o(r),s();return}d instanceof Promise?d.then(e=>{o(u(e)),s()}).catch(()=>{o(r),s()}):(o(u(d)),s())},H=null,U=(e,t,r,i)=>{e.rawContent=t,B.has(e.id)||B.set(e.id,n.createStreamParser());let a=B.get(e.id),o=t.trim().startsWith(`{`)||t.trim().startsWith(`[`);if(o&&V.set(e.id,t),a.__isPlainTextParser===!0){e.content=i===void 0?e.content+r:t,V.delete(e.id),B.delete(e.id),e.rawContent=void 0,_(e);return}let s=a.processChunk(t);if(s instanceof Promise)s.then(n=>{let a=typeof n==`string`?n:n?.text??null;a!==null&&a.trim()!==``?(e.content=a,_(e)):!o&&!t.trim().startsWith(`<`)&&(e.content=i===void 0?e.content+r:t,V.delete(e.id),B.delete(e.id),e.rawContent=void 0,_(e))}).catch(()=>{e.content=i===void 0?e.content+r:t,V.delete(e.id),B.delete(e.id),e.rawContent=void 0,_(e)});else{let n=typeof s==`string`?s:s?.text??null;n!==null&&n.trim()!==``?(e.content=n,_(e)):!o&&!t.trim().startsWith(`<`)&&(e.content=i===void 0?e.content+r:t,V.delete(e.id),B.delete(e.id),e.rawContent=void 0,_(e))}},W=(t,n)=>{let r=n??t.content;if(r==null||r===``){t.streaming=!1,_(t);return}let i=V.get(t.id)??z(r);t.rawContent=i;let a=B.get(t.id),o=null,s=!1;if(a&&(o=a.getExtractedText(),o===null&&(o=e(i)),o===null)){let e=a.processChunk(i);e instanceof Promise?(s=!0,e.then(e=>{let n=typeof e==`string`?e:e?.text??null;n!==null&&(t.content=n,t.streaming=!1,B.delete(t.id),V.delete(t.id),_(t))}).catch(()=>{})):o=typeof e==`string`?e:e?.text??null}if(!s){o!==null&&o.trim()!==``?t.content=o:V.has(t.id)||(t.content=z(r));let e=B.get(t.id);if(e){let n=e.close?.();n instanceof Promise&&n.catch(()=>{}),B.delete(t.id)}V.delete(t.id),t.streaming=!1,_(t)}},G=(e,t,n)=>{let r=w.get(e);if(r)return r;let i={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:h(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t}};return w.set(e,i),_(i),i},K=[],q,J=/* @__PURE__ */ new Map,Y=0,X=`agent`,Z=!1,Q=null,$=null,ae=n.config().iterationDisplay??`separate`;for(q=()=>{for(let e=0;e<K.length;e++){let a=K[e];if(!Z&&X!==`flow`&&typeof a.stepType==`string`&&(X=`flow`),a.type===`reasoning_start`){let e=typeof a.id==`string`?a.id:null,t=typeof a.parentToolCallId==`string`&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){C.set(e,t),G(e,t,`reasoning`);continue}let n=a.id,r=j(n);r.reasoning=r.reasoning??{id:n,status:`streaming`,chunks:[]},r.reasoning.startedAt=r.reasoning.startedAt??Date.now(),r.reasoning.completedAt=void 0,r.reasoning.durationMs=void 0,(a.scope===`loop`||a.scope===`turn`)&&(r.reasoning.scope=a.scope),r.streaming=!0,r.reasoning.status=`streaming`,_(r)}else if(a.type===`reasoning_delta`){let e=typeof a.id==`string`?a.id:null;if(e&&C.has(e)&&w.has(e)){let t=w.get(e),n=a.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),_(t));continue}let t=a.id,n=j(t);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),a.delta&&n.reasoning.chunks.push(a.delta),n.reasoning.status=`streaming`,n.streaming=!0,_(n)}else if(a.type===`reasoning_complete`){let e=typeof a.id==`string`?a.id:null;if(e&&C.has(e)&&w.has(e)){let t=w.get(e);if(t.reasoning){let e=typeof a.text==`string`?a.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,_(t)}C.delete(e),w.delete(e);continue}let t=a.id,n=typeof a.text==`string`?a.text:``;!E.get(t)&&(n||a.scope===`loop`)&&j(t);let r=E.get(t);if(r?.reasoning){(a.scope===`loop`||a.scope===`turn`)&&(r.reasoning.scope=a.scope),n&&r.reasoning.chunks.length===0&&r.reasoning.chunks.push(n),r.reasoning.status=`complete`,r.reasoning.completedAt=Date.now();let e=r.reasoning.startedAt??Date.now();r.reasoning.durationMs=Math.max(0,(r.reasoning.completedAt??Date.now())-e),r.streaming=!1,_(r)}}else if(a.type===`tool_start`){v&&=(v.streaming=!1,_(v),null),typeof a.iteration==`number`&&(Y=a.iteration);let e=a.toolCallId,t=a.toolName;if(I(t)){M.add(e);continue}let n=L(e),r=n.toolCall??{id:e,status:`pending`};r.name=t??r.name,r.status=`running`,r.success=void 0,r.error=void 0,r.duration=void 0,a.parameters!==void 0&&(r.args=a.parameters),r.startedAt=r.startedAt??R(a.startedAt),r.completedAt=void 0,r.durationMs=void 0,n.toolCall=r,n.streaming=!0,a.executionId&&(n.agentMetadata={executionId:a.executionId,iteration:a.iteration}),_(n)}else if(a.type===`tool_output_delta`){let e=a.toolCallId;if(M.has(e))continue;let t=L(e),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let r=a.delta;r&&(n.chunks=n.chunks??[],n.chunks.push(String(r))),n.status=`running`,t.toolCall=n,t.streaming=!0,a.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:a.executionId,iteration:Y}),_(t)}else if(a.type===`tool_complete`){let e=a.toolCallId;if(M.has(e)){M.delete(e);continue}let t=L(e),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,a.result!==void 0&&(n.result=a.result),n.name=a.toolName??n.name,n.success=a.success,n.error=a.error,n.completedAt=Date.now();let r=a.executionTime;if(typeof r==`number`)n.durationMs=r,n.duration=r;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,a.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:a.executionId,iteration:a.iteration??Y}),_(t)}else if(a.type===`await`&&a.toolName){let e=typeof a.toolCallId==`string`&&a.toolCallId.length>0?a.toolCallId:void 0,n=e??a.toolId??`local-${h()}`,r=L(n),i=a.toolName,o=a.origin===`webmcp`&&!t(i)?`webmcp:${i}`:i,s=t(o),c=r.toolCall??{id:n,status:`pending`};c.name=o,c.args=a.parameters,c.status=s?`running`:`complete`,c.chunks=c.chunks??[],c.startedAt=c.startedAt??R(a.awaitedAt),s?(c.completedAt=void 0,c.duration=void 0,c.durationMs=void 0):c.completedAt=c.completedAt??c.startedAt,r.toolCall=c,r.streaming=!1,r.agentMetadata={...r.agentMetadata,executionId:a.executionId??r.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},_(r)}else if(a.type===`text_start`){let e=typeof a.id==`string`?a.id:null,t=typeof a.parentToolCallId==`string`&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){C.set(e,t);continue}let n=v;n&&(X===`flow`?(W(n),H=n):(n.streaming=!1,_(n)),v=null),x=typeof a.id==`string`?a.id:x,S=``}else if(a.type===`text_delta`){let e=typeof a.id==`string`?a.id:null,t=e?C.get(e):void 0;if(e&&t){let n=typeof a.delta==`string`?a.delta:``,r=(T.get(e)??``)+n;if(T.set(e,r),r.trim()===``)continue;let i=G(e,t);i.agentMetadata={...i.agentMetadata,executionId:a.executionId,parentToolId:t},U(i,r,n,void 0);continue}if(x=typeof a.id==`string`?a.id:x,X===`flow`){let e=typeof a.delta==`string`?a.delta:``;if(S+=e,S.trim()===``)continue;let t=A();t.agentMetadata={executionId:a.executionId,iteration:Y},U(t,S,e,void 0),y=t;continue}let n=typeof a.delta==`string`?a.delta:``;S+=n;let r=A();r.agentMetadata={executionId:a.executionId,iteration:Y,turnId:Q??void 0,agentName:$?.agentName},U(r,S,n,void 0),y=r}else if(a.type===`text_complete`){let e=typeof a.id==`string`?a.id:null;if(e&&C.has(e)){let t=w.get(e);t&&W(t),C.delete(e),T.delete(e),w.delete(e);continue}let t=v;t&&(X===`flow`?(W(t),H=t):((t.content??``)===``&&typeof a.text==`string`&&(t.content=a.text),t.streaming=!1,_(t)),v=null),x=null,S=``}else if(a.type===`step_complete`){if(a.stepType===`tool`)continue;if(a.success===!1){let e=a.error||`Step failed`;o({type:`error`,error:Error(e)});let t=v;t&&t.streaming&&(t.streaming=!1,_(t)),o({type:`status`,status:`idle`});continue}{let e=H;H=null;let t=a.stopReason,n=(a.result&&typeof a.result==`object`?a.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(B.delete(e.id),V.delete(e.id),e.streaming=!1,_(e)):ie(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=A();t&&(r.stopReason=t),e?W(r,n):(r.streaming=!1,_(r))}}continue}}else if(a.type===`execution_start`)X=a.kind===`flow`?`flow`:`agent`,Z=!0,X===`agent`&&($={executionId:a.executionId,agentId:a.agentId??`virtual`,agentName:a.agentName??``});else if(a.type===`turn_start`){let e=typeof a.iteration==`number`?a.iteration:Y;if(e!==Y){if(ae===`separate`&&e>1){let e=v;e&&(e.streaming=!1,_(e),v=null)}Y=e}Q=typeof a.id==`string`?a.id:null,y=null}else if(a.type===`tool_input_delta`){let e=a.toolCallId;if(e){let t=D.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(a.delta??``),_(t))}}else if(a.type===`tool_input_complete`){if(M.has(a.toolCallId))continue;let e=L(a.toolCallId),t=e.toolCall;t.args=a.parameters,t.name=a.toolName??t.name,_(e)}else if(a.type===`turn_complete`){let e=a.stopReason,t=v??y;if(e&&t!==null){let n=a.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,_(t))}Q===a.id&&(Q=null)}else if(a.type===`media_start`){let e=String(a.id);J.set(e,{mediaType:typeof a.mediaType==`string`?a.mediaType:void 0,toolCallId:a.toolCallId,parts:[]})}else if(a.type===`media_delta`){let e=J.get(String(a.id));e&&typeof a.delta==`string`&&e.parts.push(a.delta)}else if(a.type===`media_complete`){let e=String(a.id),t=J.get(e);J.delete(e);let n=(typeof a.mediaType==`string`?a.mediaType:void 0)??t?.mediaType??`application/octet-stream`,r=typeof a.data==`string`?a.data:void 0,i=typeof a.url==`string`?a.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(r)o={type:`media`,data:r,mediaType:n};else if(i){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:i,mediaType:n}}let c=a.toolCallId??t?.toolCallId,l=o?[o]:[],u=[];for(let e of l){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))u.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))u.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))u.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;u.push({type:`file`,data:i,mimeType:e,filename:s(e)})}}}if(u.length>0){let e=h(),t=c,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:u,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:a.executionId,iteration:Y}};_(n);let r=v;r&&(r.streaming=!1,_(r)),v=null,b.current=null}}else if(a.type===`execution_complete`){let e=v;e&&(a.kind===`flow`&&e.streaming!==!1?W(e):(e.streaming=!1,_(e)),v=null),x=null,S=``,H=null,o({type:`status`,status:`idle`,terminal:!0})}else if(a.type===`execution_error`){let e=typeof a.error==`string`?a.error:a.error?.message??`Execution error`;o({type:`error`,error:Error(e)})}else if(a.type!==`ping`){if(a.type===`approval_start`){let e=a.approvalId??`approval-${h()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:h(),approval:{id:e,status:`pending`,agentId:$?.agentId??`virtual`,executionId:a.executionId??$?.executionId??``,toolName:a.toolName??``,toolType:a.toolType,description:a.description??`Execute ${a.toolName??`tool`}`,...typeof a.reason==`string`&&a.reason?{reason:a.reason}:{},parameters:a.parameters,...typeof a.toolCallId==`string`&&a.toolCallId?{toolCallId:a.toolCallId}:{}}};_(t)}else if(a.type===`approval_complete`){let e=a.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:h(),approval:{id:e,status:a.decision??`approved`,agentId:$?.agentId??`virtual`,executionId:a.executionId??$?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};_(t)}}else if(a.type===`artifact_start`||a.type===`artifact_delta`||a.type===`artifact_update`||a.type===`artifact_complete`){if(a.type===`artifact_start`){let e=a.artifactType,t=String(a.id),s=typeof a.title==`string`?a.title:void 0,c=a.file,l;if(c&&typeof c==`object`&&!Array.isArray(c)&&typeof c.path==`string`&&typeof c.mimeType==`string`&&(l={path:c.path,mimeType:c.mimeType,...typeof c.language==`string`?{language:c.language}:{}}),o({type:`artifact_start`,id:t,artifactType:e,title:s,component:typeof a.component==`string`?a.component:void 0,...l?{file:l}:{}}),F.set(t,{markdown:``,title:s,file:l}),!P.has(t)){P.add(t);let o=r(n.config().features?.artifacts,{artifactType:e,...l?{file:l}:{}}),c=typeof a.component==`string`?a.component:void 0,u={id:`artifact-ref-${t}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:h(),rawContent:i(o,{artifactId:t,title:s,artifactType:e,status:`streaming`,...l?{file:l}:{},...c?{component:c}:{}})};N.set(t,u),_(u)}}else if(a.type===`artifact_delta`){let e=String(a.id),t=typeof a.delta==`string`?a.delta:String(a.delta??``);o({type:`artifact_delta`,id:e,artDelta:t});let n=F.get(e);n&&(n.markdown+=t)}else if(a.type===`artifact_update`){let e=a.props&&typeof a.props==`object`&&!Array.isArray(a.props)?a.props:{};o({type:`artifact_update`,id:String(a.id),props:e,component:typeof a.component==`string`?a.component:void 0});let t=F.get(String(a.id));t&&(t.props={...t.props??{},...e})}else if(a.type===`artifact_complete`){let e=String(a.id);o({type:`artifact_complete`,id:e});let t=N.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=F.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}F.delete(e),_(t),N.delete(e)}}}else if(a.type===`error`&&a.recoverable===!1&&a.error!=null&&a.error!==``){let e=typeof a.error==`string`?a.error:a.error?.message==null?`Execution error`:String(a.error.message);o({type:`error`,error:Error(e)});let t=v;t&&t.streaming&&(t.streaming=!1,_(t)),o({type:`status`,status:`idle`})}}}K.length=0};;){let{done:e,value:t}=await f.read();if(e)break;p+=ee.decode(t,{stream:!0});let r=p.split(`
|
|
2
|
+
|
|
3
|
+
`);p=r.pop()??``;for(let e of r){let t=e.split(`
|
|
4
|
+
`),r=`message`,i=``,a=null;for(let e of t)e.startsWith(`event:`)?r=e.replace(`event:`,``).trim():e.startsWith(`data:`)?i+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(a=e.slice(3).trim());let s=()=>{a!==null&&a!==``&&o({type:`cursor`,id:a})};if(!i){s();continue}let c;try{c=JSON.parse(i)}catch(e){o({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let l=typeof c==`object`&&c&&!Array.isArray(c)?c:null,d=r===`message`?typeof l?.type==`string`?l.type:`message`:r;if(n.onSSEEvent?.(d,c),n.parseSSEEvent){b.current=v;let e=await u(n,c,o,b,_,h,re);if(b.current&&b.current!==v&&(v=b.current),e){s();continue}}l&&(K.push({...l,type:d}),q()),s()}}q()}export{l as preferFinalStructuredContent,a as resolveApproval,o as resumeFlow,d as streamResponse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-Csks3Qw1.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
|
+
import{d as e,h as t}from"./chunk-DtmtfIkd.js";import{t as n}from"./chunk-D5B629Mj.js";import{t as r}from"./chunk-BtTP1Wgi.js";import{r as i,t as a}from"./chunk-D5BxWOFB.js";import{r as o,t as s}from"./chunk-CQw6A6rt.js";import{Ban as c,ChevronDown as l,ChevronUp as u,ShieldAlert as d,ShieldCheck as f,ShieldX as p}from"lucide";let m=()=>void 0;const h=e=>{m=e.webMcpToolTitle},g=e=>m(e),_=e=>{let n=(e.startsWith(`webmcp:`)?e.slice(t.length):e).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(` `).toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},v=e=>e?.approval===!1?void 0:e?.approval,y=(e,t,n)=>{let r=v(n)?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},b=(e,t,n)=>{let i=v(n);e.setAttribute(`aria-expanded`,t?`true`:`false`);let a=e.querySelector(`[data-approval-details-label]`);a&&(a.textContent=t?i?.hideDetailsLabel??`Hide details`:i?.showDetailsLabel??`Show details`);let o=e.querySelector(`[data-approval-details-chevron]`);if(o){o.innerHTML=``;let e=r(t?u:l,14,`currentColor`,2);e&&o.appendChild(e)}},x=(e,t,n,r=/* @__PURE__ */ new Map)=>{let i=t.querySelector(`button[data-bubble-type="approval"]`),a=t.querySelector(`[data-approval-details]`);if(!i||!a)return;let o=y(e,r,n);b(i,o,n),a.style.display=o?``:`none`},S=(t,i,o=/* @__PURE__ */ new Map)=>{let s=t.approval,c=i?.approval===!1?void 0:i?.approval,l=s?.status===`pending`,u=a(`div`,[`persona-approval-bubble`,`persona-w-full`,`persona-rounded-2xl`,`persona-border`,`persona-shadow-sm`,`persona-overflow-hidden`].join(` `));if(u.id=`bubble-${t.id}`,u.setAttribute(`data-message-id`,t.id),u.style.backgroundColor=c?.backgroundColor??`var(--persona-approval-bg)`,u.style.borderColor=c?.borderColor??`var(--persona-approval-border)`,u.style.boxShadow=c?.shadow===void 0?`var(--persona-approval-shadow)`:c.shadow.trim()===``?`none`:c.shadow,!s)return u;let m=a(`div`,`persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3`),h=a(`div`,`persona-flex-shrink-0 persona-mt-0.5`);h.setAttribute(`data-approval-icon`,`true`);let v=s.status===`denied`?p:s.status===`timeout`?d:f,x=s.status===`approved`?`var(--persona-feedback-success, var(--persona-palette-colors-success-600))`:s.status===`denied`?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:s.status===`timeout`?`var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))`:c?.titleColor??`currentColor`,S=r(v,20,x,2);S&&h.appendChild(S);let C=a(`div`,`persona-flex-1 persona-min-w-0`),w=a(`div`,`persona-flex persona-items-center persona-gap-2`),T=a(`span`,`persona-text-sm persona-font-medium persona-text-persona-primary`);if(c?.titleColor&&(T.style.color=c.titleColor),T.textContent=c?.title??`Approval Required`,w.appendChild(T),!l){let e=a(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`);e.setAttribute(`data-approval-status`,s.status),s.status===`approved`?(e.style.backgroundColor=`var(--persona-palette-colors-success-100)`,e.style.color=`var(--persona-palette-colors-success-700)`,e.textContent=`Approved`):s.status===`denied`?(e.style.backgroundColor=`var(--persona-palette-colors-error-100)`,e.style.color=`var(--persona-palette-colors-error-700)`,e.textContent=`Denied`):s.status===`timeout`&&(e.style.backgroundColor=`var(--persona-palette-colors-warning-100)`,e.style.color=`var(--persona-palette-colors-warning-700)`,e.textContent=s.status===`timeout`&&s.interrupted?`Interrupted`:`Timeout`),w.appendChild(e)}if(C.appendChild(w),s.status===`timeout`&&s.interrupted){let e=a(`p`,`persona-text-sm`);e.textContent=n,C.appendChild(e)}let E=s.toolType===`webmcp`||s.toolName.startsWith(`webmcp:`)?g(s.toolName):void 0,D=c?.formatDescription?.({toolName:s.toolName,toolType:s.toolType,description:s.description,parameters:s.parameters,...E?{displayTitle:E}:{},...s.reason?{reason:s.reason}:{}}),O=!s.toolName,k=D||(O?s.description:`The assistant wants to use “${E??_(s.toolName)}”.`),A=a(`p`,`persona-text-sm persona-mt-0.5 persona-text-persona-muted`);if(A.setAttribute(`data-approval-summary`,`true`),c?.descriptionColor&&(A.style.color=c.descriptionColor),A.textContent=k,C.appendChild(A),s.reason){let e=a(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-reason`,`true`),c?.reasonColor?e.style.color=c.reasonColor:c?.descriptionColor&&(e.style.color=c.descriptionColor);let t=a(`span`,`persona-font-medium`);t.textContent=`${c?.reasonLabel??`Agent's stated reason:`} `,e.appendChild(t),e.appendChild(document.createTextNode(s.reason)),C.appendChild(e)}let j=c?.detailsDisplay??`collapsed`,M=!!s.description&&!O,N=M||!!s.parameters;if(j!==`hidden`&&N){let n=y(t.id,o,i),r=a(`button`,`persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted`);r.type=`button`,r.setAttribute(`data-expand-header`,`true`),r.setAttribute(`data-bubble-type`,`approval`),c?.descriptionColor&&(r.style.color=c.descriptionColor);let l=a(`span`);l.setAttribute(`data-approval-details-label`,`true`);let u=a(`span`,`persona-inline-flex persona-items-center`);u.setAttribute(`data-approval-details-chevron`,`true`),r.append(l,u),b(r,n,i),C.appendChild(r);let d=a(`div`);if(d.setAttribute(`data-approval-details`,`true`),d.style.display=n?``:`none`,M){let e=a(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);c?.descriptionColor&&(e.style.color=c.descriptionColor),e.textContent=s.description,d.appendChild(e)}if(s.parameters){let t=a(`pre`,`persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary`);c?.parameterBackgroundColor&&(t.style.backgroundColor=c.parameterBackgroundColor),c?.parameterTextColor&&(t.style.color=c.parameterTextColor),t.style.fontSize=`0.75rem`,t.style.lineHeight=`1rem`,t.textContent=e(s.parameters),d.appendChild(t)}C.appendChild(d)}if(l){let e=a(`div`,`persona-flex persona-gap-2 persona-mt-2`);e.setAttribute(`data-approval-buttons`,`true`);let t=a(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer`);t.type=`button`,t.style.backgroundColor=c?.approveButtonColor??`var(--persona-approval-approve-bg)`,t.style.color=c?.approveButtonTextColor??`var(--persona-button-primary-fg)`,t.setAttribute(`data-approval-action`,`approve`);let n=r(f,14,c?.approveButtonTextColor??`var(--persona-button-primary-fg)`,2);n&&(n.style.marginRight=`4px`,t.appendChild(n));let i=document.createTextNode(c?.approveLabel??`Approve`);t.appendChild(i);let o=a(`button`,`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer`);o.type=`button`,o.style.backgroundColor=c?.denyButtonColor??`transparent`,o.style.color=c?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,o.style.border=`1px solid ${c?.denyButtonTextColor?c.denyButtonTextColor:`var(--persona-palette-colors-error-200)`}`,o.setAttribute(`data-approval-action`,`deny`);let s=r(p,14,c?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,2);s&&(s.style.marginRight=`4px`,o.appendChild(s));let l=document.createTextNode(c?.denyLabel??`Deny`);o.appendChild(l),e.append(t,o),C.appendChild(e)}return m.append(h,C),u.appendChild(m),u},C=()=>({keyHandlers:/* @__PURE__ */ new Map,popovers:/* @__PURE__ */ new Map,pendingOrder:[],latestPendingApprovalId:null}),w=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener(`keydown`,n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},T=(e,t)=>{w(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},E=e=>e?.approval===!1?void 0:e?.approval,D=(e,t,n)=>{let r=n?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},O=e=>{let t=a(`span`,`persona-approval-kbd`);return t.textContent=e,t},k=(e,t)=>{let n=a(`span`,`persona-approval-title`);t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType===`webmcp`||e.toolName.startsWith(`webmcp:`)?g(e.toolName):void 0,i=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??``,parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(i)return n.textContent=i,n;let o=r??_(e.toolName),s=e.toolType&&e.toolType!==`webmcp`?e.toolType:null;n.append(`The assistant wants to use `);let c=document.createElement(`strong`);if(c.textContent=o,n.appendChild(c),s){n.append(` from `);let e=document.createElement(`strong`);e.textContent=s,n.appendChild(e)}return n},A=e=>{let t=a(`div`,`persona-approval-resolved`),o=r(c,15,`currentColor`,2);o&&t.appendChild(o);let s=a(`span`,`persona-approval-resolved-name`);s.textContent=e.toolName?_(e.toolName):`Tool`;let l=e.status===`timeout`&&e.interrupted?` approval expired. ${n}`:e.status===`timeout`?` timed out`:` denied`;return t.appendChild(i(`span`,{className:`persona-approval-resolved-text`},s,l)),t},j=(t,n,i,o,c,u,d,p,m=!1)=>{let h=a(`div`,`persona-approval-card persona-shadow-sm`);h.id=`bubble-${i.id}`,h.setAttribute(`data-message-id`,i.id),h.setAttribute(`data-bubble-type`,`approval`),c?.backgroundColor&&(h.style.background=c.backgroundColor),c?.borderColor&&(h.style.borderColor=c.borderColor),c?.shadow!==void 0&&(h.style.boxShadow=c.shadow.trim()===``?`none`:c.shadow);let g=c?.detailsDisplay??`collapsed`,_=!!o.description&&g!==`hidden`,v=o.parameters!=null&&g!==`hidden`&&!m,y=_||v,b=y&&D(i.id,n,c),x=c?.showDetailsLabel??`Show details`,S=c?.hideDetailsLabel??`Hide details`,C=a(`button`,`persona-approval-head`);C.type=`button`,y?(C.setAttribute(`data-action`,`toggle-params`),C.setAttribute(`aria-expanded`,b?`true`:`false`),C.setAttribute(`aria-label`,b?S:x)):C.setAttribute(`data-static`,`true`);let w=a(`span`,`persona-approval-logo`),E=r(f,16,`currentColor`,2);E&&w.appendChild(E),C.appendChild(w);let A=k(o,c);if(y){let e=a(`span`,`persona-approval-toggle`);e.setAttribute(`aria-hidden`,`true`);let t=r(l,14,`currentColor`,2);t&&e.appendChild(t),A.append(` `),A.appendChild(e)}C.appendChild(A),h.appendChild(C);let j=a(`div`,`persona-approval-body`);if(y){let t=a(`div`,`persona-approval-details`);if(t.setAttribute(`data-role`,`params`),t.hidden=!b,_){let e=a(`p`,`persona-approval-desc`);c?.descriptionColor&&(e.style.color=c.descriptionColor),e.textContent=o.description,t.appendChild(e)}if(v){let n=a(`pre`,`persona-approval-params`);c?.parameterBackgroundColor&&(n.style.background=c.parameterBackgroundColor),c?.parameterTextColor&&(n.style.color=c.parameterTextColor),n.textContent=e(o.parameters),t.appendChild(n)}j.appendChild(t)}if(m){let t=a(`div`,`persona-approval-call`);t.setAttribute(`data-role`,`raw-call`);let n=a(`code`,`persona-approval-tool-name`);if(n.textContent=o.toolName,t.appendChild(n),o.parameters!=null){let n=a(`pre`,`persona-approval-params`);c?.parameterBackgroundColor&&(n.style.background=c.parameterBackgroundColor),c?.parameterTextColor&&(n.style.color=c.parameterTextColor),n.textContent=e(o.parameters),t.appendChild(n)}j.appendChild(t)}if(o.reason){let e=a(`p`,`persona-approval-reason`);c?.reasonColor?e.style.color=c.reasonColor:c?.descriptionColor&&(e.style.color=c.descriptionColor);let t=a(`span`,`persona-approval-reason-label`);t.textContent=`${c?.reasonLabel??`Agent's stated reason:`} `,e.append(t,document.createTextNode(o.reason)),j.appendChild(e)}let M=a(`div`,`persona-approval-actions`),N=null,P=e=>{c?.approveButtonColor&&(e.style.background=c.approveButtonColor),c?.approveButtonTextColor&&(e.style.color=c.approveButtonTextColor)},F=a(`button`,`persona-approval-deny`);if(F.type=`button`,F.setAttribute(`data-action`,`deny`),c?.denyButtonColor&&(F.style.background=c.denyButtonColor),c?.denyButtonTextColor&&(F.style.color=c.denyButtonTextColor),F.append(c?.denyLabel??`Deny`),p){let e=a(`div`,`persona-approval-split`),n=a(`button`,`persona-approval-primary`);n.type=`button`,n.setAttribute(`data-action`,`always`),P(n),n.append(c?.approveLabel??`Always allow`,O(`⏎`));let o=a(`button`,`persona-approval-caret`);o.type=`button`,o.setAttribute(`data-action`,`toggle-menu`),o.setAttribute(`aria-label`,`More options`),P(o);let d=r(l,15,`currentColor`,2);d&&o.appendChild(d),e.append(n,o),M.append(e,F),F.append(O(`Esc`));let f=a(`div`,`persona-approval-menu`),p=a(`button`,`persona-approval-menu-item`);p.type=`button`,p.append(`Allow once`,O(`⌘⏎`)),f.appendChild(p),N=s({anchor:e,content:f,placement:`bottom-start`,matchAnchorWidth:!0}),t.popovers.set(i.id,N),p.addEventListener(`click`,()=>{T(t,i.id),u()})}else{let e=a(`button`,`persona-approval-primary persona-approval-primary--solo`);e.type=`button`,e.setAttribute(`data-action`,`allow`),P(e),e.append(c?.approveLabel??`Allow`),M.append(e,F)}return j.appendChild(M),h.appendChild(j),h.addEventListener(`click`,e=>{let r=e.target instanceof Element?e.target.closest(`[data-action]`):null;if(!r)return;let a=r.getAttribute(`data-action`);if(a===`toggle-params`){let e=h.querySelector(`[data-role="params"]`);if(e){let t=!!e.hidden;e.hidden=!t,C.setAttribute(`aria-expanded`,t?`true`:`false`),C.setAttribute(`aria-label`,t?S:x),n.set(i.id,t)}}else a===`toggle-menu`?N?.toggle():a===`always`?(T(t,i.id),u({remember:!0})):a===`allow`?(T(t,i.id),u()):a===`deny`&&(T(t,i.id),d())}),h},M=(e=/* @__PURE__ */ new Map)=>{let t=C();return{plugin:{id:`persona-built-in-approval`,renderApproval:({message:n,approve:r,deny:i,config:a})=>{let s=n?.approval;if(!s)return null;let c=E(a);if(s.status!==`pending`){if(T(t,n.id),s.status===`approved`){let e=document.createElement(`div`);return e.style.display=`none`,e}return A(s)}w(t,n.id);let l=!!a?.clientToken,u=c?.enableAlwaysAllow===!0,d=j(t,e,n,s,c,r,i,u,l);if(u){t.pendingOrder.includes(n.id)||t.pendingOrder.push(n.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let e=e=>{o(e)||n.id===t.latestPendingApprovalId&&(e.key===`Escape`||e.key===`Enter`)&&(e.preventDefault(),e.stopImmediatePropagation(),T(t,n.id),e.key===`Escape`?i():e.metaKey||e.ctrlKey?r():r({remember:!0}))};t.keyHandlers.set(n.id,e),document.addEventListener(`keydown`,e)}return d}},teardown:()=>{for(let e of[...t.keyHandlers.keys(),...t.popovers.keys()])T(t,e);t.latestPendingApprovalId=null}}};export{S as createApprovalBubble,M as createBuiltInApprovalPlugin,_ as humanizeToolName,h as initApprovalUi,x as updateApprovalDetailsUI};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function t(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function n(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}export{n,e as r,t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=`4.29.1`;export{e as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v as e}from"./chunk-DtmtfIkd.js";const t=`The chat restarted and this browser tool was interrupted. Request a fresh proposal to try again.`;function n(e){return e.toolType===`webmcp`&&!e.executionId}function r(r){let i=r.approval,a=i?.status===`pending`&&n(i),o=!1,s=n=>!n.name||!e(n.name)||(o=!0,!(n.status!==`complete`||r.agentMetadata?.awaitingLocalTool===!0&&n.result===void 0&&n.success===void 0))?n:{...n,status:`complete`,interrupted:!0,success:!1,error:t,approvalStatus:n.approvalStatus===`pending`?`timeout`:n.approvalStatus,startedAt:n.completedAt===void 0?void 0:n.startedAt},c=r.toolCall?s(r.toolCall):void 0,l=r.tools?.map(s);return{...r,streaming:o||a?!1:r.streaming,...a?{approval:{...i,status:`timeout`,interrupted:!0}}:{},...c?{toolCall:c}:{},...l?{tools:l}:{},...o&&r.agentMetadata?.awaitingLocalTool?{agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1}}:{}}}export{n,r,t};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{t as e}from"./chunk-Csks3Qw1.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
|
+
`)}`]:[];return n&&a.push(n),a.join(`
|
|
3
|
+
|
|
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(`
|
|
5
|
+
`)}\n\nBriefly tell the user what you're about to do and ask them to approve or decline it in the chat. Don't claim it's done.`}const P=e=>e.variant===`approval`&&e.approval?.status===`pending`;function F(e){let t=null,n=null,r=()=>e.track(t??n),i=[],a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=(e,t)=>{a.set(e,[...a.get(e)??[],t]),a.size>32&&a.delete(a.keys().next().value)},c=t=>e.messages().find(e=>e.id===t),l=e=>e.approvals.filter(e=>c(e)?.approval?.status===`pending`),u=e=>j(c(e)?.approval?.toolName??``),d=(t,n,r)=>{t.outcome={status:n,text:r};for(let n of l(t))e.decide(n)},f=t=>t.flatMap(t=>e.messages().find(e=>e.id===t)??[]).filter(e=>!e.variant&&e.content.trim()).map(e=>e.content.trim()).join(`
|
|
6
|
+
|
|
7
|
+
`),p=async t=>{do await k();while(e.busy()&&!(t&&(e.parked()||t.failed)))};return{clientTools:e.clientTools,recordDirectTurn:e.recordDirect,getHistory:()=>{let t=e.messages().filter(e=>(e.role===`user`||e.role===`assistant`)&&!e.variant&&!e.voiceProcessing&&!e.streaming&&e.content),n=!1,r=[];for(let e=t.length-1;e>=0;--e){let i=t[e];if(i.role===`user`)n=!1;else if(!i.voiceCaption)n=!0;else if(n)continue;r.unshift({role:i.role,content:i.content})}return r},dropDelegation(t,n){o.set(t,!!n),o.size>32&&o.delete(o.keys().next().value);let r=n&&i.find(e=>e.delegationId===t);r&&!r.outcome&&d(r,`timeout`,``);for(let n of a.get(t)??[])n.stopStream?.(),n.dropped=!0,n.ids.length&&e.unspoken(n.ids)},async runDelegatedTurn({delegationId:m,userText:h,userUtteranceIds:g,stream:_,priorToolResults:v}){let y=i.filter(e=>l(e).length),b=y.flatMap(l);if(b.length===1&&O(h)){let e=u(b[0]);return d(y[0],`denied`,``),{status:`denied`,text:`Okay, I cancelled the ${e} request. Nothing was done.`,inChat:!1}}let x=e.parked()&&e.messages().every(e=>!P(e)||b.includes(e.id));e.busy()&&!x&&await p();let S=new Set(e.messages().map(e=>e.id)),C=()=>e.messages().filter(e=>!S.has(e.id)&&e.variant===`approval`),E={ids:[],failed:!1},D=_?new w:null,A=``,M=``,F=!1,I=e=>{for(let t of e)M+=t,_(t)},L;D&&(E.onUpdate=()=>{if(F)return;let e=f(E.ids);if(!e.startsWith(A)){F=!0,clearTimeout(L);return}if(e.length===A.length)return;let t=e.slice(A.length);A=e,I(D.push(t)),clearTimeout(L),L=setTimeout(()=>{F||I(D.idle())},200)},E.stopStream=()=>{clearTimeout(L),F=!0,E.onUpdate=void 0}),s(m,E),t=E,r();try{await e.send(h,{userMessageId:e.claim(h,g),priorToolResults:v}),await p(E)}catch{E.failed=!0}finally{t=null,r()}D&&(E.onUpdate?.(),clearTimeout(L),F||I(D.flush()),E.onUpdate=void 0,E.stopStream=void 0);let R=e=>{let t=T(M,e);return t>0?{streamedChars:t}:{}},z=E.ids.flatMap(t=>e.messages().find(e=>e.id===t)??[]),B=f(E.ids),V=E.failed?[]:C().filter(P),H=new Set(V.map(e=>j(e.approval.toolName)));for(let t of y){if(t.outcome)continue;for(let n of l(t).filter(e=>H.has(u(e))))t.replaced.add(n),e.decide(n);let n=u(t.approvals[0]);(t.approvals.every(e=>t.replaced.has(e))||x&&t.approvals.every(e=>c(e)?.approval?.status===`denied`))&&(t.outcome={status:`cancelled`,text:`The earlier ${n} request was replaced by the new one; it was not done.`})}if(V.length){let c=new Set(V.map(e=>e.id)),p={delegationId:m,approvals:[...c],at:Date.now(),replaced:/* @__PURE__ */ new Set};return i.push(p),o.get(m)&&d(p,`timeout`,``),B=`${B}\n\n${N(V.map(e=>e.approval))}`.trim(),{status:`pending_approval`,text:B,...R(B),followUp:async({signal:o,approvalTimeoutMs:h=3e5,readBack:g=!0,onUpdate:_})=>{let v={ids:[],failed:!1};a.delete(m),s(m,v);let y=()=>C().filter(e=>c.has(e.id)||v.ids.includes(e.id)),b=()=>C().filter(e=>P(e)&&!c.has(e.id)&&!i.some(t=>t.approvals.includes(e.id))&&(v.ids.includes(e.id)||e.approval?.toolType===`webmcp`&&n===v)),x=()=>{n=v,r()};g&&x();try{for(;!o.aborted&&!p.outcome&&(t||e.busy()||y().some(P));){g&&n!==v&&!l(p).length&&x();let t=b();if(t.length){for(let e of t)c.add(e.id),p.approvals.push(e.id);p.at=Date.now(),_?.(N(t.map(e=>e.approval)))}if(Date.now()-p.at>=h&&l(p).length&&(!e.busy()||e.parked())){d(p,`timeout`,`That ${u(p.approvals[0])} request expired, so nothing was done.`);break}await k()}}finally{n===v&&(n=null,r()),i.splice(i.indexOf(p),1)}if(o.aborted)return null;if(p.outcome)return p.outcome;if(v.failed)return{status:`failed`,text:`The ${u(p.approvals[0])} request didn't complete.`};let S=y(),w=e=>S.filter(e).map(e=>j(e.approval.toolName)).join(`, `),T=S.some(e=>e.approval?.status===`approved`),E=w(e=>e.approval?.status===`denied`&&!p.replaced.has(e.id)),D=w(e=>p.replaced.has(e.id)),O=w(e=>e.approval?.status===`timeout`),A=[T?f(v.ids):``,E&&`The user declined the ${E} request in the chat, so ${T?`that part was not done`:`nothing was done`}.`,D&&`The earlier ${D} request was replaced by the new one; it was not done.`,O&&`The ${O} request timed out, so it was not done.`].filter(Boolean).join(`
|
|
8
|
+
|
|
9
|
+
`);return{status:T?`completed`:E?`denied`:D?`cancelled`:O?`timeout`:`completed`,text:A}}}}return!E.failed&&e.parked()||z.some(e=>e.agentMetadata?.awaitingLocalTool&&!e.agentMetadata.askUserQuestionAnswered&&!e.toolCall?.name?.startsWith(`webmcp:`))?(B=`${B}\n\nI need your answer in the chat before I can continue.`.trim(),{status:E.failed?`failed`:`completed`,text:B,...R(B)}):{status:!E.failed&&B?`completed`:`failed`,text:B,...R(B)}}}}const I=(e,t,n,r)=>{let i=e.session;try{e.keyed=n?new n({find:e=>i.messages.find(t=>t.id===e),inject:e=>i.injectMessage(e),upsert:e=>i.upsertMessage(e),settle:e=>{i.messages=i.messages.map(t=>e.has(t.id)?{...t,streaming:!1,voiceProcessing:!1}:t),i.callbacks.onMessagesChanged([...i.messages])},setStreaming:t=>{(t||!e.busy())&&e.setStreaming(t)},markSpoken:e=>{i.ttsSpokenMessageIds.add(e)}}):null,r&&t.setSessionBridge&&t.setSessionBridge(r({messages:()=>i.messages,busy:()=>e.busy(),parked:()=>i.webMcpApprovalResolvers.size>0,claim:(t,n)=>e.keyed?.claimUserTurn(t,n)??null,send:(e,t)=>i.sendMessage(e,{viaVoice:!0,voiceTurn:t}),track:t=>{e.setDelegation(t)},unspoken:e=>{for(let t of e)i.ttsSpokenMessageIds.delete(t);i.streaming||i.speakLatestAssistantMessage(e)},clientTools:()=>i.getClient().getVoiceClientTools(),recordDirect:({delegationId:t,userText:n,userUtteranceIds:r,assistantText:a})=>{let o=e.keyed?.claimUserTurn(n,r),s=!1;i.messages=i.messages.map(e=>{if(e.id!==o||e.role!==`user`)return e;s=!0;let{voiceCaption:t,...n}=e;return{...n,viaVoice:!0}}),s?i.callbacks.onMessagesChanged([...i.messages]):n.trim()&&i.injectMessage({role:`user`,content:n.trim()});let c=a.trim();if(!c)return;let l=`voice-direct-${t}`;i.ttsSpokenMessageIds.add(l),i.injectMessage({id:l,role:`assistant`,content:c})},decide:e=>{if(i.webMcpApprovalResolvers.has(e))return i.resolveWebMcpApproval(e,`denied`);let t=i.messages.find(t=>t.id===e)?.approval;t?.status===`pending`&&i.resolveApproval(t,`denied`)}}));let a=e.generation(),o=()=>e.provider()===t&&a===e.generation(),s=(i.config.voiceRecognition??{}).processingErrorText??`Voice processing failed. Please try again.`;t.onResult(e=>{o()&&e.provider!==`runtype`&&e.text&&e.text.trim()&&i.sendMessage(e.text,{viaVoice:!0})}),t.onTranscript&&t.onTranscript((t,n,r,a)=>{if(o()){if(a?.turnId)e.keyed?.apply(t,n,r,a.turnId,a.startMs,a.caption);else if(t===`user`)e.pendingUser?i.upsertMessage({id:e.pendingUser,role:`user`,content:n,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,voiceProcessing:!r}):e.pendingUser=i.injectMessage({role:`user`,content:n,streaming:!1,voiceProcessing:!r}).id,r&&(e.turns().start(a?.turnId),e.pendingUser=null,e.pendingAssistant=i.injectMessage({role:`assistant`,content:``,streaming:!0,voiceProcessing:!0}).id,e.setStreaming(!0));else{if(!e.turns().accepts(a?.turnId))return;e.pendingAssistant?i.upsertMessage({id:e.pendingAssistant,role:`assistant`,content:n,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!r,voiceProcessing:!r}):e.pendingAssistant=i.injectMessage({role:`assistant`,content:n,streaming:!r,voiceProcessing:!r}).id,r&&(e.pendingAssistant&&i.ttsSpokenMessageIds.add(e.pendingAssistant),e.setStreaming(!1),e.pendingAssistant=null)}}}),t.onLevel&&t.onLevel(t=>{o()&&e.setLevel(Number.isFinite(t)?Math.max(0,Math.min(1,t)):0)}),t.onMetrics&&t.onMetrics(e=>{o()&&i.config.voiceRecognition?.onMetrics?.(e)}),t.onError(t=>{o()&&(console.error(`Voice error:`,t),e.pendingAssistant&&=(i.upsertMessage({id:e.pendingAssistant,role:`assistant`,content:s,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,voiceProcessing:!1}),e.setStreaming(!1),e.pendingUser=null,null),e.keyed?.fail(s))}),t.onStatusChange(t=>{o()&&(e.setStatus(t),(t===`listening`||t===`idle`||t===`disconnected`)&&e.settlePending(t!==`listening`),(t===`idle`||t===`disconnected`)&&e.keyed?.settle(),i.callbacks.onVoiceStatusChanged?.(t))}),t.connect()}catch(e){console.error(`Failed to setup voice:`,e)}},L=e=>{let t=t=>{if(e.original)return;let n=e.config().voiceRecognition??{};e.original={backgroundColor:t.style.backgroundColor,color:t.style.color,borderColor:t.style.borderColor,iconName:n.iconName??`mic`,iconSize:parseFloat(n.iconSize??``)||e.iconFallbackPx}},n=(t,n,r)=>{let i=t.querySelector(`svg`);i&&i.remove();let a=e.original?.iconSize??(parseFloat(e.config().voiceRecognition?.iconSize??``)||e.iconFallbackPx),o=e.renderIcon(n,a,r,1.5);o&&t.appendChild(o)},r=e=>{e.classList.remove(`persona-voice-recording`,`persona-voice-processing`,`persona-voice-speaking`)};return{recording:()=>{let n=e.mic();if(!n)return;t(n);let i=e.config().voiceRecognition??{},a=i.recordingBackgroundColor,o=i.recordingIconColor,s=i.recordingBorderColor;if(r(n),n.classList.add(`persona-voice-recording`),e.setMicState(`recording`),n.style.backgroundColor=a??`var(--persona-voice-recording-bg, #ef4444)`,n.style.color=o??`var(--persona-voice-recording-indicator, #ffffff)`,o){let e=n.querySelector(`svg`);e&&e.setAttribute(`stroke`,o)}s&&(n.style.borderColor=s),n.setAttribute(`aria-label`,`Stop voice recognition`)},processing:()=>{let i=e.mic();if(!i)return;t(i);let a=e.config().voiceRecognition??{},o=e.session().getVoiceInterruptionMode(),s=e.original,c=a.processingIconName??`loader`,l=a.processingIconColor??s?.color??``,u=a.processingBackgroundColor??s?.backgroundColor??``,d=a.processingBorderColor??s?.borderColor??``;r(i),i.classList.add(`persona-voice-processing`),e.setMicState(`processing`),i.style.backgroundColor=u,i.style.borderColor=d;let f=l||`currentColor`;i.style.color=f,n(i,c,f),i.setAttribute(`aria-label`,`Processing voice input`),o===`none`&&(i.style.cursor=`default`)},speaking:()=>{let i=e.mic();if(!i)return;t(i);let a=e.config().voiceRecognition??{},o=e.session().getVoiceInterruptionMode(),s=e.original,c=o===`cancel`?`square`:o===`barge-in`?`mic`:`volume-2`,l=a.speakingIconName??c,u=a.speakingIconColor??(o===`barge-in`?a.recordingIconColor??s?.color??``:s?.color??``),d=a.speakingBackgroundColor??(o===`barge-in`?a.recordingBackgroundColor??`var(--persona-voice-recording-bg, #ef4444)`:s?.backgroundColor??``),f=a.speakingBorderColor??(o===`barge-in`?a.recordingBorderColor??``:s?.borderColor??``);r(i),i.classList.add(`persona-voice-speaking`),e.setMicState(`speaking`),i.style.backgroundColor=d,i.style.borderColor=f;let p=u||`currentColor`;i.style.color=p,n(i,l,p);let m=o===`cancel`?`Stop playback and re-record`:o===`barge-in`?`Speak to interrupt`:`Agent is speaking`;i.setAttribute(`aria-label`,m),o===`none`&&(i.style.cursor=`default`),o===`barge-in`&&i.classList.add(`persona-voice-recording`)},reset:()=>{let t=e.mic();if(!t)return;r(t),e.setMicState(`idle`);let i=e.original;i&&(t.style.backgroundColor=i.backgroundColor??``,t.style.color=i.color??``,t.style.borderColor=i.borderColor??``,n(t,i.iconName,i.color||`currentColor`),e.original=null),t.style.cursor=``,t.setAttribute(`aria-label`,`Start voice recognition`)}}};export{f as BrowserVoiceProvider,_ as KeyedVoiceTranscript,d as RuntypeVoiceProvider,m as createBestAvailableVoiceProvider,L as createMicStateStyles,p as createVoiceProvider,F as createVoiceSessionBridge,h as isVoiceSupported,I as wireSessionVoice};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./chunk-DTDHeUsG.js";const t=[1e3,2e3,4e3,8e3,8e3];function n(n){let r=0,i=null,a=null,o=!1,s=()=>{if(a&&=(clearTimeout(a),null),i){let e=i;i=null,e()}},c=()=>{let e=n.getStatus();(e===`resuming`||e===`paused`)&&s()},l=()=>{(typeof document>`u`||document.visibilityState!==`hidden`)&&c()},u=()=>{c()},d=()=>{o||=(typeof document<`u`&&document.addEventListener(`visibilitychange`,l),typeof window<`u`&&window.addEventListener(`online`,u),!0)},f=()=>{o&&=(typeof document<`u`&&document.removeEventListener(`visibilitychange`,l),typeof window<`u`&&window.removeEventListener(`online`,u),!1)},p=e=>new Promise(t=>{i=t,a=setTimeout(()=>{a=null,i=null,t()},e)}),m=()=>{let t=n.getResumable();n.clearResumable(),n.setReconnecting(!1),r=0,f(),n.setAbortController(null);let i=!1;for(let e of n.getMessages())e.streaming&&(e.streaming=!1,i=!0);let a=n.buildErrorContent(`Connection lost and the response could not be resumed.`);a?n.appendMessage({id:`${e}${t?.executionId??n.nextSequence()}`,role:`assistant`,content:a,localOnly:!0,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:n.nextSequence()}):i&&n.notifyMessagesChanged(),n.setStreaming(!1),n.setStatus(`idle`),n.onError(/* @__PURE__ */ Error(`Durable session reconnect failed.`))},h=async()=>{let e=n.config.reconnect?.backoffMs??t,i=n.config.reconnect?.maxAttempts??e.length,a=n.config.reconnectStream;if(!a)n.setReconnecting(!1);else{for(;n.getResumable()&&r<i;){r+=1,n.setStatus(`resuming`);let t=n.getResumable(),o=t.lastEventId,s=new AbortController;n.setAbortController(s),n.emitReconnect({phase:`resuming`,handle:t,attempt:r});let c=null;try{let e=await a({executionId:t.executionId,after:t.lastEventId,signal:s.signal});e&&e.ok&&e.body&&(c=e.body)}catch{c=null}if(s.signal.aborted)return;if(c){let e=n.getMessages().find(e=>e.id===t.assistantMessageId)?.content,i=typeof e==`string`?e:``;try{await n.resumeConnect(c,t.assistantMessageId,i)}catch{}if(s.signal.aborted)return;if(!n.getResumable()){n.setReconnecting(!1),r=0,f(),n.emitReconnect({phase:`resumed`,handle:t});return}n.getResumable().lastEventId!==o&&(r=0)}if(c&&n.getResumable()&&n.settleParked(t.executionId)){r=0,f();return}if(n.getResumable()&&r<i&&(n.setStatus(`paused`),await p(e[Math.min(r-1,e.length-1)]??1e3),s.signal.aborted))return}n.getResumable()&&m()}};return{begin(){r=0,d(),h()},teardown(){a&&=(clearTimeout(a),null),i=null,r=0,f()},wake:s}}export{n as createReconnectController};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=`reconnect-failed-`,t=e=>e.localOnly===!0||e.role===`assistant`&&typeof e.id==`string`&&e.id.startsWith(`reconnect-failed-`);export{t as n,e as t};
|