@runtypelabs/persona 4.17.0 → 4.17.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.
@@ -8,7 +8,7 @@ ${t}`:"")+(e.description?`
8
8
  ${e.description}`:"");return window.confirm(n)},eh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},th=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},nh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function yn(e){return e==="card"?"collapsed":e}function Ar(e){return e.split(";",1)[0].trim().toLowerCase()}function oh(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ar(r)===t)return{mode:yn(s),selector:Ar(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ar(r)===o)return{mode:yn(s),selector:o}}function rh(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:yn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Ar(t.file.mimeType):void 0,u=l?oh(o.files.byMediaType,l):void 0;if(l&&u)return{mode:u.mode,matchedBy:{type:"mediaType",mediaType:l,selector:u.selector}};if(o.files.default)return{mode:yn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:yn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:yn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:yn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ho(e,t){return rh(e,t).mode}function xs(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var sh="agent_",ah="flow_";function Vp(e){return e.startsWith(sh)?{kind:"agentId",agentId:e}:e.startsWith(ah)?{kind:"flowId",flowId:e}:null}function qp(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=Vp(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let u=t?.[a];if(!u)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:u(l).payload}}let r=Vp(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as ih,ARR as lh,OBJ as ch,STR as dh}from"partial-json";var Rl="ask_user_question",Cs=8,Sr="data-persona-ask-sheet-for",ph="Other",uh="Other\u2026",Gp="Type your own answer here",Yp="Send",fh="Next",gh="Back",mh="Submit all",hh="Skip",yh=3,Hl="data-ask-current-index",Bl="data-ask-question-count",Xp="data-ask-answers",Dl="data-ask-grouped",Qp="data-ask-layout",bh=e=>e.layout==="pills"?"pills":"rows",vh=e=>e.getAttribute(Qp)==="pills"?"pills":"rows",Kp=!1,Jp=e=>e.replace(/["\\]/g,"\\$&"),qo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Rl,Fl=e=>e?.features?.askUserQuestion??{},Tr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=ih(r,dh|ch|lh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},As=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Cs&&!Kp&&(Kp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cs}.`)),t.slice(0,Cs)},wh=e=>As(e)[0]??null,xh=(e,t)=>As(e)[t]??null,Ch=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Zp=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ah=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),l=b("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=b("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let u=Zp(n,o,t);u&&s.appendChild(u)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Sh=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Th=(e,t,n,o)=>{let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,u=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(u.length===0&&!n){for(let c=0;c<yh;c++)s.appendChild(Sh(o));return s}if(u.forEach((c,f)=>{s.appendChild(Ah(c,f,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?ph:uh;if(o==="rows"){let f=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(u.length)),f.setAttribute("data-ask-other-row","true");let w=b("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??Gp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(g),f.appendChild(w);let v=Zp(o,a,u.length);v&&f.appendChild(v),s.appendChild(f)}else{let f=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??c,s.appendChild(f)}}return s},eu=(e,t)=>{let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Gp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=b("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Yp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Mh=e=>{let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Yp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Eh=(e,t,n)=>{let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??gh,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??hh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=b("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let u=e===t-1;return l.textContent=u?n.submitAllLabel??mh:n.nextLabel??fh,l.setAttribute("data-ask-user-action",u?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ko=e=>{let t=e.getAttribute(Xp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},tu=(e,t)=>{e.setAttribute(Xp,JSON.stringify(t))},bn=e=>{let t=Number(e.getAttribute(Hl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},kh=(e,t)=>{e.setAttribute(Hl,String(Math.max(0,Math.floor(t))))},Mr=e=>{let t=Number(e.getAttribute(Bl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=e=>e.getAttribute(Dl)==="true",Lh=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Ph=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=Tr(t),o=As(n),r=Ko(e),s={},a=new Set;return o.forEach((l,u)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,u)&&(s[d]=r[u]))}),s},nu=e=>{let t=Ko(e),n=bn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(u=>r.add(u));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(u=>{let d=u.getAttribute("data-option-label")??"",c=r.has(d);u.setAttribute("aria-pressed",c?"true":"false"),u.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(u=>u.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},ou=e=>{if(!yo(e))return;let t=Ko(e),n=bn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Ol=(e,t,n)=>{let o=Fl(n),r=vh(e),{payload:s,complete:a}=Tr(t),l=yo(e),u=bn(e),d=Mr(e),c=l?xh(s,u):wh(s),f=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${u+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let S=typeof c?.question=="string"?c.question:"";v.textContent=S,v.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let S=Th(c,o,a,r);C.replaceWith(S)}if(r!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(eu(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!T?e.appendChild(Mh(o)):(!f||l)&&T&&T.remove(),e.setAttribute("data-multi-select",f?"true":"false");let B=e.querySelector('[data-ask-nav-row="true"]');if(l){let S=Eh(u,d,o);B?B.replaceWith(S):e.appendChild(S)}else B&&B.remove();nu(e),ou(e)},Ih=(e,t,n)=>{let o=Fl(t),r=bh(o),s=e.toolCall.id,a=As(n),l=Math.max(1,a.length),u=l>1,d=Lh(e,a),c=u?Ph(e,l):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Sr,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",e.id),f.setAttribute(Bl,String(l)),f.setAttribute(Hl,String(c)),f.setAttribute(Dl,u?"true":"false"),f.setAttribute(Qp,r),tu(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Ch(f,o);let w=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=b("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",w.appendChild(g);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),f.appendChild(w);let T=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),r!=="rows"&&f.appendChild(eu(o,r)),Ol(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Wh=(e,t,n)=>{let{payload:o}=Tr(t),r=Math.max(1,As(o).length);r>Mr(e)&&(e.setAttribute(Bl,String(r)),r>1&&!yo(e)&&e.setAttribute(Dl,"true")),Ol(e,t,n)};var _a=(e,t,n)=>{if(!n||!qo(e)||Fl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sr}]`).forEach(d=>{d.getAttribute(Sr)!==r&&d.remove()});let a=n.querySelector(`[${Sr}="${Jp(r)}"]`);if(a){Wh(a,e,t);return}let{payload:l}=Tr(e),u=Ih(e,t,l);n.appendChild(u)},Er=(e,t)=>{if(!e)return;let n=t?`[${Sr}="${Jp(t)}"]`:`[${Sr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Nl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),bo=(e,t)=>{let n=Ko(e),o=bn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,tu(e,n),nu(e),ou(e)},$a=(e,t,n,o)=>{let r=Mr(e),s=Math.max(0,Math.min(r-1,o));kh(e,s),Ol(e,t,n)};var Xn="suggest_replies";var Rh={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},su={name:Xn,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:Rh,origin:"sdk",annotations:{readOnlyHint:!0}},_l=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ss=e=>e.variant==="tool"&&e.toolCall?.name===Xn,Hh=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},au=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ss(n))continue;let o=Hh(n.toolCall?.args);return o.length>0?o:null}return null},ru=new Set,Bh=(e,t,n)=>{let o=`${e}:${t}:${n}`;ru.has(o)||(ru.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},vo=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let l=t?.[a],u=n?.[a];l===void 0||u===void 0||l!==u&&Bh(a,u,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var Dh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Cs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Fh={name:Rl,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Dh,origin:"sdk",annotations:{readOnlyHint:!0}},Ua=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Fh),vo(e).expose&&t.push(su),t};import{parse as Oh,STR as Nh,OBJ as _h}from"partial-json";var iu=e=>e.replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),wo=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)}},$h=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},lu=e=>e.status==="complete"?$h(e):e.status==="pending"?"Waiting":"",Uh=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var cu=e=>e.status==="complete"?Uh(e):"Using tool...",za=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ms=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return za(t)},ja=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return za(t)},$l=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ms(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Va=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ts(o,n.slice(s,a.index),[]),a[1]!==void 0?Ts(o,a[1],["bold"]):a[2]!==void 0?Ts(o,a[2],["italic"]):a[3]!==void 0&&Ts(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ts(o,n.slice(s),[]),o},Ts=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},zh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},du=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},pu=()=>{let e=zh();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},uu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Oh(n,Nh|_h);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?iu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=iu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var fu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var gu="4.17.0";var ks=gu;var Vh="https://api.runtype.com/v1/dispatch",qa="https://api.runtype.com";function qh(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Ul=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Kh(e){switch(e){case"json":return uu;case"regex-json":return pu;case"xml":return fu;default:return du}}var mu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gh(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=mu(n);if(!mu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Es(e);return Es(t)!==null&&a===null?t:e}var Ls=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Vh,this.headers={"Content-Type":"application/json","X-Persona-Version":ks,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Kh(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Oa(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=qp(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Ul).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:u}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}u(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?zp(n):void 0,l=this.clientToolsFingerprintSessionId===t,u=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let w=0;;w++){if(f=await o({...s&&(c||!u)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),f.status===409&&w===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||qa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let u={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(u.sessionId=a),r&&a){let d=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(a,d,w=>{let g={...u,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(u),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Ul).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Ul).sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,u]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=u);let s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let u=l;return r.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=r.clientTools),u}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let u=c=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=f,r(f),f},d=c=>o.current?o.current:u(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),u(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",u=Date.now(),d=0,c=()=>u+d++,f=M=>{let I=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,W=M.tools?M.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...M,reasoning:I,toolCall:h,tools:W}},w=M=>{if(M.role!=="assistant"||M.variant)return!0;let I=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||I||h||!!M.stopReason},g=M=>{w(M)&&n({type:"message",message:f(M)})},v=null,C=null,T={current:null},B={current:null},S=null,k="",P=new Map,H=new Map,F=new Map,N=new Map,z=new Map,j={lastId:null,byStep:new Map},te={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},G=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Q=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ie=o,Y=!1,ue=()=>{if(v)return v;let M,I="",h=S;return!Y&&ie?(M=ie,Y=!0,I=r??""):ie&&h?M=`${ie}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:M,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(v),v},X=(M,I)=>{j.lastId=I,M&&j.byStep.set(M,I)},ge=(M,I)=>{let h=M.reasoningId??M.id,W=G(M);if(h){let R=String(h);return X(W,R),R}if(W){let R=j.byStep.get(W);if(R)return j.lastId=R,R}if(j.lastId&&!I)return j.lastId;if(!I)return null;let L=`reason-${c()}`;return X(W,L),L},Z=M=>{let I=N.get(M);if(I)return I;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return N.set(M,h),g(h),h},pe=(M,I)=>{te.lastId=I,M&&te.byCall.set(M,I)},ee=new Set,me=new Map,we=new Set,he=new Map,ke=M=>{if(!M)return!1;let I=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},Ne=(M,I)=>{let h=M.toolId??M.id,W=Q(M);if(h){let R=String(h);return pe(W,R),R}if(W){let R=te.byCall.get(W);if(R)return te.lastId=R,R}if(te.lastId&&!I)return te.lastId;if(!I)return null;let L=`tool-${c()}`;return pe(W,L),L},Ue=M=>{let I=z.get(M);if(I)return I;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),g(h),h},Qe=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let I=Number(M);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Oe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},_e=new Map,Ae=new Map,Se=new Map,ze=(M,I,h)=>{let W=Se.get(M);W||(W=[],Se.set(M,W));let L=0,R=W.length;for(;L<R;){let $=L+R>>>1;W[$].seq<I?L=$+1:R=$}W[L]?.seq===I?W[L]={seq:I,text:h}:W.splice(L,0,{seq:I,text:h});let q="";for(let $=0;$<W.length;$++)q+=W[$].text;return q},Gt=(M,I)=>{let h=Oe(I),W=Ae.get(M.id),L=Gh(W,h);M.rawContent=L;let R=_e.get(M.id),q=de=>{let Pe=M.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(M.content=de)},$=()=>{if(R){let de=R.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(M.id),Ae.delete(M.id),M.streaming=!1,g(M)};if(!R){q(h),$();return}let K=Es(L);if(K!==null&&K.trim()!==""){q(K),$();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let Ve=R.getExtractedText();return Ve!==null&&Ve.trim()!==""?Ve:h},je;try{je=R.processChunk(L)}catch{q(h),$();return}if(je instanceof Promise){je.then(de=>{q(ce(de)),$()}).catch(()=>{q(h),$()});return}q(ce(je)),$()},gt=null,Ht=(M,I,h,W)=>{M.rawContent=I,_e.has(M.id)||_e.set(M.id,this.createStreamParser());let L=_e.get(M.id),R=I.trim().startsWith("{")||I.trim().startsWith("[");if(R&&Ae.set(M.id,I),L.__isPlainTextParser===!0){M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M);return}let $=L.processChunk(I);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(M.content=ce,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(M.content=K,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}},xn=(M,I)=>{let h=I??M.content;if(h==null||h===""){M.streaming=!1,g(M);return}let L=Ae.get(M.id)??Oe(h);M.rawContent=L;let R=_e.get(M.id),q=null,$=!1;if(R&&(q=R.getExtractedText(),q===null&&(q=Es(L)),q===null)){let K=R.processChunk(L);K instanceof Promise?($=!0,K.then(ce=>{let je=typeof ce=="string"?ce:ce?.text??null;je!==null&&(M.content=je,M.streaming=!1,_e.delete(M.id),Ae.delete(M.id),g(M))}).catch(()=>{})):q=typeof K=="string"?K:K?.text??null}if(!$){q!==null&&q.trim()!==""?M.content=q:Ae.has(M.id)||(M.content=Oe(h));let K=_e.get(M.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,g(M)}},Cn=(M,I,h)=>{let W=H.get(M);if(W)return W;let L={id:`nested-${I}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(M,L),g(L),L},et=[],Le,ye=new Map,tt=0,Te="agent",ve=!1,re=null,xe=null,An=new Map,ne=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let I=et[M].payloadType,h=et[M].payload;if(!ve&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L),Cn(W,L,"reasoning");continue}let R=ge(h,!0)??`reason-${c()}`,q=Z(R);q.reasoning=q.reasoning??{id:R,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??Qe(h.startedAt??h.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),q.streaming=!0,q.reasoning.status="streaming",g(q)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let $=H.get(W),K=h.reasoningText??h.text??h.delta??"";K&&h.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),g($));continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=Z(L);R.reasoning=R.reasoning??{id:L,status:"streaming",chunks:[]},R.reasoning.startedAt=R.reasoning.startedAt??Qe(h.startedAt??h.timestamp);let q=h.reasoningText??h.text??h.delta??"";if(q&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=ze(L,$,String(q));R.reasoning.chunks=[K]}else R.reasoning.chunks.push(String(q))}if(R.reasoning.status=h.done?"complete":"streaming",h.done){R.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let $=R.reasoning.startedAt??Date.now();R.reasoning.durationMs=Math.max(0,(R.reasoning.completedAt??Date.now())-$)}R.streaming=R.reasoning.status!=="complete",g(R)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let ce=typeof h.text=="string"?h.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}P.delete(W),H.delete(W);continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=typeof h.text=="string"?h.text:"";!N.get(L)&&(R||h.scope==="loop")&&Z(L);let q=N.get(L);if(q?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),R&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(R),q.reasoning.status="complete",q.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let K=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-K),q.streaming=!1,g(q)}let $=G(h);$&&j.byStep.delete($)}else if(I==="tool_start"){v&&(v.streaming=!1,g(v),v=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??Ne(h,!0)??`tool-${c()}`,L=h.toolName??h.name;if(ke(L)){ee.add(W);continue}pe(Q(h),W);let R=Ue(W),q=R.toolCall??{id:W,status:"pending"};q.name=L??q.name,q.status="running",h.parameters!==void 0?q.args=h.parameters:h.args!==void 0&&(q.args=h.args),q.startedAt=q.startedAt??Qe(h.startedAt??h.timestamp),q.completedAt=void 0,q.durationMs=void 0,R.toolCall=q,R.streaming=!0,h.executionId&&(R.agentMetadata={executionId:h.executionId,iteration:h.iteration}),g(R)}else if(I==="tool_output_delta"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W))continue;let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.startedAt=R.startedAt??Qe(h.startedAt??h.timestamp);let q=h.text??h.delta??h.message??"";q&&(R.chunks=R.chunks??[],R.chunks.push(String(q))),R.status="running",L.toolCall=R,L.streaming=!0;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L)}else if(I==="tool_complete"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W)){ee.delete(W);continue}let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.status="complete",h.result!==void 0&&(R.result=h.result),typeof h.duration=="number"&&(R.duration=h.duration),R.completedAt=Qe(h.completedAt??h.timestamp);let q=h.duration??h.executionTime;if(typeof q=="number")R.durationMs=q;else{let ce=R.startedAt??Date.now();R.durationMs=Math.max(0,(R.completedAt??Date.now())-ce)}L.toolCall=R,L.streaming=!1;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L);let K=Q(h);K&&te.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,L=W??h.toolId??`local-${c()}`,R=Ue(L),q=h.toolName,$=h.origin==="webmcp"&&!Cr(q)?`webmcp:${q}`:q,K=Cr($),ce=R.toolCall??{id:L,status:"pending"};ce.name=$,ce.args=h.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(h.startedAt??h.timestamp??h.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,R.toolCall=ce,R.streaming=!1,R.agentMetadata={...R.agentMetadata,executionId:h.executionId??R.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},g(R)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L);continue}let R=v;R&&(Te==="flow"?(xn(R),gt=R):(R.streaming=!1,g(R)),v=null),S=typeof h.id=="string"?h.id:S,k=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,L=W?P.get(W):void 0;if(W&&L){let q=typeof h.delta=="string"?h.delta:"",$=(F.get(W)??"")+q;if(F.set(W,$),$.trim()==="")continue;let K=Cn(W,L);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:L},Ht(K,$,q,void 0);continue}if(S=typeof h.id=="string"?h.id:S,Te==="flow"){let q=typeof h.delta=="string"?h.delta:"";if(k+=q,k.trim()==="")continue;let $=ue();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},Ht($,k,q,void 0),C=$;continue}let R=ue();R.content+=h.delta??"",R.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:xe?.agentName},C=R,g(R)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)){let R=H.get(W);R&&xn(R),P.delete(W),F.delete(W),H.delete(W);continue}let L=v;L&&(Te==="flow"?(xn(L),gt=L):((L.content??"")===""&&typeof h.text=="string"&&(L.content=h.text),L.streaming=!1,g(L)),v=null),S=null,k=""}else if(I==="step_complete"){let W=h.stepType,L=h.executionType;if(W==="tool"||L==="context")continue;if(h.success===!1){let R=h.error,q=typeof R=="string"&&R!==""?R:R!=null&&typeof R=="object"&&Reflect.has(R,"message")?String(R.message??"Step failed"):"Step failed";n({type:"error",error:new Error(q)});let $=v;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let R=gt;gt=null;let q=h.stopReason,$=h.result?.response;if(R)q&&(R.stopReason=q),$!=null?Gt(R,$):R.streaming!==!1&&(_e.delete(R.id),Ae.delete(R.id),R.streaming=!1,g(R));else{let K=$!=null&&$!=="";if(K||q){let ce=ue();q&&(ce.stopReason=q),K?xn(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",ve=!0,Te==="agent"&&(xe={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Qe(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(xe&&(xe.currentIteration=W),ne==="separate"&&W>1){let L=v;L&&(L.streaming=!1,g(L),An.set(W-1,L),v=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??te.lastId;if(W){let L=z.get(W);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(h.delta??""),g(L))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,L=v??C;if(W&&L!==null){let R=h.id;(!R||L.agentMetadata?.turnId===R)&&(L.stopReason=W,g(L))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ye.set(W,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(I==="media_delta"){let W=ye.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),L=ye.get(W);ye.delete(W);let R=(typeof h.mediaType=="string"?h.mediaType:void 0)??L?.mediaType??"application/octet-stream",q=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:L&&L.parts.length>0?L.parts.join(""):void 0,K=null;if(q)K={type:"media",data:q,mediaType:R};else if($){let Pe=R.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:R}}let ce=h.toolCallId??L?.toolCallId,je=K?[K]:[],de=[];for(let Pe of je){if(!Pe||typeof Pe!="object")continue;let Ve=Pe,$e=typeof Ve.type=="string"?Ve.type:void 0,Re=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",Ce=null,nt="";if($e==="media"){let xt=typeof Ve.data=="string"?Ve.data:void 0;if(!xt)continue;nt=Re.length>0?Re:"application/octet-stream",Ce=`data:${nt};base64,${xt}`}else if($e==="image-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else if($e==="file-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else continue;if(Ce)if($e==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:Ce,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:Ce,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:Ce,mimeType:nt});else{let xt=nt||"application/octet-stream";de.push({type:"file",data:Ce,mimeType:xt,filename:qh(xt)})}}if(de.length>0){let Pe=c(),Ve=ce,Re={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};g(Re);let Ce=v;Ce&&(Ce.streaming=!1,g(Ce)),v=null,T.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&xe&&(xe.status=h.success?"complete":"error",xe.completedAt=Qe(h.completedAt),xe.stopReason=h.stopReason);let L=v;L&&(W==="flow"&&L.streaming!==!1?xn(L):(L.streaming=!1,g(L)),v=null),S=null,k="",gt=null,n({type:"status",status:"idle",terminal:!0})}else if(I==="execution_error"){let W=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(W)})}else if(I!=="ping"){if(I==="approval_start"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};g(R)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,L=String(h.id),R=typeof h.title=="string"?h.title:void 0,q=h.file,$;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&($={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:L,artifactType:W,title:R,component:typeof h.component=="string"?h.component:void 0,...$?{file:$}:{}});let K=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(he.set(L,{markdown:"",title:R,file:$,...K?{props:K}:{}}),!we.has(L)){we.add(L);let ce=ho(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),je=typeof h.component=="string"?h.component:void 0,de={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:xs(ce,{artifactId:L,title:R,artifactType:W,status:"streaming",...$?{file:$}:{},...je?{component:je}:{}})};me.set(L,de),g(de)}}else if(I==="artifact_delta"){let W=String(h.id),L=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:L});let R=he.get(W);R&&(R.markdown+=L)}else if(I==="artifact_update"){let W=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:W,component:typeof h.component=="string"?h.component:void 0});let L=he.get(String(h.id));L&&(L.props={...L.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let L=me.get(W);if(L){L.streaming=!1;try{let R=JSON.parse(L.rawContent??"{}");if(R.props){R.props.status="complete";let q=he.get(W);q?.markdown&&(R.props.markdown=q.markdown),q?.file&&(R.props.file=q.file),R.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(R.props.componentProps=q.props)}L.rawContent=JSON.stringify(R)}catch{}he.delete(W),g(L),me.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let L=String(W.id??`msg-${c()}`),R=W.role,$={id:L,role:R==="user"?"user":R==="system"?"system":"assistant",content:typeof W.content=="string"?W.content:"",rawContent:typeof W.rawContent=="string"?W.rawContent:void 0,createdAt:typeof W.createdAt=="string"?W.createdAt:new Date().toISOString(),streaming:W.streaming===!0,...typeof W.variant=="string"?{variant:W.variant}:{},sequence:c()};if(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&we.add(ce)}catch{}v=null,T.current=null,_e.delete(L),Ae.delete(L)}else if(I==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let W=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(W)});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}else if(I==="step_error"||I==="dispatch_error"||I==="flow_error"){let W=null;if(h.error instanceof Error)W=h.error;else if(I==="dispatch_error"){let L=h.message??h.error;L!=null&&L!==""&&(W=new Error(String(L)))}else{let L=h.error;typeof L=="string"&&L!==""?W=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(W=new Error(String(L.message??L)))}if(W){n({type:"error",error:W});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:I}=await s.read();if(M)break;l+=a.decode(I,{stream:!0});let h=l.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},du=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},pu=()=>{let e=zh();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},uu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Oh(n,Nh|_h);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?iu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=iu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var fu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var gu="4.17.1";var ks=gu;var Vh="https://api.runtype.com/v1/dispatch",qa="https://api.runtype.com";function qh(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Ul=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Kh(e){switch(e){case"json":return uu;case"regex-json":return pu;case"xml":return fu;default:return du}}var mu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gh(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=mu(n);if(!mu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Es(e);return Es(t)!==null&&a===null?t:e}var Ls=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Vh,this.headers={"Content-Type":"application/json","X-Persona-Version":ks,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Kh(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Oa(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=qp(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Ul).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:u}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}u(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?zp(n):void 0,l=this.clientToolsFingerprintSessionId===t,u=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let w=0;;w++){if(f=await o({...s&&(c||!u)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),f.status===409&&w===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||qa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let u={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(u.sessionId=a),r&&a){let d=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(a,d,w=>{let g={...u,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(u),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Ul).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Ul).sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,u]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=u);let s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let u=l;return r.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=r.clientTools),u}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let u=c=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=f,r(f),f},d=c=>o.current?o.current:u(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),u(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",u=Date.now(),d=0,c=()=>u+d++,f=M=>{let I=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,W=M.tools?M.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...M,reasoning:I,toolCall:h,tools:W}},w=M=>{if(M.role!=="assistant"||M.variant)return!0;let I=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||I||h||!!M.stopReason},g=M=>{w(M)&&n({type:"message",message:f(M)})},v=null,C=null,T={current:null},B={current:null},S=null,k="",P=new Map,H=new Map,F=new Map,N=new Map,z=new Map,j={lastId:null,byStep:new Map},te={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},G=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Q=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ie=o,Y=!1,ue=()=>{if(v)return v;let M,I="",h=S;return!Y&&ie?(M=ie,Y=!0,I=r??""):ie&&h?M=`${ie}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:M,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(v),v},X=(M,I)=>{j.lastId=I,M&&j.byStep.set(M,I)},ge=(M,I)=>{let h=M.reasoningId??M.id,W=G(M);if(h){let R=String(h);return X(W,R),R}if(W){let R=j.byStep.get(W);if(R)return j.lastId=R,R}if(j.lastId&&!I)return j.lastId;if(!I)return null;let L=`reason-${c()}`;return X(W,L),L},Z=M=>{let I=N.get(M);if(I)return I;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return N.set(M,h),g(h),h},pe=(M,I)=>{te.lastId=I,M&&te.byCall.set(M,I)},ee=new Set,me=new Map,we=new Set,he=new Map,ke=M=>{if(!M)return!1;let I=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},Ne=(M,I)=>{let h=M.toolId??M.id,W=Q(M);if(h){let R=String(h);return pe(W,R),R}if(W){let R=te.byCall.get(W);if(R)return te.lastId=R,R}if(te.lastId&&!I)return te.lastId;if(!I)return null;let L=`tool-${c()}`;return pe(W,L),L},Ue=M=>{let I=z.get(M);if(I)return I;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),g(h),h},Qe=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let I=Number(M);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Oe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},_e=new Map,Ae=new Map,Se=new Map,ze=(M,I,h)=>{let W=Se.get(M);W||(W=[],Se.set(M,W));let L=0,R=W.length;for(;L<R;){let $=L+R>>>1;W[$].seq<I?L=$+1:R=$}W[L]?.seq===I?W[L]={seq:I,text:h}:W.splice(L,0,{seq:I,text:h});let q="";for(let $=0;$<W.length;$++)q+=W[$].text;return q},Gt=(M,I)=>{let h=Oe(I),W=Ae.get(M.id),L=Gh(W,h);M.rawContent=L;let R=_e.get(M.id),q=de=>{let Pe=M.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(M.content=de)},$=()=>{if(R){let de=R.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(M.id),Ae.delete(M.id),M.streaming=!1,g(M)};if(!R){q(h),$();return}let K=Es(L);if(K!==null&&K.trim()!==""){q(K),$();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let Ve=R.getExtractedText();return Ve!==null&&Ve.trim()!==""?Ve:h},je;try{je=R.processChunk(L)}catch{q(h),$();return}if(je instanceof Promise){je.then(de=>{q(ce(de)),$()}).catch(()=>{q(h),$()});return}q(ce(je)),$()},gt=null,Ht=(M,I,h,W)=>{M.rawContent=I,_e.has(M.id)||_e.set(M.id,this.createStreamParser());let L=_e.get(M.id),R=I.trim().startsWith("{")||I.trim().startsWith("[");if(R&&Ae.set(M.id,I),L.__isPlainTextParser===!0){M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M);return}let $=L.processChunk(I);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(M.content=ce,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(M.content=K,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}},xn=(M,I)=>{let h=I??M.content;if(h==null||h===""){M.streaming=!1,g(M);return}let L=Ae.get(M.id)??Oe(h);M.rawContent=L;let R=_e.get(M.id),q=null,$=!1;if(R&&(q=R.getExtractedText(),q===null&&(q=Es(L)),q===null)){let K=R.processChunk(L);K instanceof Promise?($=!0,K.then(ce=>{let je=typeof ce=="string"?ce:ce?.text??null;je!==null&&(M.content=je,M.streaming=!1,_e.delete(M.id),Ae.delete(M.id),g(M))}).catch(()=>{})):q=typeof K=="string"?K:K?.text??null}if(!$){q!==null&&q.trim()!==""?M.content=q:Ae.has(M.id)||(M.content=Oe(h));let K=_e.get(M.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,g(M)}},Cn=(M,I,h)=>{let W=H.get(M);if(W)return W;let L={id:`nested-${I}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(M,L),g(L),L},et=[],Le,ye=new Map,tt=0,Te="agent",ve=!1,re=null,xe=null,An=new Map,ne=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let I=et[M].payloadType,h=et[M].payload;if(!ve&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L),Cn(W,L,"reasoning");continue}let R=ge(h,!0)??`reason-${c()}`,q=Z(R);q.reasoning=q.reasoning??{id:R,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??Qe(h.startedAt??h.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),q.streaming=!0,q.reasoning.status="streaming",g(q)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let $=H.get(W),K=h.reasoningText??h.text??h.delta??"";K&&h.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),g($));continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=Z(L);R.reasoning=R.reasoning??{id:L,status:"streaming",chunks:[]},R.reasoning.startedAt=R.reasoning.startedAt??Qe(h.startedAt??h.timestamp);let q=h.reasoningText??h.text??h.delta??"";if(q&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=ze(L,$,String(q));R.reasoning.chunks=[K]}else R.reasoning.chunks.push(String(q))}if(R.reasoning.status=h.done?"complete":"streaming",h.done){R.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let $=R.reasoning.startedAt??Date.now();R.reasoning.durationMs=Math.max(0,(R.reasoning.completedAt??Date.now())-$)}R.streaming=R.reasoning.status!=="complete",g(R)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let ce=typeof h.text=="string"?h.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}P.delete(W),H.delete(W);continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=typeof h.text=="string"?h.text:"";!N.get(L)&&(R||h.scope==="loop")&&Z(L);let q=N.get(L);if(q?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),R&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(R),q.reasoning.status="complete",q.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let K=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-K),q.streaming=!1,g(q)}let $=G(h);$&&j.byStep.delete($)}else if(I==="tool_start"){v&&(v.streaming=!1,g(v),v=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??Ne(h,!0)??`tool-${c()}`,L=h.toolName??h.name;if(ke(L)){ee.add(W);continue}pe(Q(h),W);let R=Ue(W),q=R.toolCall??{id:W,status:"pending"};q.name=L??q.name,q.status="running",h.parameters!==void 0?q.args=h.parameters:h.args!==void 0&&(q.args=h.args),q.startedAt=q.startedAt??Qe(h.startedAt??h.timestamp),q.completedAt=void 0,q.durationMs=void 0,R.toolCall=q,R.streaming=!0,h.executionId&&(R.agentMetadata={executionId:h.executionId,iteration:h.iteration}),g(R)}else if(I==="tool_output_delta"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W))continue;let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.startedAt=R.startedAt??Qe(h.startedAt??h.timestamp);let q=h.text??h.delta??h.message??"";q&&(R.chunks=R.chunks??[],R.chunks.push(String(q))),R.status="running",L.toolCall=R,L.streaming=!0;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L)}else if(I==="tool_complete"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W)){ee.delete(W);continue}let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.status="complete",h.result!==void 0&&(R.result=h.result),typeof h.duration=="number"&&(R.duration=h.duration),R.completedAt=Qe(h.completedAt??h.timestamp);let q=h.duration??h.executionTime;if(typeof q=="number")R.durationMs=q;else{let ce=R.startedAt??Date.now();R.durationMs=Math.max(0,(R.completedAt??Date.now())-ce)}L.toolCall=R,L.streaming=!1;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L);let K=Q(h);K&&te.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,L=W??h.toolId??`local-${c()}`,R=Ue(L),q=h.toolName,$=h.origin==="webmcp"&&!Cr(q)?`webmcp:${q}`:q,K=Cr($),ce=R.toolCall??{id:L,status:"pending"};ce.name=$,ce.args=h.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(h.startedAt??h.timestamp??h.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,R.toolCall=ce,R.streaming=!1,R.agentMetadata={...R.agentMetadata,executionId:h.executionId??R.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},g(R)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L);continue}let R=v;R&&(Te==="flow"?(xn(R),gt=R):(R.streaming=!1,g(R)),v=null),S=typeof h.id=="string"?h.id:S,k=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,L=W?P.get(W):void 0;if(W&&L){let q=typeof h.delta=="string"?h.delta:"",$=(F.get(W)??"")+q;if(F.set(W,$),$.trim()==="")continue;let K=Cn(W,L);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:L},Ht(K,$,q,void 0);continue}if(S=typeof h.id=="string"?h.id:S,Te==="flow"){let q=typeof h.delta=="string"?h.delta:"";if(k+=q,k.trim()==="")continue;let $=ue();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},Ht($,k,q,void 0),C=$;continue}let R=ue();R.content+=h.delta??"",R.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:xe?.agentName},C=R,g(R)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)){let R=H.get(W);R&&xn(R),P.delete(W),F.delete(W),H.delete(W);continue}let L=v;L&&(Te==="flow"?(xn(L),gt=L):((L.content??"")===""&&typeof h.text=="string"&&(L.content=h.text),L.streaming=!1,g(L)),v=null),S=null,k=""}else if(I==="step_complete"){let W=h.stepType,L=h.executionType;if(W==="tool"||L==="context")continue;if(h.success===!1){let R=h.error,q=typeof R=="string"&&R!==""?R:R!=null&&typeof R=="object"&&Reflect.has(R,"message")?String(R.message??"Step failed"):"Step failed";n({type:"error",error:new Error(q)});let $=v;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let R=gt;gt=null;let q=h.stopReason,$=h.result?.response;if(R)q&&(R.stopReason=q),$!=null?Gt(R,$):R.streaming!==!1&&(_e.delete(R.id),Ae.delete(R.id),R.streaming=!1,g(R));else{let K=$!=null&&$!=="";if(K||q){let ce=ue();q&&(ce.stopReason=q),K?xn(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",ve=!0,Te==="agent"&&(xe={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Qe(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(xe&&(xe.currentIteration=W),ne==="separate"&&W>1){let L=v;L&&(L.streaming=!1,g(L),An.set(W-1,L),v=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??te.lastId;if(W){let L=z.get(W);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(h.delta??""),g(L))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,L=v??C;if(W&&L!==null){let R=h.id;(!R||L.agentMetadata?.turnId===R)&&(L.stopReason=W,g(L))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ye.set(W,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(I==="media_delta"){let W=ye.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),L=ye.get(W);ye.delete(W);let R=(typeof h.mediaType=="string"?h.mediaType:void 0)??L?.mediaType??"application/octet-stream",q=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:L&&L.parts.length>0?L.parts.join(""):void 0,K=null;if(q)K={type:"media",data:q,mediaType:R};else if($){let Pe=R.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:R}}let ce=h.toolCallId??L?.toolCallId,je=K?[K]:[],de=[];for(let Pe of je){if(!Pe||typeof Pe!="object")continue;let Ve=Pe,$e=typeof Ve.type=="string"?Ve.type:void 0,Re=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",Ce=null,nt="";if($e==="media"){let xt=typeof Ve.data=="string"?Ve.data:void 0;if(!xt)continue;nt=Re.length>0?Re:"application/octet-stream",Ce=`data:${nt};base64,${xt}`}else if($e==="image-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else if($e==="file-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else continue;if(Ce)if($e==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:Ce,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:Ce,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:Ce,mimeType:nt});else{let xt=nt||"application/octet-stream";de.push({type:"file",data:Ce,mimeType:xt,filename:qh(xt)})}}if(de.length>0){let Pe=c(),Ve=ce,Re={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};g(Re);let Ce=v;Ce&&(Ce.streaming=!1,g(Ce)),v=null,T.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&xe&&(xe.status=h.success?"complete":"error",xe.completedAt=Qe(h.completedAt),xe.stopReason=h.stopReason);let L=v;L&&(W==="flow"&&L.streaming!==!1?xn(L):(L.streaming=!1,g(L)),v=null),S=null,k="",gt=null,n({type:"status",status:"idle",terminal:!0})}else if(I==="execution_error"){let W=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(W)})}else if(I!=="ping"){if(I==="approval_start"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};g(R)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,L=String(h.id),R=typeof h.title=="string"?h.title:void 0,q=h.file,$;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&($={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:L,artifactType:W,title:R,component:typeof h.component=="string"?h.component:void 0,...$?{file:$}:{}});let K=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(he.set(L,{markdown:"",title:R,file:$,...K?{props:K}:{}}),!we.has(L)){we.add(L);let ce=ho(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),je=typeof h.component=="string"?h.component:void 0,de={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:xs(ce,{artifactId:L,title:R,artifactType:W,status:"streaming",...$?{file:$}:{},...je?{component:je}:{}})};me.set(L,de),g(de)}}else if(I==="artifact_delta"){let W=String(h.id),L=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:L});let R=he.get(W);R&&(R.markdown+=L)}else if(I==="artifact_update"){let W=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:W,component:typeof h.component=="string"?h.component:void 0});let L=he.get(String(h.id));L&&(L.props={...L.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let L=me.get(W);if(L){L.streaming=!1;try{let R=JSON.parse(L.rawContent??"{}");if(R.props){R.props.status="complete";let q=he.get(W);q?.markdown&&(R.props.markdown=q.markdown),q?.file&&(R.props.file=q.file),R.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(R.props.componentProps=q.props)}L.rawContent=JSON.stringify(R)}catch{}he.delete(W),g(L),me.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let L=String(W.id??`msg-${c()}`),R=W.role,$={id:L,role:R==="user"?"user":R==="system"?"system":"assistant",content:typeof W.content=="string"?W.content:"",rawContent:typeof W.rawContent=="string"?W.rawContent:void 0,createdAt:typeof W.createdAt=="string"?W.createdAt:new Date().toISOString(),streaming:W.streaming===!0,...typeof W.variant=="string"?{variant:W.variant}:{},sequence:c()};if(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&we.add(ce)}catch{}v=null,T.current=null,_e.delete(L),Ae.delete(L)}else if(I==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let W=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(W)});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}else if(I==="step_error"||I==="dispatch_error"||I==="flow_error"){let W=null;if(h.error instanceof Error)W=h.error;else if(I==="dispatch_error"){let L=h.message??h.error;L!=null&&L!==""&&(W=new Error(String(L)))}else{let L=h.error;typeof L=="string"&&L!==""?W=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(W=new Error(String(L.message??L)))}if(W){n({type:"error",error:W});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:I}=await s.read();if(M)break;l+=a.decode(I,{stream:!0});let h=l.split(`
12
12
 
13
13
  `);l=h.pop()??"";for(let W of h){let L=W.split(`
14
14
  `),R="message",q="",$=null;for(let de of L)de.startsWith("event:")?R=de.replace("event:","").trim():de.startsWith("data:")?q+=de.replace("data:","").trim():de.startsWith("id:")&&($=de.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!q){K();continue}let ce;try{ce=JSON.parse(q)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let je=R!=="message"?R:ce.type??"message";if(this.onSSEEvent?.(je,ce),this.parseSSEEvent){T.current=v;let de=await this.handleCustomSSEEvent(ce,n,T,g,c,B);if(T.current&&T.current!==v&&(v=T.current),de){K();continue}}et.push({payloadType:je,payload:ce}),Le(),K()}}Le()}};function Ka(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function kr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ga="[Image]";function hu(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Lr(e){return{type:"text",text:e}}var yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Yh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Qn=[...yu,...Yh];function Xh(e){return yu.includes(e)||e.startsWith("image/")}function Ya(e){return Xh(e.type)}async function bu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ya(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function vu(e,t=Qn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Qh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function wu(e,t){let n=Qh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var xu=16e3,Jh=24e3,Zh=4096,ey=1380533830;function ty(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===ey?new Uint8Array(e,44):new Uint8Array(e)}function ny(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}`}var Ps=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:xu,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(f=>f.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:xu});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Mp(Jh);if(r!==this.callGeneration){u.destroy(),s.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${ny(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=f=>this.handleMessage(f,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=f=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(f.code!==1e3){let w=f.code?` (code ${f.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Zh,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let u=l.inputBuffer.getChannelData(0),d=new Int16Array(u.length);for(let c=0;c<u.length;c++){let f=Math.max(-1,Math.min(1,u[c]));d[c]=f<0?f*32768:f*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=ty(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Go=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Pr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ps(e.runtype);case"browser":if(!Go.isSupported())throw new Error("Browser speech recognition not supported");return new Go(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new 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 new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Cu(e){if(e?.type==="custom"&&e.custom)return Pr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Pr({type:"runtype",runtype:e.runtype});if(Go.isSupported())return Pr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function zl(e){try{return Cu(e),!0}catch{return!1}}function Xa(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Ir=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Xa(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Is=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function jl(e){if(!e)return"";let t=oy(e);return Au(t!==null?t:e)}function oy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Au(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
@@ -1052,6 +1052,7 @@ type RuntypeExecutionStreamEvent = ({
1052
1052
  iterations?: number;
1053
1053
  kind: "agent" | "flow";
1054
1054
  seq: number;
1055
+ stepErrorCount?: number;
1055
1056
  stopReason?: string;
1056
1057
  success: boolean;
1057
1058
  successfulSteps?: number;
@@ -1381,10 +1382,21 @@ type RuntypeExecutionStreamEvent = ({
1381
1382
  mode: "form" | "url";
1382
1383
  pauseCount?: number;
1383
1384
  requestedSchema?: Record<string, unknown>;
1385
+ requests?: Array<{
1386
+ message: string;
1387
+ mode: "form" | "url";
1388
+ name: string;
1389
+ requestedSchema?: Record<string, unknown>;
1390
+ url?: string;
1391
+ }>;
1384
1392
  serverName?: string;
1385
1393
  url?: string;
1386
1394
  };
1387
1395
  executionId: string;
1396
+ externalAgent?: {
1397
+ contextId?: string;
1398
+ taskId?: string;
1399
+ };
1388
1400
  origin?: "webmcp" | "sdk";
1389
1401
  pageOrigin?: string;
1390
1402
  parameters?: Record<string, unknown>;
@@ -1052,6 +1052,7 @@ type RuntypeExecutionStreamEvent = ({
1052
1052
  iterations?: number;
1053
1053
  kind: "agent" | "flow";
1054
1054
  seq: number;
1055
+ stepErrorCount?: number;
1055
1056
  stopReason?: string;
1056
1057
  success: boolean;
1057
1058
  successfulSteps?: number;
@@ -1381,10 +1382,21 @@ type RuntypeExecutionStreamEvent = ({
1381
1382
  mode: "form" | "url";
1382
1383
  pauseCount?: number;
1383
1384
  requestedSchema?: Record<string, unknown>;
1385
+ requests?: Array<{
1386
+ message: string;
1387
+ mode: "form" | "url";
1388
+ name: string;
1389
+ requestedSchema?: Record<string, unknown>;
1390
+ url?: string;
1391
+ }>;
1384
1392
  serverName?: string;
1385
1393
  url?: string;
1386
1394
  };
1387
1395
  executionId: string;
1396
+ externalAgent?: {
1397
+ contextId?: string;
1398
+ taskId?: string;
1399
+ };
1388
1400
  origin?: "webmcp" | "sdk";
1389
1401
  pageOrigin?: string;
1390
1402
  parameters?: Record<string, unknown>;
@@ -1,4 +1,4 @@
1
- var He=Object.defineProperty;var Fe=(e,t,r)=>t in e?He(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var T=(e,t,r)=>Fe(e,typeof t!="symbol"?t+"":t,r);function N(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(!N(e[i],t[i]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(let o of n)if(!N(e[o],t[o]))return!1;return!0}return e===t}function S(e){return encodeURI(Be(e))}function Be(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Ke={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ge={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ye={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Ze=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function O(e,t=Object.create(null),r=Ze,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let d=e.$id||e.id;if(d){let o=new URL(d,r.href);o.hash.length>1?t[o.href]=e:(o.hash="",n===""?r=o:O(e,t,r))}}else if(e!==!0&&e!==!1)return t;let i=r.href+(n?"#"+n:"");if(t[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let d=new URL(e.$ref,r.href);d.hash=d.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:d.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let d=new URL(e.$recursiveRef,r.href);d.hash=d.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:d.href})}if(e.$anchor){let d=new URL("#"+e.$anchor,r.href);t[d.href]=e}for(let d in e){if(Ye[d])continue;let o=`${n}/${S(d)}`,s=e[d];if(Array.isArray(s)){if(Ke[d]){let h=s.length;for(let b=0;b<h;b++)O(s[b],t,r,`${o}/${b}`)}}else if(Ge[d])for(let h in s)O(s[h],t,r,`${o}/${S(h)}`);else O(s,t,r,o)}return t}var Xe=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Qe=[0,31,28,31,30,31,30,31,31,30,31,30,31],Le=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,et=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,tt=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,rt=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,ot=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,nt=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,it=/^(?:\/(?:[^~/]|~0|~1)*)*$/,st=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,dt=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,at=e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},ft=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,lt=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,ut=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function _(e){return e.test.bind(e)}var me={date:Ee,time:Me.bind(void 0,!1),"date-time":pt,duration:ut,uri:$t,"uri-reference":_(tt),"uri-template":_(rt),url:_(ot),email:at,hostname:_(et),ipv4:_(ft),ipv6:_(lt),regex:wt,uuid:_(nt),"json-pointer":_(it),"json-pointer-uri-fragment":_(st),"relative-json-pointer":_(dt)};function mt(e){return e%4===0&&(e%100!==0||e%400===0)}function Ee(e){let t=e.match(Xe);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&mt(r)?29:Qe[n])}function Me(e,t){let r=t.match(Le);if(!r)return!1;let n=+r[1],i=+r[2],d=+r[3],o=!!r[5];return(n<=23&&i<=59&&d<=59||n==23&&i==59&&d==60)&&(!e||o)}var ct=/t|\s/i;function pt(e){let t=e.split(ct);return t.length==2&&Ee(t[0])&&Me(!0,t[1])}var yt=/\/|:/,ht=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function $t(e){return yt.test(e)&&ht.test(e)}var gt=/[^\\]\\Z/;function wt(e){if(gt.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var Ce;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(Ce||(Ce={}));function Ne(e){let t=0,r=e.length,n=0,i;for(;n<r;)t++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=e.charCodeAt(n),(i&64512)==56320&&n++);return t}function w(e,t,r="2019-09",n=O(t),i=!0,d=null,o="#",s="#",h=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:"false",keywordLocation:o,error:"False boolean schema."}]};let b=typeof e,$;switch(b){case"boolean":case"number":case"string":$=b;break;case"object":e===null?$="null":Array.isArray(e)?$="array":$="object";break;default:throw new Error(`Instances of "${b}" type are not supported.`)}let{$ref:E,$recursiveRef:W,$recursiveAnchor:q,type:I,const:j,enum:z,required:ye,not:he,anyOf:ee,allOf:te,oneOf:$e,if:ge,then:we,else:xe,format:U,properties:re,patternProperties:oe,additionalProperties:be,unevaluatedProperties:ve,minProperties:ne,maxProperties:ie,propertyNames:Se,dependentRequired:se,dependentSchemas:de,dependencies:ae,prefixItems:fe,items:D,additionalItems:Te,unevaluatedItems:Ie,contains:_e,minContains:P,maxContains:V,minItems:le,maxItems:ue,uniqueItems:Ue,minimum:M,maximum:C,exclusiveMinimum:R,exclusiveMaximum:J,multipleOf:H,minLength:F,maxLength:B,pattern:ke,__absolute_ref__:K,__absolute_recursive_ref__:Ve}=t,f=[];if(q===!0&&d===null&&(d=t),W==="#"){let m=d===null?n[Ve]:d,u=`${s}/$recursiveRef`,y=w(e,d===null?t:d,r,n,i,m,o,u,h);y.valid||f.push({instanceLocation:o,keyword:"$recursiveRef",keywordLocation:u,error:"A subschema had errors."},...y.errors)}if(E!==void 0){let u=n[K||E];if(u===void 0){let a=`Unresolved $ref "${E}".`;throw K&&K!==E&&(a+=` Absolute URI "${K}".`),a+=`
1
+ var Ge=Object.defineProperty;var Ye=(e,t,r)=>t in e?Ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var I=(e,t,r)=>Ye(e,typeof t!="symbol"?t+"":t,r);function A(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(!A(e[i],t[i]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(let o of n)if(!A(e[o],t[o]))return!1;return!0}return e===t}function T(e){return encodeURI(Qe(e))}function Qe(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Ze={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Xe={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Le={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},et=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function k(e,t=Object.create(null),r=et,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let d=e.$id||e.id;if(d){let o=new URL(d,r.href);o.hash.length>1?t[o.href]=e:(o.hash="",n===""?r=o:k(e,t,r))}}else if(e!==!0&&e!==!1)return t;let i=r.href+(n?"#"+n:"");if(t[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let d=new URL(e.$ref,r.href);d.hash=d.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:d.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let d=new URL(e.$recursiveRef,r.href);d.hash=d.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:d.href})}if(e.$anchor){let d=new URL("#"+e.$anchor,r.href);t[d.href]=e}for(let d in e){if(Le[d])continue;let o=`${n}/${T(d)}`,s=e[d];if(Array.isArray(s)){if(Ze[d]){let h=s.length;for(let b=0;b<h;b++)k(s[b],t,r,`${o}/${b}`)}}else if(Xe[d])for(let h in s)k(s[h],t,r,`${o}/${T(h)}`);else k(s,t,r,o)}return t}var tt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,rt=[0,31,28,31,30,31,30,31,31,30,31,30,31],ot=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,nt=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,it=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,st=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,dt=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,at=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,lt=/^(?:\/(?:[^~/]|~0|~1)*)*$/,ft=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ut=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ct=e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},mt=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,pt=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,yt=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function _(e){return e.test.bind(e)}var ce={date:Me,time:Ce.bind(void 0,!1),"date-time":gt,duration:yt,uri:bt,"uri-reference":_(it),"uri-template":_(st),url:_(dt),email:ct,hostname:_(nt),ipv4:_(mt),ipv6:_(pt),regex:St,uuid:_(at),"json-pointer":_(lt),"json-pointer-uri-fragment":_(ft),"relative-json-pointer":_(ut)};function ht(e){return e%4===0&&(e%100!==0||e%400===0)}function Me(e){let t=e.match(tt);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&ht(r)?29:rt[n])}function Ce(e,t){let r=t.match(ot);if(!r)return!1;let n=+r[1],i=+r[2],d=+r[3],o=!!r[5];return(n<=23&&i<=59&&d<=59||n==23&&i==59&&d==60)&&(!e||o)}var $t=/t|\s/i;function gt(e){let t=e.split($t);return t.length==2&&Me(t[0])&&Ce(!0,t[1])}var wt=/\/|:/,xt=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function bt(e){return wt.test(e)&&xt.test(e)}var vt=/[^\\]\\Z/;function St(e){if(vt.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var Ne;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(Ne||(Ne={}));function Ae(e){let t=0,r=e.length,n=0,i;for(;n<r;)t++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=e.charCodeAt(n),(i&64512)==56320&&n++);return t}function w(e,t,r="2019-09",n=k(t),i=!0,d=null,o="#",s="#",h=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:"false",keywordLocation:o,error:"False boolean schema."}]};let b=typeof e,$;switch(b){case"boolean":case"number":case"string":$=b;break;case"object":e===null?$="null":Array.isArray(e)?$="array":$="object";break;default:throw new Error(`Instances of "${b}" type are not supported.`)}let{$ref:P,$recursiveRef:W,$recursiveAnchor:M,type:S,const:z,enum:D,required:he,not:$e,anyOf:ee,allOf:te,oneOf:ge,if:we,then:xe,else:be,format:q,properties:re,patternProperties:oe,additionalProperties:ve,unevaluatedProperties:Se,minProperties:ne,maxProperties:ie,propertyNames:Ie,dependentRequired:se,dependentSchemas:de,dependencies:ae,prefixItems:le,items:R,additionalItems:Te,unevaluatedItems:_e,contains:Oe,minContains:E,maxContains:U,minItems:fe,maxItems:ue,uniqueItems:Be,minimum:C,maximum:N,exclusiveMinimum:J,exclusiveMaximum:V,multipleOf:H,minLength:F,maxLength:B,pattern:Ee,__absolute_ref__:K,__absolute_recursive_ref__:Ke}=t,l=[];if(M===!0&&d===null&&(d=t),W==="#"){let c=d===null?n[Ke]:d,u=`${s}/$recursiveRef`,y=w(e,d===null?t:d,r,n,i,c,o,u,h);y.valid||l.push({instanceLocation:o,keyword:"$recursiveRef",keywordLocation:u,error:"A subschema had errors."},...y.errors)}if(P!==void 0){let u=n[K||P];if(u===void 0){let a=`Unresolved $ref "${P}".`;throw K&&K!==P&&(a+=` Absolute URI "${K}".`),a+=`
2
2
  Known schemas:
3
3
  - ${Object.keys(n).join(`
4
- - `)}`,new Error(a)}let y=`${s}/$ref`,l=w(e,u,r,n,i,d,o,y,h);if(l.valid||f.push({instanceLocation:o,keyword:"$ref",keywordLocation:y,error:"A subschema had errors."},...l.errors),r==="4"||r==="7")return{valid:f.length===0,errors:f}}if(Array.isArray(I)){let m=I.length,u=!1;for(let y=0;y<m;y++)if($===I[y]||I[y]==="integer"&&$==="number"&&e%1===0&&e===e){u=!0;break}u||f.push({instanceLocation:o,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${$}" is invalid. Expected "${I.join('", "')}".`})}else I==="integer"?($!=="number"||e%1||e!==e)&&f.push({instanceLocation:o,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${$}" is invalid. Expected "${I}".`}):I!==void 0&&$!==I&&f.push({instanceLocation:o,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${$}" is invalid. Expected "${I}".`});if(j!==void 0&&($==="object"||$==="array"?N(e,j)||f.push({instanceLocation:o,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(j)}.`}):e!==j&&f.push({instanceLocation:o,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(j)}.`})),z!==void 0&&($==="object"||$==="array"?z.some(m=>N(e,m))||f.push({instanceLocation:o,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(z)}.`}):z.some(m=>e===m)||f.push({instanceLocation:o,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(z)}.`})),he!==void 0){let m=`${s}/not`;w(e,he,r,n,i,d,o,m).valid&&f.push({instanceLocation:o,keyword:"not",keywordLocation:m,error:'Instance matched "not" schema.'})}let G=[];if(ee!==void 0){let m=`${s}/anyOf`,u=f.length,y=!1;for(let l=0;l<ee.length;l++){let a=ee[l],p=Object.create(h),c=w(e,a,r,n,i,q===!0?d:null,o,`${m}/${l}`,p);f.push(...c.errors),y=y||c.valid,c.valid&&G.push(p)}y?f.length=u:f.splice(u,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:m,error:"Instance does not match any subschemas."})}if(te!==void 0){let m=`${s}/allOf`,u=f.length,y=!0;for(let l=0;l<te.length;l++){let a=te[l],p=Object.create(h),c=w(e,a,r,n,i,q===!0?d:null,o,`${m}/${l}`,p);f.push(...c.errors),y=y&&c.valid,c.valid&&G.push(p)}y?f.length=u:f.splice(u,0,{instanceLocation:o,keyword:"allOf",keywordLocation:m,error:"Instance does not match every subschema."})}if($e!==void 0){let m=`${s}/oneOf`,u=f.length,y=$e.filter((l,a)=>{let p=Object.create(h),c=w(e,l,r,n,i,q===!0?d:null,o,`${m}/${a}`,p);return f.push(...c.errors),c.valid&&G.push(p),c.valid}).length;y===1?f.length=u:f.splice(u,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:m,error:`Instance does not match exactly one subschema (${y} matches).`})}if(($==="object"||$==="array")&&Object.assign(h,...G),ge!==void 0){let m=`${s}/if`;if(w(e,ge,r,n,i,d,o,m,h).valid){if(we!==void 0){let y=w(e,we,r,n,i,d,o,`${s}/then`,h);y.valid||f.push({instanceLocation:o,keyword:"if",keywordLocation:m,error:'Instance does not match "then" schema.'},...y.errors)}}else if(xe!==void 0){let y=w(e,xe,r,n,i,d,o,`${s}/else`,h);y.valid||f.push({instanceLocation:o,keyword:"if",keywordLocation:m,error:'Instance does not match "else" schema.'},...y.errors)}}if($==="object"){if(ye!==void 0)for(let l of ye)l in e||f.push({instanceLocation:o,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${l}".`});let m=Object.keys(e);if(ne!==void 0&&m.length<ne&&f.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${ne} properties.`}),ie!==void 0&&m.length>ie&&f.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${ie} properties.`}),Se!==void 0){let l=`${s}/propertyNames`;for(let a in e){let p=`${o}/${S(a)}`,c=w(a,Se,r,n,i,d,p,l);c.valid||f.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:l,error:`Property name "${a}" does not match schema.`},...c.errors)}}if(se!==void 0){let l=`${s}/dependantRequired`;for(let a in se)if(a in e){let p=se[a];for(let c of p)c in e||f.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:l,error:`Instance has "${a}" but does not have "${c}".`})}}if(de!==void 0)for(let l in de){let a=`${s}/dependentSchemas`;if(l in e){let p=w(e,de[l],r,n,i,d,o,`${a}/${S(l)}`,h);p.valid||f.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:a,error:`Instance has "${l}" but does not match dependant schema.`},...p.errors)}}if(ae!==void 0){let l=`${s}/dependencies`;for(let a in ae)if(a in e){let p=ae[a];if(Array.isArray(p))for(let c of p)c in e||f.push({instanceLocation:o,keyword:"dependencies",keywordLocation:l,error:`Instance has "${a}" but does not have "${c}".`});else{let c=w(e,p,r,n,i,d,o,`${l}/${S(a)}`);c.valid||f.push({instanceLocation:o,keyword:"dependencies",keywordLocation:l,error:`Instance has "${a}" but does not match dependant schema.`},...c.errors)}}}let u=Object.create(null),y=!1;if(re!==void 0){let l=`${s}/properties`;for(let a in re){if(!(a in e))continue;let p=`${o}/${S(a)}`,c=w(e[a],re[a],r,n,i,d,p,`${l}/${S(a)}`);if(c.valid)h[a]=u[a]=!0;else if(y=i,f.push({instanceLocation:o,keyword:"properties",keywordLocation:l,error:`Property "${a}" does not match schema.`},...c.errors),y)break}}if(!y&&oe!==void 0){let l=`${s}/patternProperties`;for(let a in oe){let p=new RegExp(a,"u"),c=oe[a];for(let v in e){if(!p.test(v))continue;let Pe=`${o}/${S(v)}`,Oe=w(e[v],c,r,n,i,d,Pe,`${l}/${S(a)}`);Oe.valid?h[v]=u[v]=!0:(y=i,f.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:l,error:`Property "${v}" matches pattern "${a}" but does not match associated schema.`},...Oe.errors))}}}if(!y&&be!==void 0){let l=`${s}/additionalProperties`;for(let a in e){if(u[a])continue;let p=`${o}/${S(a)}`,c=w(e[a],be,r,n,i,d,p,l);c.valid?h[a]=!0:(y=i,f.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:l,error:`Property "${a}" does not match additional properties schema.`},...c.errors))}}else if(!y&&ve!==void 0){let l=`${s}/unevaluatedProperties`;for(let a in e)if(!h[a]){let p=`${o}/${S(a)}`,c=w(e[a],ve,r,n,i,d,p,l);c.valid?h[a]=!0:f.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:l,error:`Property "${a}" does not match unevaluated properties schema.`},...c.errors)}}}else if($==="array"){ue!==void 0&&e.length>ue&&f.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${ue}).`}),le!==void 0&&e.length<le&&f.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${le}).`});let m=e.length,u=0,y=!1;if(fe!==void 0){let l=`${s}/prefixItems`,a=Math.min(fe.length,m);for(;u<a;u++){let p=w(e[u],fe[u],r,n,i,d,`${o}/${u}`,`${l}/${u}`);if(h[u]=!0,!p.valid&&(y=i,f.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:l,error:"Items did not match schema."},...p.errors),y))break}}if(D!==void 0){let l=`${s}/items`;if(Array.isArray(D)){let a=Math.min(D.length,m);for(;u<a;u++){let p=w(e[u],D[u],r,n,i,d,`${o}/${u}`,`${l}/${u}`);if(h[u]=!0,!p.valid&&(y=i,f.push({instanceLocation:o,keyword:"items",keywordLocation:l,error:"Items did not match schema."},...p.errors),y))break}}else for(;u<m;u++){let a=w(e[u],D,r,n,i,d,`${o}/${u}`,l);if(h[u]=!0,!a.valid&&(y=i,f.push({instanceLocation:o,keyword:"items",keywordLocation:l,error:"Items did not match schema."},...a.errors),y))break}if(!y&&Te!==void 0){let a=`${s}/additionalItems`;for(;u<m;u++){let p=w(e[u],Te,r,n,i,d,`${o}/${u}`,a);h[u]=!0,p.valid||(y=i,f.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:a,error:"Items did not match additional items schema."},...p.errors))}}}if(_e!==void 0)if(m===0&&P===void 0)f.push({instanceLocation:o,keyword:"contains",keywordLocation:`${s}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(P!==void 0&&m<P)f.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${s}/minContains`,error:`Array has less items (${m}) than minContains (${P}).`});else{let l=`${s}/contains`,a=f.length,p=0;for(let c=0;c<m;c++){let v=w(e[c],_e,r,n,i,d,`${o}/${c}`,l);v.valid?(h[c]=!0,p++):f.push(...v.errors)}p>=(P||0)&&(f.length=a),P===void 0&&V===void 0&&p===0?f.splice(a,0,{instanceLocation:o,keyword:"contains",keywordLocation:l,error:"Array does not contain item matching schema."}):P!==void 0&&p<P?f.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${s}/minContains`,error:`Array must contain at least ${P} items matching schema. Only ${p} items were found.`}):V!==void 0&&p>V&&f.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${V} items matching schema. ${p} items were found.`})}if(!y&&Ie!==void 0){let l=`${s}/unevaluatedItems`;for(u;u<m;u++){if(h[u])continue;let a=w(e[u],Ie,r,n,i,d,`${o}/${u}`,l);h[u]=!0,a.valid||f.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:l,error:"Items did not match unevaluated items schema."},...a.errors)}}if(Ue)for(let l=0;l<m;l++){let a=e[l],p=typeof a=="object"&&a!==null;for(let c=0;c<m;c++){if(l===c)continue;let v=e[c];(a===v||p&&(typeof v=="object"&&v!==null)&&N(a,v))&&(f.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${l} and ${c}.`}),l=Number.MAX_SAFE_INTEGER,c=Number.MAX_SAFE_INTEGER)}}}else if($==="number"){if(r==="4"?(M!==void 0&&(R===!0&&e<=M||e<M)&&f.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${s}/minimum`,error:`${e} is less than ${R?"or equal to ":""} ${M}.`}),C!==void 0&&(J===!0&&e>=C||e>C)&&f.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${s}/maximum`,error:`${e} is greater than ${J?"or equal to ":""} ${C}.`})):(M!==void 0&&e<M&&f.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${s}/minimum`,error:`${e} is less than ${M}.`}),C!==void 0&&e>C&&f.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${s}/maximum`,error:`${e} is greater than ${C}.`}),R!==void 0&&e<=R&&f.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${R}.`}),J!==void 0&&e>=J&&f.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${J}.`})),H!==void 0){let m=e%H;Math.abs(0-m)>=11920929e-14&&Math.abs(H-m)>=11920929e-14&&f.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${H}.`})}}else if($==="string"){let m=F===void 0&&B===void 0?0:Ne(e);F!==void 0&&m<F&&f.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${s}/minLength`,error:`String is too short (${m} < ${F}).`}),B!==void 0&&m>B&&f.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${s}/maxLength`,error:`String is too long (${m} > ${B}).`}),ke!==void 0&&!new RegExp(ke,"u").test(e)&&f.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${s}/pattern`,error:"String does not match pattern."}),U!==void 0&&me[U]&&!me[U](e)&&f.push({instanceLocation:o,keyword:"format",keywordLocation:`${s}/format`,error:`String does not match format "${U}".`})}return{valid:f.length===0,errors:f}}var Y=class{constructor(t,r="2019-09",n=!0){T(this,"schema");T(this,"draft");T(this,"shortCircuit");T(this,"lookup");this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=O(t)}validate(t){return w(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),O(t,this.lookup)}};var Ae="Failed to parse input arguments",Q="Tool was executed but the invocation failed. For example, the script function threw an error",ce="Tool was cancelled",Z={type:"object",properties:{}},xt=["draft-2020-12","draft-07"],bt="__isWebMCPPolyfill",ze=Symbol("standardValidator"),g={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},vt=class extends EventTarget{constructor(){super(...arguments);T(this,"tools",new Map);T(this,"testingShim",null);T(this,"_ontoolchange",null);T(this,"unregisterToolDeprecationWarned",!1)}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerTool(t,r){let n=r?.signal;if(n?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${t?.name??"<unknown>"}") skipped: options.signal was already aborted.`);return}let i=Et(t,this.tools);this.tools.set(i.name,i),this.notifyToolsChanged(),n&&n.addEventListener("abort",()=>{this.tools.delete(i.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(t){this.warnUnregisterToolDeprecationOnce();let r=It(t);this.tools.delete(r)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(t,r,n){return this.executeToolByName(t.name,r,n,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new St(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(t=>{let r;try{r=JSON.stringify(t.inputSchema??{type:"object"})}catch{r='{"type":"object"}'}return{name:t.name,description:t.description,inputSchema:r}})}getRegisteredToolInfos(){return this.getToolInfos().map(t=>{let r=this.tools.get(t.name);return{...t,title:r?.title??"",origin:globalThis.location?.origin??"",window:globalThis.window}})}async executeToolForTesting(t,r,n){return this.executeToolByName(t,r,n,!0)}async executeToolByName(t,r,n,i){if(n?.signal?.aborted)throw k(ce);let d=this.tools.get(t);if(!d)throw k(`Tool not found: ${t}`);let o=Tt(r),s=await At(o,d);if(s)throw k(s);let h=!0,b={requestUserInteraction:async $=>{if(!h)throw new Error(`ModelContextClient for tool "${t}" is no longer active after execute() resolved`);if(typeof $!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return $()}};try{let $=d.execute(o,b),E=await Ut(Promise.resolve($),n?.signal);if(i)return qt(Jt(E));let W=JSON.stringify(E);return W===void 0?null:W}catch($){throw k($ instanceof Error?`${Q}: ${$.message}`:Q)}finally{h=!1}}notifyToolsChanged(){queueMicrotask(()=>{let t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(r){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",r)}this.dispatchEvent(t),this.testingShim?.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) \u2014 pass an AbortSignal and abort it to unregister."))}},St=class extends EventTarget{constructor(t){super();T(this,"context");T(this,"_ontoolchange",null);this.context=t}listTools(){return this.context.getToolInfos()}executeTool(t,r,n){return this.context.executeToolForTesting(t,r,n)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerToolsChangedCallback(t){if(typeof t!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",t)}dispatchToolChange(){let t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(r){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",r)}this.dispatchEvent(t),this.dispatchEvent(new Event("toolschanged"))}};function k(e){try{return new DOMException(e,"UnknownError")}catch{let t=new Error(e);return t.name="UnknownError",t}}function Tt(e){let t;try{t=JSON.parse(e)}catch{throw k(Ae)}if(!t||typeof t!="object"||Array.isArray(t))throw k(Ae);return t}function It(e){if(typeof e=="string")return e;if(x(e)&&typeof e.name=="string")return e.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function x(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function De(e){if(!x(e))return null;let t=e["~standard"];return x(t)?t:null}function _t(e){let t=De(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function kt(e){let t=De(e);return!t||t.version!==1||!x(t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function X(e){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(t){if(!x(t))return{issues:[{message:"expected object arguments"}]};let r=Mt(t,e);return r?{issues:[r]}:{value:t}}}}}function Pt(e){for(let t of xt)try{let r=e["~standard"].jsonSchema.input({target:t});return Re(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function Ot(e){if(e===void 0){let r=Z;return{inputSchema:r,standardValidator:X(r)}}if(kt(e)){let r=Pt(e);return{inputSchema:r,standardValidator:X(r)}}if(_t(e))return{inputSchema:Z,standardValidator:e};if(Re(e),Object.keys(e).length===0)return{inputSchema:Z,standardValidator:X(Z)};let t=e.type===void 0?{type:"object",...e}:e;return{inputSchema:t,standardValidator:X(t)}}function Re(e){if(!x(e))throw new Error("inputSchema must be a JSON Schema object");A(e,"$")}function A(e,t){let r=e.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(s=>typeof s=="string"&&s.length>0)))throw new Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);let n=e.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(s=>typeof s=="string")))throw new Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);let i=e.properties;if(i!==void 0){if(!x(i))throw new Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[s,h]of Object.entries(i)){if(!x(h))throw new Error(`Invalid JSON Schema at ${t}.properties.${s}: expected object schema`);A(h,`${t}.properties.${s}`)}}let d=e.items;if(d!==void 0)if(Array.isArray(d))for(let[s,h]of d.entries()){if(!x(h))throw new Error(`Invalid JSON Schema at ${t}.items[${s}]: expected object schema`);A(h,`${t}.items[${s}]`)}else if(x(d))A(d,`${t}.items`);else throw new Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(let s of["allOf","anyOf","oneOf"]){let h=e[s];if(h!==void 0){if(!Array.isArray(h))throw new Error(`Invalid JSON Schema at ${t}: "${s}" must be an array`);for(let[b,$]of h.entries()){if(!x($))throw new Error(`Invalid JSON Schema at ${t}.${s}[${b}]: expected object schema`);A($,`${t}.${s}[${b}]`)}}}let o=e.not;if(o!==void 0){if(!x(o))throw new Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);A(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw new Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function Et(e,t){if(!e||typeof e!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof e.name!="string"||e.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof e.description!="string"||e.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof e.execute!="function")throw new TypeError('Tool "execute" must be a function');if(t.has(e.name))throw new Error(`Tool already registered: ${e.name}`);let r=Ot(e.inputSchema),n=e.annotations,i=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...e,...i?{annotations:i}:{},inputSchema:r.inputSchema,[ze]:r.standardValidator}}function Mt(e,t){let r=new Y(t,"2020-12",!0).validate(e);if(r.valid)return null;let n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function Ct(e){if(!e||e.length===0)return null;let t=e.map(r=>x(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return t.length===0?null:t.join(".")}async function Nt(e,t){let r;try{r=await Promise.resolve(t["~standard"].validate(e))}catch(d){let o=d instanceof Error?`: ${d.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",d),`Input validation error: schema validation failed${o}`}if(!r.issues||r.issues.length===0)return null;let n=r.issues[0];if(!n)return"Input validation error";let i=Ct(n?.path);return i?`Input validation error: ${n.message} at ${i}`:`Input validation error: ${n.message}`}async function At(e,t){return Nt(e,t[ze])}function jt(e){return x(e)&&Array.isArray(e.content)}function zt(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function pe(e){return zt(e)?Number.isFinite(e)||typeof e!="number":Array.isArray(e)?e.every(t=>pe(t)):x(e)?Object.values(e).every(t=>pe(t)):!1}function Dt(e){if(!(!x(e)||!pe(e)))return e}function Rt(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Jt(e){if(jt(e))return e;let t=Dt(e);return{content:[{type:"text",text:Rt(e)}],...t?{structuredContent:t}:{},isError:!1}}function Wt(e){for(let t of e.content??[])if(t.type==="text"&&"text"in t&&typeof t.text=="string")return t.text;return null}function qt(e){if(e.isError)throw k(Wt(e)?.replace(/^Error:\s*/i,"").trim()||Q);let t=e.metadata;if(t&&typeof t=="object"&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw k(Q)}}function Ut(e,t){return t?t.aborted?Promise.reject(k(ce)):new Promise((r,n)=>{let i=()=>{d(),n(k(ce))},d=()=>{t.removeEventListener("abort",i)};t.addEventListener("abort",i,{once:!0}),e.then(o=>{d(),r(o)},o=>{d(),n(o)})}):e}function Je(){return typeof navigator<"u"?navigator:null}function We(){return typeof document<"u"?document:null}function Vt(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:r})}function je(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:t})}var L=!1;function Ht(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get(){return L||(L=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document \u2014 use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),t}})}function qe(e){let t=Je(),r=We();if(!t&&!r||r?.modelContext)return;let i=t?.modelContext,d=!!i;if(g.installed&&Ft(),r&&i){g.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),je(r,i),g.installedDocumentModelContext=!0,g.installed=!0;return}if(d)return;let o=new vt,s=o;if(s[bt]=!0,r&&(g.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),je(r,s),g.installedDocumentModelContext=!0),t){g.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(t,"modelContext"),g.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,"modelContextTesting"),L=!1,Ht(t,s),g.installedNavigatorModelContext=!0;let h=e?.installTestingShim??"if-missing",b=!!t.modelContextTesting;(h==="always"||(h===!0||h==="if-missing")&&!b)&&(Vt(t,"modelContextTesting",o.getTestingShim()),g.installedNavigatorModelContextTesting=!0)}g.installed=!0}function Ft(){if(!g.installed)return;let e=(n,i,d)=>{if(d){Object.defineProperty(n,i,d);return}delete n[i]},t=Je(),r=We();r&&g.installedDocumentModelContext&&e(r,"modelContext",g.previousDocumentModelContextDescriptor),t&&g.installedNavigatorModelContext&&e(t,"modelContext",g.previousNavigatorModelContextDescriptor),t&&g.installedNavigatorModelContextTesting&&e(t,"modelContextTesting",g.previousNavigatorModelContextTestingDescriptor),g.installed=!1,g.previousDocumentModelContextDescriptor=void 0,g.previousNavigatorModelContextDescriptor=void 0,g.previousNavigatorModelContextTestingDescriptor=void 0,g.installedDocumentModelContext=!1,g.installedNavigatorModelContext=!1,g.installedNavigatorModelContextTesting=!1,L=!1}if(typeof window<"u"&&typeof document<"u"){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{qe(e)}catch(t){console.error("[WebMCPPolyfill] Auto-initialization failed:",t)}}export{qe as initializeWebMCPPolyfill};
4
+ - `)}`,new Error(a)}let y=`${s}/$ref`,f=w(e,u,r,n,i,d,o,y,h);if(f.valid||l.push({instanceLocation:o,keyword:"$ref",keywordLocation:y,error:"A subschema had errors."},...f.errors),r==="4"||r==="7")return{valid:l.length===0,errors:l}}if(Array.isArray(S)){let c=S.length,u=!1;for(let y=0;y<c;y++)if($===S[y]||S[y]==="integer"&&$==="number"&&e%1===0&&e===e){u=!0;break}u||l.push({instanceLocation:o,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${$}" is invalid. Expected "${S.join('", "')}".`})}else S==="integer"?($!=="number"||e%1||e!==e)&&l.push({instanceLocation:o,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${$}" is invalid. Expected "${S}".`}):S!==void 0&&$!==S&&l.push({instanceLocation:o,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${$}" is invalid. Expected "${S}".`});if(z!==void 0&&($==="object"||$==="array"?A(e,z)||l.push({instanceLocation:o,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(z)}.`}):e!==z&&l.push({instanceLocation:o,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(z)}.`})),D!==void 0&&($==="object"||$==="array"?D.some(c=>A(e,c))||l.push({instanceLocation:o,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(D)}.`}):D.some(c=>e===c)||l.push({instanceLocation:o,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(D)}.`})),$e!==void 0){let c=`${s}/not`;w(e,$e,r,n,i,d,o,c).valid&&l.push({instanceLocation:o,keyword:"not",keywordLocation:c,error:'Instance matched "not" schema.'})}let G=[];if(ee!==void 0){let c=`${s}/anyOf`,u=l.length,y=!1;for(let f=0;f<ee.length;f++){let a=ee[f],p=Object.create(h),m=w(e,a,r,n,i,M===!0?d:null,o,`${c}/${f}`,p);l.push(...m.errors),y=y||m.valid,m.valid&&G.push(p)}y?l.length=u:l.splice(u,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:c,error:"Instance does not match any subschemas."})}if(te!==void 0){let c=`${s}/allOf`,u=l.length,y=!0;for(let f=0;f<te.length;f++){let a=te[f],p=Object.create(h),m=w(e,a,r,n,i,M===!0?d:null,o,`${c}/${f}`,p);l.push(...m.errors),y=y&&m.valid,m.valid&&G.push(p)}y?l.length=u:l.splice(u,0,{instanceLocation:o,keyword:"allOf",keywordLocation:c,error:"Instance does not match every subschema."})}if(ge!==void 0){let c=`${s}/oneOf`,u=l.length,y=ge.filter((f,a)=>{let p=Object.create(h),m=w(e,f,r,n,i,M===!0?d:null,o,`${c}/${a}`,p);return l.push(...m.errors),m.valid&&G.push(p),m.valid}).length;y===1?l.length=u:l.splice(u,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:c,error:`Instance does not match exactly one subschema (${y} matches).`})}if(($==="object"||$==="array")&&Object.assign(h,...G),we!==void 0){let c=`${s}/if`;if(w(e,we,r,n,i,d,o,c,h).valid){if(xe!==void 0){let y=w(e,xe,r,n,i,d,o,`${s}/then`,h);y.valid||l.push({instanceLocation:o,keyword:"if",keywordLocation:c,error:'Instance does not match "then" schema.'},...y.errors)}}else if(be!==void 0){let y=w(e,be,r,n,i,d,o,`${s}/else`,h);y.valid||l.push({instanceLocation:o,keyword:"if",keywordLocation:c,error:'Instance does not match "else" schema.'},...y.errors)}}if($==="object"){if(he!==void 0)for(let f of he)f in e||l.push({instanceLocation:o,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${f}".`});let c=Object.keys(e);if(ne!==void 0&&c.length<ne&&l.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${ne} properties.`}),ie!==void 0&&c.length>ie&&l.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${ie} properties.`}),Ie!==void 0){let f=`${s}/propertyNames`;for(let a in e){let p=`${o}/${T(a)}`,m=w(a,Ie,r,n,i,d,p,f);m.valid||l.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:f,error:`Property name "${a}" does not match schema.`},...m.errors)}}if(se!==void 0){let f=`${s}/dependantRequired`;for(let a in se)if(a in e){let p=se[a];for(let m of p)m in e||l.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:f,error:`Instance has "${a}" but does not have "${m}".`})}}if(de!==void 0)for(let f in de){let a=`${s}/dependentSchemas`;if(f in e){let p=w(e,de[f],r,n,i,d,o,`${a}/${T(f)}`,h);p.valid||l.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:a,error:`Instance has "${f}" but does not match dependant schema.`},...p.errors)}}if(ae!==void 0){let f=`${s}/dependencies`;for(let a in ae)if(a in e){let p=ae[a];if(Array.isArray(p))for(let m of p)m in e||l.push({instanceLocation:o,keyword:"dependencies",keywordLocation:f,error:`Instance has "${a}" but does not have "${m}".`});else{let m=w(e,p,r,n,i,d,o,`${f}/${T(a)}`);m.valid||l.push({instanceLocation:o,keyword:"dependencies",keywordLocation:f,error:`Instance has "${a}" but does not match dependant schema.`},...m.errors)}}}let u=Object.create(null),y=!1;if(re!==void 0){let f=`${s}/properties`;for(let a in re){if(!(a in e))continue;let p=`${o}/${T(a)}`,m=w(e[a],re[a],r,n,i,d,p,`${f}/${T(a)}`);if(m.valid)h[a]=u[a]=!0;else if(y=i,l.push({instanceLocation:o,keyword:"properties",keywordLocation:f,error:`Property "${a}" does not match schema.`},...m.errors),y)break}}if(!y&&oe!==void 0){let f=`${s}/patternProperties`;for(let a in oe){let p=new RegExp(a,"u"),m=oe[a];for(let v in e){if(!p.test(v))continue;let ke=`${o}/${T(v)}`,Pe=w(e[v],m,r,n,i,d,ke,`${f}/${T(a)}`);Pe.valid?h[v]=u[v]=!0:(y=i,l.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:f,error:`Property "${v}" matches pattern "${a}" but does not match associated schema.`},...Pe.errors))}}}if(!y&&ve!==void 0){let f=`${s}/additionalProperties`;for(let a in e){if(u[a])continue;let p=`${o}/${T(a)}`,m=w(e[a],ve,r,n,i,d,p,f);m.valid?h[a]=!0:(y=i,l.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:f,error:`Property "${a}" does not match additional properties schema.`},...m.errors))}}else if(!y&&Se!==void 0){let f=`${s}/unevaluatedProperties`;for(let a in e)if(!h[a]){let p=`${o}/${T(a)}`,m=w(e[a],Se,r,n,i,d,p,f);m.valid?h[a]=!0:l.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:f,error:`Property "${a}" does not match unevaluated properties schema.`},...m.errors)}}}else if($==="array"){ue!==void 0&&e.length>ue&&l.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${ue}).`}),fe!==void 0&&e.length<fe&&l.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${fe}).`});let c=e.length,u=0,y=!1;if(le!==void 0){let f=`${s}/prefixItems`,a=Math.min(le.length,c);for(;u<a;u++){let p=w(e[u],le[u],r,n,i,d,`${o}/${u}`,`${f}/${u}`);if(h[u]=!0,!p.valid&&(y=i,l.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:f,error:"Items did not match schema."},...p.errors),y))break}}if(R!==void 0){let f=`${s}/items`;if(Array.isArray(R)){let a=Math.min(R.length,c);for(;u<a;u++){let p=w(e[u],R[u],r,n,i,d,`${o}/${u}`,`${f}/${u}`);if(h[u]=!0,!p.valid&&(y=i,l.push({instanceLocation:o,keyword:"items",keywordLocation:f,error:"Items did not match schema."},...p.errors),y))break}}else for(;u<c;u++){let a=w(e[u],R,r,n,i,d,`${o}/${u}`,f);if(h[u]=!0,!a.valid&&(y=i,l.push({instanceLocation:o,keyword:"items",keywordLocation:f,error:"Items did not match schema."},...a.errors),y))break}if(!y&&Te!==void 0){let a=`${s}/additionalItems`;for(;u<c;u++){let p=w(e[u],Te,r,n,i,d,`${o}/${u}`,a);h[u]=!0,p.valid||(y=i,l.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:a,error:"Items did not match additional items schema."},...p.errors))}}}if(Oe!==void 0)if(c===0&&E===void 0)l.push({instanceLocation:o,keyword:"contains",keywordLocation:`${s}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(E!==void 0&&c<E)l.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${s}/minContains`,error:`Array has less items (${c}) than minContains (${E}).`});else{let f=`${s}/contains`,a=l.length,p=0;for(let m=0;m<c;m++){let v=w(e[m],Oe,r,n,i,d,`${o}/${m}`,f);v.valid?(h[m]=!0,p++):l.push(...v.errors)}p>=(E||0)&&(l.length=a),E===void 0&&U===void 0&&p===0?l.splice(a,0,{instanceLocation:o,keyword:"contains",keywordLocation:f,error:"Array does not contain item matching schema."}):E!==void 0&&p<E?l.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${s}/minContains`,error:`Array must contain at least ${E} items matching schema. Only ${p} items were found.`}):U!==void 0&&p>U&&l.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${U} items matching schema. ${p} items were found.`})}if(!y&&_e!==void 0){let f=`${s}/unevaluatedItems`;for(u;u<c;u++){if(h[u])continue;let a=w(e[u],_e,r,n,i,d,`${o}/${u}`,f);h[u]=!0,a.valid||l.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:f,error:"Items did not match unevaluated items schema."},...a.errors)}}if(Be)for(let f=0;f<c;f++){let a=e[f],p=typeof a=="object"&&a!==null;for(let m=0;m<c;m++){if(f===m)continue;let v=e[m];(a===v||p&&(typeof v=="object"&&v!==null)&&A(a,v))&&(l.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${f} and ${m}.`}),f=Number.MAX_SAFE_INTEGER,m=Number.MAX_SAFE_INTEGER)}}}else if($==="number"){if(r==="4"?(C!==void 0&&(J===!0&&e<=C||e<C)&&l.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${s}/minimum`,error:`${e} is less than ${J?"or equal to ":""} ${C}.`}),N!==void 0&&(V===!0&&e>=N||e>N)&&l.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${s}/maximum`,error:`${e} is greater than ${V?"or equal to ":""} ${N}.`})):(C!==void 0&&e<C&&l.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${s}/minimum`,error:`${e} is less than ${C}.`}),N!==void 0&&e>N&&l.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${s}/maximum`,error:`${e} is greater than ${N}.`}),J!==void 0&&e<=J&&l.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${J}.`}),V!==void 0&&e>=V&&l.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${V}.`})),H!==void 0){let c=e%H;Math.abs(0-c)>=11920929e-14&&Math.abs(H-c)>=11920929e-14&&l.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${H}.`})}}else if($==="string"){let c=F===void 0&&B===void 0?0:Ae(e);F!==void 0&&c<F&&l.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${s}/minLength`,error:`String is too short (${c} < ${F}).`}),B!==void 0&&c>B&&l.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${s}/maxLength`,error:`String is too long (${c} > ${B}).`}),Ee!==void 0&&!new RegExp(Ee,"u").test(e)&&l.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${s}/pattern`,error:"String does not match pattern."}),q!==void 0&&ce[q]&&!ce[q](e)&&l.push({instanceLocation:o,keyword:"format",keywordLocation:`${s}/format`,error:`String does not match format "${q}".`})}return{valid:l.length===0,errors:l}}var Y=class{constructor(t,r="2019-09",n=!0){I(this,"schema");I(this,"draft");I(this,"shortCircuit");I(this,"lookup");this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=k(t)}validate(t){return w(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),k(t,this.lookup)}};var Q={type:"object",properties:{}},It=["draft-2020-12","draft-07"];function x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tt(e){if(!x(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function je(e,t=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);try{return(Array.isArray(e)?e:Tt(e)?Object.values(e):null)?.every(r=>je(r,t))??!1}catch{return!1}finally{t.delete(e)}}function ze(e){return je(e)?e:void 0}function De(e){if(!x(e))return null;let t=e["~standard"];return x(t)?t:null}function _t(e){let t=De(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function Ot(e){let t=De(e);return!t||t.version!==1||!x(t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function Z(e){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(t){if(!x(t))return{issues:[{message:"expected object arguments"}]};let r=me(t,e);return r?{issues:[r]}:{value:t}}}}}function Et(e){let t=[];for(let r of It)try{let n=e["~standard"].jsonSchema.input({target:r});return Je(n),n}catch(n){t.push({target:r,error:n})}throw console.warn("[WebMCPPolyfill] Standard JSON Schema conversion failed:",t),new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function Re(e){if(e===void 0){let r=Q;return{inputSchema:r,standardValidator:Z(r)}}if(Ot(e)){let r=Et(e);return{inputSchema:r,standardValidator:Z(r)}}if(_t(e))return{inputSchema:Q,standardValidator:e};if(Je(e),Object.keys(e).length===0)return{inputSchema:Q,standardValidator:Z(Q)};let t=e.type===void 0?{type:"object",...e}:e;return{inputSchema:t,standardValidator:Z(t)}}function Je(e){if(!x(e))throw new Error("inputSchema must be a JSON Schema object");j(e,"$")}function j(e,t){let r=e.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(s=>typeof s=="string"&&s.length>0)))throw new Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);let n=e.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(s=>typeof s=="string")))throw new Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);let i=e.properties;if(i!==void 0){if(!x(i))throw new Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[s,h]of Object.entries(i)){if(!x(h))throw new Error(`Invalid JSON Schema at ${t}.properties.${s}: expected object schema`);j(h,`${t}.properties.${s}`)}}let d=e.items;if(d!==void 0)if(Array.isArray(d))for(let[s,h]of d.entries()){if(!x(h))throw new Error(`Invalid JSON Schema at ${t}.items[${s}]: expected object schema`);j(h,`${t}.items[${s}]`)}else if(x(d))j(d,`${t}.items`);else throw new Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(let s of["allOf","anyOf","oneOf"]){let h=e[s];if(h!==void 0){if(!Array.isArray(h))throw new Error(`Invalid JSON Schema at ${t}: "${s}" must be an array`);for(let[b,$]of h.entries()){if(!x($))throw new Error(`Invalid JSON Schema at ${t}.${s}[${b}]: expected object schema`);j($,`${t}.${s}[${b}]`)}}}let o=e.not;if(o!==void 0){if(!x(o))throw new Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);j(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw new Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function me(e,t){let r=new Y(t,"2020-12",!0).validate(e);if(r.valid)return null;let n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}var Ve="Failed to parse input arguments",X="Tool was executed but the invocation failed. For example, the script function threw an error",ye="Tool was cancelled",kt=/^[A-Za-z0-9_\-.]{1,128}$/u,Pt="__isWebMCPPolyfill",qe=Symbol("standardValidator");function Mt(){return new DOMException("signal is aborted without reason","AbortError")}var g={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},Ct=class extends EventTarget{constructor(){super(...arguments);I(this,"tools",new Map);I(this,"testingShim",null);I(this,"_ontoolchange",null);I(this,"unregisterToolDeprecationWarned",!1);I(this,"toolsChangedQueued",!1)}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerTool(t,r){let n=r?.signal;if(n?.aborted)return Promise.reject(Mt());let i=zt(t,this.tools);return this.tools.set(i.name,i),this.notifyToolsChanged(),n&&n.addEventListener("abort",()=>{this.tools.delete(i.name)&&this.notifyToolsChanged()},{once:!0}),Promise.resolve()}unregisterTool(t){this.warnUnregisterToolDeprecationOnce();let r=jt(t);this.tools.delete(r)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(t,r,n){return this.executeToolByName(t.name,r,n,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new Nt(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(t=>{let r;try{r=JSON.stringify(t.inputSchema??{type:"object"})}catch{r='{"type":"object"}'}return{name:t.name,description:t.description,inputSchema:r}})}getRegisteredToolInfos(){return this.getToolInfos().map(t=>{let r=this.tools.get(t.name);return{...t,title:r?.title??"",origin:globalThis.location?.origin??"",window:globalThis.window}})}async executeToolForTesting(t,r,n){return this.executeToolByName(t,r,n,!0)}async executeToolByName(t,r,n,i){if(n?.signal?.aborted)throw O(ye);let d=this.tools.get(t);if(!d)throw O(`Tool not found: ${t}`);let o=At(r),s=await Jt(o,d);if(s)throw O(s);let h=!0,b={requestUserInteraction:async $=>{if(!h)throw new Error(`ModelContextClient for tool "${t}" is no longer active after execute() resolved`);if(typeof $!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return $()}};try{let $=d.execute(o,b),P=await Bt(Promise.resolve($),n?.signal),W=Ut(P),M=Vt(W,d);if(M)throw new Error(M);if(i)return Ft(W);let S=JSON.stringify(P);return S===void 0?null:S}catch($){throw O($ instanceof Error?`${X}: ${$.message}`:X)}finally{h=!1}}notifyToolsChanged(){this.toolsChangedQueued||(this.toolsChangedQueued=!0,queueMicrotask(()=>{this.toolsChangedQueued=!1;let t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(r){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",r)}this.dispatchEvent(t),this.testingShim?.dispatchToolChange()}))}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) \u2014 pass an AbortSignal and abort it to unregister."))}},Nt=class extends EventTarget{constructor(t){super();I(this,"context");I(this,"_ontoolchange",null);this.context=t}listTools(){return this.context.getToolInfos()}executeTool(t,r,n){return this.context.executeToolForTesting(t,r,n)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerToolsChangedCallback(t){if(typeof t!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",t)}dispatchToolChange(){let t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(r){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",r)}this.dispatchEvent(t),this.dispatchEvent(new Event("toolschanged"))}};function O(e){try{return new DOMException(e,"UnknownError")}catch{let t=new Error(e);return t.name="UnknownError",t}}function pe(e){try{return new DOMException(e,"InvalidStateError")}catch{let t=new Error(e);return t.name="InvalidStateError",t}}function At(e){let t;try{t=JSON.parse(e)}catch{throw O(Ve)}if(!t||typeof t!="object"||Array.isArray(t))throw O(Ve);return t}function jt(e){if(typeof e=="string")return e;if(x(e)&&typeof e.name=="string")return e.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function zt(e,t){if(!e||typeof e!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof e.name!="string"||e.name.length===0)throw pe('Tool "name" must be a non-empty string');if(!kt.test(e.name)||Array.from(e.name).length>128)throw pe('Tool "name" must be 1\u2013128 characters and contain only ASCII alphanumeric, underscore, hyphen, or period');if(typeof e.description!="string"||e.description.length===0)throw pe('Tool "description" must be a non-empty string');if(typeof e.execute!="function")throw new TypeError('Tool "execute" must be a function');if(t.has(e.name))throw new Error(`Tool already registered: ${e.name}`);let r=Re(e.inputSchema),n=e.annotations,i=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...e,...i?{annotations:i}:{},inputSchema:r.inputSchema,[qe]:r.standardValidator}}function Dt(e){if(!e||e.length===0)return null;let t=e.map(r=>x(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return t.length===0?null:t.join(".")}async function Rt(e,t){let r;try{r=await Promise.resolve(t["~standard"].validate(e))}catch(d){let o=d instanceof Error?`: ${d.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",d),`Input validation error: schema validation failed${o}`}if(!r.issues||r.issues.length===0)return null;let n=r.issues[0];if(!n)return"Input validation error";let i=Dt(n?.path);return i?`Input validation error: ${n.message} at ${i}`:`Input validation error: ${n.message}`}async function Jt(e,t){return Rt(e,t[qe])}function Vt(e,t){if(!t.outputSchema||e.isError)return null;if(e.structuredContent===void 0)return`Output validation error: Tool ${t.name} has an output schema but no structured content was provided`;let r=me(e.structuredContent,t.outputSchema);return r?`Output validation error: ${r.message}`:null}function Wt(e){return x(e)&&Array.isArray(e.content)}function qt(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Ut(e){if(Wt(e))return e;let t=ze(e);return{content:[{type:"text",text:qt(e)}],...t!==void 0?{structuredContent:t}:{},isError:!1}}function Ht(e){for(let t of e.content??[])if(t.type==="text"&&"text"in t&&typeof t.text=="string")return t.text;return null}function Ft(e){if(e.isError)throw O(Ht(e)?.replace(/^Error:\s*/i,"").trim()||X);let t=e.metadata;if(t&&typeof t=="object"&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw O(X)}}function Bt(e,t){return t?t.aborted?Promise.reject(O(ye)):new Promise((r,n)=>{let i=()=>{d(),n(O(ye))},d=()=>{t.removeEventListener("abort",i)};t.addEventListener("abort",i,{once:!0}),e.then(o=>{d(),r(o)},o=>{d(),n(o)})}):e}function Ue(){return typeof navigator<"u"?navigator:null}function He(){return typeof document<"u"?document:null}function Kt(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:r})}function We(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:t})}var L=!1;function Gt(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get(){return L||(L=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document \u2014 use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),t}})}function Fe(e){let t=Ue(),r=He();if(!t&&!r||r?.modelContext)return;let i=t?.modelContext,d=!!i;if(g.installed&&Yt(),r&&i){g.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),We(r,i),g.installedDocumentModelContext=!0,g.installed=!0;return}if(d)return;let o=new Ct,s=o;if(s[Pt]=!0,r&&(g.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),We(r,s),g.installedDocumentModelContext=!0),t){g.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(t,"modelContext"),g.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,"modelContextTesting"),L=!1,Gt(t,s),g.installedNavigatorModelContext=!0;let h=e?.installTestingShim??"if-missing",b=!!t.modelContextTesting;(h==="always"||(h===!0||h==="if-missing")&&!b)&&(Kt(t,"modelContextTesting",o.getTestingShim()),g.installedNavigatorModelContextTesting=!0)}g.installed=!0}function Yt(){if(!g.installed)return;let e=(n,i,d)=>{if(d){Object.defineProperty(n,i,d);return}delete n[i]},t=Ue(),r=He();r&&g.installedDocumentModelContext&&e(r,"modelContext",g.previousDocumentModelContextDescriptor),t&&g.installedNavigatorModelContext&&e(t,"modelContext",g.previousNavigatorModelContextDescriptor),t&&g.installedNavigatorModelContextTesting&&e(t,"modelContextTesting",g.previousNavigatorModelContextTestingDescriptor),g.installed=!1,g.previousDocumentModelContextDescriptor=void 0,g.previousNavigatorModelContextDescriptor=void 0,g.previousNavigatorModelContextTestingDescriptor=void 0,g.installedDocumentModelContext=!1,g.installedNavigatorModelContext=!1,g.installedNavigatorModelContextTesting=!1,L=!1}if(typeof window<"u"&&typeof document<"u"){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{Fe(e)}catch(t){console.error("[WebMCPPolyfill] Auto-initialization failed:",t)}}export{Fe as initializeWebMCPPolyfill};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runtypelabs/persona",
3
- "version": "4.17.0",
3
+ "version": "4.17.1",
4
4
  "description": "Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -79,7 +79,7 @@
79
79
  "src"
80
80
  ],
81
81
  "dependencies": {
82
- "@mcp-b/webmcp-polyfill": "^3.0.0",
82
+ "@mcp-b/webmcp-polyfill": "^4.0.0",
83
83
  "dompurify": "^3.4.13",
84
84
  "idiomorph": "^0.7.4",
85
85
  "lucide": "^1.18.0",
@@ -88,11 +88,11 @@
88
88
  },
89
89
  "devDependencies": {
90
90
  "@size-limit/file": "^12.1.0",
91
- "acorn": "^8.15.0",
92
91
  "@types/node": "^20.12.7",
93
92
  "@typescript-eslint/eslint-plugin": "^7.0.0",
94
93
  "@typescript-eslint/parser": "^7.0.0",
95
94
  "@vitest/ui": "^4.0.9",
95
+ "acorn": "^8.15.0",
96
96
  "esbuild": "^0.21.5",
97
97
  "eslint": "^8.57.0",
98
98
  "eslint-config-prettier": "^9.1.0",