@artooi/ag-ui-web-component 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +86 -1
- package/README.md +98 -5
- package/dist/ag-ui-web-component.bundle.js +126 -50
- package/dist/ag-ui-web-component.bundle.js.map +4 -4
- package/dist/constants.d.ts +9 -0
- package/dist/constants.d.ts.map +1 -1
- package/dist/core/ag_ui_chat.d.ts +29 -4
- package/dist/core/ag_ui_chat.d.ts.map +1 -1
- package/dist/core/agui_client.d.ts +11 -0
- package/dist/core/agui_client.d.ts.map +1 -1
- package/dist/core/create_http_agent.d.ts +6 -0
- package/dist/core/create_http_agent.d.ts.map +1 -1
- package/dist/core/run_index.d.ts +50 -0
- package/dist/core/run_index.d.ts.map +1 -0
- package/dist/index.d.ts +9 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +453 -63
- package/dist/index.js.map +3 -3
- package/dist/tools/page_state.d.ts +40 -0
- package/dist/tools/page_state.d.ts.map +1 -0
- package/dist/ui/checkpoint_menu.d.ts +32 -0
- package/dist/ui/checkpoint_menu.d.ts.map +1 -0
- package/dist/ui/styles.d.ts +1 -1
- package/dist/ui/styles.d.ts.map +1 -1
- package/dist/ui/ui_strings.d.ts +10 -0
- package/dist/ui/ui_strings.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/constants.ts +10 -0
- package/src/core/ag_ui_chat.ts +153 -6
- package/src/core/agui_client.ts +28 -0
- package/src/core/create_http_agent.ts +7 -0
- package/src/core/run_index.ts +91 -0
- package/src/index.ts +14 -1
- package/src/tools/page_state.ts +72 -0
- package/src/ui/checkpoint_menu.ts +153 -0
- package/src/ui/styles.ts +76 -0
- package/src/ui/ui_strings.ts +15 -0
- package/src/version.ts +1 -1
- package/dist/tools/state_hook.d.ts +0 -23
- package/dist/tools/state_hook.d.ts.map +0 -1
- package/src/tools/state_hook.ts +0 -53
|
@@ -1,79 +1,79 @@
|
|
|
1
|
-
var Vu=Object.defineProperty;var Ii=(t,e)=>{for(var n in e)Vu(t,n,{get:e[n],enumerable:!0})};var Er="ag-ui-chat",Ci="ag-ui-submit",Ni="ag-ui-toggle",Ye={USER:"user",ASSISTANT:"assistant"},Ln="x-destructive",Ri="x-confirm",Ne="x-summary",Pn="x-navigates",Oi=10,ce={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Le={UPLOADING:"uploading",READY:"ready",ERROR:"error"},Mi=10*1024*1024,ze={INLINE:"inline",MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var Wu=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function Fa(t,e){let n=[];return{text:t.replace(Wu,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function qu(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&typeof e.prompt=="string"}function Li(t){return Array.isArray(t)?t.filter(qu):[]}var Dn=class{#n=new Map;register(e){this.#n.set(e.name,e)}has(e){return this.#n.has(e)}get(e){let n=this.#n.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#n.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function Pi(t){return t[Ln]===!0}function Di(t){return t[Pn]===!0}function Tr(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Xu=Tr(HTMLInputElement.prototype,"value"),Ku=Tr(HTMLTextAreaElement.prototype,"value"),Zu=Tr(HTMLSelectElement.prototype,"value"),Yu=Tr(HTMLInputElement.prototype,"checked");function kt(t,e){t instanceof HTMLTextAreaElement?Ku.call(t,e):t instanceof HTMLSelectElement?Zu.call(t,e):Xu.call(t,e)}function Un(t,e){Yu.call(t,e)}var $a="#4f46e5";function Sr(t){return new Promise(e=>{setTimeout(e,t)})}async function Ui(t,e,n={}){let r=n.charDelayMs??35;kt(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)kt(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await Sr(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Hi(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${$a}`,t.style.outlineOffset="2px",await Sr(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}function lt(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function Gi(t,e={}){let n=e.flashMs??200;t.focus();let r=t.style.boxShadow;t.style.boxShadow="0 0 0 3px rgba(79, 70, 229, 0.4)",await Sr(n),t.style.boxShadow=r}var za="0 0 0 3px rgba(79, 70, 229, 0.4)";function Ba(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Fi(t){return t<=0||Ba()?Promise.resolve():Sr(t)}async function $i(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,i=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=za,await Fi(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function Ju(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function zi(t,e,n={}){let r=Ju(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,i=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${$a}`,t.style.outlineOffset="2px",await Fi(o),kt(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=i,t.style.outlineOffset=s}async function Bi(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=za,await Fi(r),Un(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var ji={SCROLL:"scroll",DRAG:"drag"};function Vi(t,e){let n=[];return t.has(ji.SCROLL)&&n.push(Qu(e)),t.has(ji.DRAG)&&n.push(ed(e)),n}function Qu(t){return{name:"scroll_to",description:"Scroll a target into view. `target` is `top`, `bottom`, or a CSS selector / page-map element id. Read-only: it changes nothing on the page.",parameters:{type:"object",properties:{target:{type:"string"}},required:["target"],[Ne]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let o=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:o,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return lt(r),{scrolled:!0,target:n}}}}function ed(t){return{name:"drag_and_drop",description:"Drag the `from` element onto the `to` element (CSS selectors or page-map element ids), firing the page's native drag-and-drop. Use for reordering sortable lists. The page decides what the drop commits.",parameters:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"],[Ne]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),o=t(n);if(o===null)throw new Error(`no element matching "${n}"`);let i=t(r);if(i===null)throw new Error(`no element matching "${r}"`);return td(o,i),{dragged:!0,from:n,to:r}}}}function td(t,e){let n=new DataTransfer;Hn(t,"dragstart",n),Hn(e,"dragenter",n),Hn(e,"dragover",n),Hn(e,"drop",n),Hn(t,"dragend",n)}function Hn(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function Wi(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function qi(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,i=r.summary;typeof o=="string"&&typeof i=="string"&&(e[o]=i)}return e}var ja=/:([A-Za-z_][A-Za-z0-9_]*)/g;function nd(t){let e=[];for(let n of t.matchAll(ja)){let r=n[1];r!==void 0&&e.push(r)}return e}function rd(t,e,n){let r={...n};return{path:e.replace(ja,(i,s)=>{let a=n[s];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${s}"`);return delete r[s],encodeURIComponent(String(a))}),leftover:r}}function od(t,e){let n=new URLSearchParams;for(let[o,i]of Object.entries(e))n.set(o,String(i));let r=n.toString();return r===""?t:`${t}?${r}`}function Xi(t,e){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[Ne]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:nd(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[Pn]:!0,[Ne]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(p=>p.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=rd(o.id,o.path,i),l=od(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}function Ki(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[Ne]:`Read ${t.name}`},handler:()=>t.read()}],n=t.write;return n!==void 0&&e.push({name:`set_${t.name}`,description:`Update the "${t.name}" state.`,parameters:{...t.schema??{type:"object"},[Ln]:!0,[Ne]:`Update ${t.name}`},handler:r=>n(r)}),e}var re={title:"Assistant",chatHistory:"Chat history",newChat:"New chat",collapse:"Collapse",expand:"Expand",toggleTheme:"Toggle theme",conversation:"Conversation",thinking:"Assistant is thinking\u2026",thoughts:"Thoughts",stopped:"\u23F9 Stopped",connectionLost:"Connection lost",noResult:"No result returned.",declinedAction:"User declined the action.",navigating:"Navigating\u2026",skillNeeds:"\u201C{title}\u201D needs: {fields}",message:"Message",inputPlaceholder:"Ask anything\u2026",send:"Send",stop:"Stop",attachFiles:"Attach files",recordVoice:"Record voice",stopRecording:"Stop recording",transcribing:"Transcribing\u2026",transcriptionFailed:"Transcription failed",toolRunning:"running\u2026",toolDone:"\u2713 done",toolError:"\u26A0 error",toolDeclined:"\u2298 declined",resultLabel:"Result",errorLabel:"Error",declinedLabel:"Declined",details:"Details",confirmAction:"Confirm action",confirmRun:"Run \u201C{tool}\u201D?",confirm:"Confirm",cancel:"Cancel",approveAction:"Approve action",approvalPrompt:"Approve this action?",approve:"Approve",deny:"Deny",askUserAction:"Question",otherOption:"Other\u2026",answerPlaceholder:"Type your answer\u2026",submit:"Submit",chats:"Chats",noConversations:"No conversations yet.",rename:"Rename",renameConversation:"Rename conversation",delete:"Delete",deleteConversation:"Delete conversation",deletePrompt:"Delete?",tooLarge:"Too large (max {size})",fileTypeNotAllowed:"File type not allowed",uploadFailed:"upload failed",retry:"Retry",retryUpload:"Retry upload",remove:"Remove",removeAttachment:"Remove attachment",justNow:"just now",minutesAgo:"{n}m ago",hoursAgo:"{n}h ago",daysAgo:"{n}d ago",weeksAgo:"{n}w ago"};function Zi(t){let e={...re};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function Va(t,e){let n=document.createElement("button");return n.type="button",n.className=`approval-btn approval-btn--${t}`,n.setAttribute("part",`approval-button approval-${t}`),n.textContent=e,n}function Yi(t,e,n={}){let r=n.strings??re;return new Promise(o=>{let i=document.createElement("div");i.className="approval",i.setAttribute("part","approval"),e.toolName!==void 0&&i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.approveAction);let s=document.createElement("div");s.className="approval-body",s.setAttribute("part","approval-body"),s.textContent=e.message??r.approvalPrompt;let a=document.createElement("div");a.className="approval-actions",a.setAttribute("part","approval-actions");let l=Va("deny",r.deny),c=Va("approve",r.approve),p=!1,m=b=>{p||(p=!0,l.disabled=!0,c.disabled=!0,i.setAttribute("data-resolved",b?"approved":"denied"),o(b))};if(l.addEventListener("click",()=>m(!1)),c.addEventListener("click",()=>m(!0)),n.signal?.addEventListener("abort",()=>m(!1),{once:!0}),a.append(l,c),i.append(s,a),t.appendChild(i),n.signal?.aborted===!0){m(!1);return}c.focus()})}function Ji(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild(id(n));return e}function id(t){let e=document.createElement("div");e.className="attachment-chip attachment-chip--ready",e.setAttribute("part","attachment-chip");let n=document.createElement("span");n.className="attachment-chip-icon",n.setAttribute("part","attachment-chip-icon"),n.textContent=Qi(t.mime),n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.className="attachment-chip-name",r.setAttribute("part","attachment-chip-name"),r.textContent=t.name,r.title=t.name;let o=document.createElement("span");return o.className="attachment-chip-size",o.setAttribute("part","attachment-chip-size"),o.textContent=wr(t.size),e.append(n,r,o),e}function Qi(t){return t.startsWith("image/")?"\u{1F5BC}":t==="application/pdf"?"\u{1F4D5}":t.startsWith("text/")?"\u{1F4C4}":"\u{1F4CE}"}function wr(t){if(t<1024)return`${t} B`;let e=["KB","MB","GB"],n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r+=1;return`${n<10?Math.round(n*10)/10:Math.round(n)} ${e[r]}`}var ve=[];for(let t=0;t<256;++t)ve.push((t+256).toString(16).slice(1));function Wa(t,e=0){return(ve[t[e+0]]+ve[t[e+1]]+ve[t[e+2]]+ve[t[e+3]]+"-"+ve[t[e+4]]+ve[t[e+5]]+"-"+ve[t[e+6]]+ve[t[e+7]]+"-"+ve[t[e+8]]+ve[t[e+9]]+"-"+ve[t[e+10]]+ve[t[e+11]]+ve[t[e+12]]+ve[t[e+13]]+ve[t[e+14]]+ve[t[e+15]]).toLowerCase()}var es,sd=new Uint8Array(16);function ts(){if(!es){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");es=crypto.getRandomValues.bind(crypto)}return es(sd)}var ad=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ns={randomUUID:ad};function ld(t,e,n){if(ns.randomUUID&&!e&&!t)return ns.randomUUID();t=t||{};let r=t.random??t.rng?.()??ts();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return Wa(r)}var bt=ld;var u={};Ii(u,{BRAND:()=>Ld,DIRTY:()=>It,EMPTY_PATH:()=>pd,INVALID:()=>M,NEVER:()=>bp,OK:()=>Ee,ParseStatus:()=>be,Schema:()=>$,ZodAny:()=>Et,ZodArray:()=>pt,ZodBigInt:()=>Nt,ZodBoolean:()=>Rt,ZodBranded:()=>Fn,ZodCatch:()=>zt,ZodDate:()=>Ot,ZodDefault:()=>$t,ZodDiscriminatedUnion:()=>kr,ZodEffects:()=>Ue,ZodEnum:()=>Gt,ZodError:()=>ke,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>Cr,ZodIntersection:()=>Dt,ZodIssueCode:()=>T,ZodLazy:()=>Ut,ZodLiteral:()=>Ht,ZodMap:()=>dn,ZodNaN:()=>fn,ZodNativeEnum:()=>Ft,ZodNever:()=>Be,ZodNull:()=>Lt,ZodNullable:()=>et,ZodNumber:()=>Ct,ZodObject:()=>Ie,ZodOptional:()=>Pe,ZodParsedType:()=>k,ZodPipeline:()=>$n,ZodPromise:()=>Tt,ZodReadonly:()=>Bt,ZodRecord:()=>Ir,ZodSchema:()=>$,ZodSet:()=>pn,ZodString:()=>xt,ZodSymbol:()=>cn,ZodTransformer:()=>Ue,ZodTuple:()=>Qe,ZodType:()=>$,ZodUndefined:()=>Mt,ZodUnion:()=>Pt,ZodUnknown:()=>dt,ZodVoid:()=>un,addIssueToContext:()=>_,any:()=>Bd,array:()=>qd,bigint:()=>Hd,boolean:()=>rl,coerce:()=>vp,custom:()=>el,date:()=>Gd,datetimeRegex:()=>Ja,defaultErrorMap:()=>ct,discriminatedUnion:()=>Yd,effect:()=>cp,enum:()=>sp,function:()=>rp,getErrorMap:()=>sn,getParsedType:()=>Je,instanceof:()=>Dd,intersection:()=>Jd,isAborted:()=>_r,isAsync:()=>an,isDirty:()=>Ar,isValid:()=>yt,late:()=>Pd,lazy:()=>op,literal:()=>ip,makeIssue:()=>Gn,map:()=>tp,nan:()=>Ud,nativeEnum:()=>ap,never:()=>Vd,null:()=>zd,nullable:()=>dp,number:()=>nl,object:()=>Xd,objectUtil:()=>rs,oboolean:()=>gp,onumber:()=>mp,optional:()=>up,ostring:()=>hp,pipeline:()=>fp,preprocess:()=>pp,promise:()=>lp,quotelessJson:()=>cd,record:()=>ep,set:()=>np,setErrorMap:()=>dd,strictObject:()=>Kd,string:()=>tl,symbol:()=>Fd,transformer:()=>cp,tuple:()=>Qd,undefined:()=>$d,union:()=>Zd,unknown:()=>jd,util:()=>B,void:()=>Wd});var B;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},t.find=(o,i)=>{for(let s of o)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(B||(B={}));var rs;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(rs||(rs={}));var k=B.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Je=t=>{switch(typeof t){case"undefined":return k.undefined;case"string":return k.string;case"number":return Number.isNaN(t)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(t)?k.array:t===null?k.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?k.promise:typeof Map<"u"&&t instanceof Map?k.map:typeof Set<"u"&&t instanceof Set?k.set:typeof Date<"u"&&t instanceof Date?k.date:k.object;default:return k.unknown}};var T=B.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),cd=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ke=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,B.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];n[i]=n[i]||[],n[i].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ke.create=t=>new ke(t);var ud=(t,e)=>{let n;switch(t.code){case T.invalid_type:t.received===k.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case T.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,B.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:n=`Unrecognized key(s) in object: ${B.joinValues(t.keys,", ")}`;break;case T.invalid_union:n="Invalid input";break;case T.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${B.joinValues(t.options)}`;break;case T.invalid_enum_value:n=`Invalid enum value. Expected ${B.joinValues(t.options)}, received '${t.received}'`;break;case T.invalid_arguments:n="Invalid function arguments";break;case T.invalid_return_type:n="Invalid function return type";break;case T.invalid_date:n="Invalid date";break;case T.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:B.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case T.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case T.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case T.custom:n="Invalid input";break;case T.invalid_intersection_types:n="Intersection results could not be merged";break;case T.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case T.not_finite:n="Number must be finite";break;default:n=e.defaultError,B.assertNever(t)}return{message:n}},ct=ud;var qa=ct;function dd(t){qa=t}function sn(){return qa}var Gn=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,i=[...n,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...o,path:i,message:a}},pd=[];function _(t,e){let n=sn(),r=Gn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ct?void 0:ct].filter(o=>!!o)});t.common.issues.push(r)}var be=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return M;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let i=await o.key,s=await o.value;r.push({key:i,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return M;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:e.value,value:r}}},M=Object.freeze({status:"aborted"}),It=t=>({status:"dirty",value:t}),Ee=t=>({status:"valid",value:t}),_r=t=>t.status==="aborted",Ar=t=>t.status==="dirty",yt=t=>t.status==="valid",an=t=>typeof Promise<"u"&&t instanceof Promise;var C;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(C||(C={}));var De=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Xa=(t,e)=>{if(yt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ke(t.common.issues);return this._error=n,this._error}}};function H(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(s,a)=>{let{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var $=class{get description(){return this._def.description}_getType(e){return Je(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new be,ctx:{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(an(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Xa(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return yt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>yt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(an(o)?o:Promise.resolve(o));return Xa(r,i)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:T.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new Ue({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Pe.create(this,this._def)}nullable(){return et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return Tt.create(this,this._def)}or(e){return Pt.create([this,e],this._def)}and(e){return Dt.create(this,e,this._def)}transform(e){return new Ue({...H(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new $t({...H(this._def),innerType:this,defaultValue:n,typeName:L.ZodDefault})}brand(){return new Fn({typeName:L.ZodBranded,type:this,...H(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new zt({...H(this._def),innerType:this,catchValue:n,typeName:L.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return $n.create(this,e)}readonly(){return Bt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},fd=/^c[^\s-]{8,}$/i,hd=/^[0-9a-z]+$/,md=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,vd=/^[a-z0-9_-]{21}$/i,bd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,xd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ed="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",os,Td=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Sd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,wd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,_d=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ad=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,kd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Za="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Id=new RegExp(`^${Za}$`);function Ya(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Cd(t){return new RegExp(`^${Ya(t)}$`)}function Ja(t){let e=`${Za}T${Ya(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Nd(t,e){return!!((e==="v4"||!e)&&Td.test(t)||(e==="v6"||!e)&&wd.test(t))}function Rd(t,e){if(!bd.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Od(t,e){return!!((e==="v4"||!e)&&Sd.test(t)||(e==="v6"||!e)&&_d.test(t))}var xt=class t extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==k.string){let i=this._getOrReturnCtx(e);return _(i,{code:T.invalid_type,expected:k.string,received:i.parsedType}),M}let r=new be,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),_(o,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),_(o,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(e,o),s?_(o,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&_(o,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")xd.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"email",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")os||(os=new RegExp(Ed,"u")),os.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"emoji",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")gd.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"uuid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")vd.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"nanoid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")fd.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"cuid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")hd.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"cuid2",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")md.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"ulid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),_(o,{validation:"url",code:T.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"regex",code:T.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),_(o,{code:T.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),_(o,{code:T.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),_(o,{code:T.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Ja(i).test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{code:T.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Id.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{code:T.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Cd(i).test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{code:T.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?yd.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"duration",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Nd(e.data,i.version)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"ip",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Rd(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"jwt",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Od(e.data,i.version)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"cidr",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Ad.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"base64",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?kd.test(e.data)||(o=this._getOrReturnCtx(e,o),_(o,{validation:"base64url",code:T.invalid_string,message:i.message}),r.dirty()):B.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:T.invalid_string,...C.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...C.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...C.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...C.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...C.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...C.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...C.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...C.errToObj(n)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};xt.create=t=>new xt({checks:[],typeName:L.ZodString,coerce:t?.coerce??!1,...H(t)});function Md(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}var Ct=class t extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==k.number){let i=this._getOrReturnCtx(e);return _(i,{code:T.invalid_type,expected:k.number,received:i.parsedType}),M}let r,o=new be;for(let i of this._def.checks)i.kind==="int"?B.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{code:T.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?Md(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{code:T.not_finite,message:i.message}),o.dirty()):B.assertNever(i);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,C.toString(n))}gt(e,n){return this.setLimit("min",e,!1,C.toString(n))}lte(e,n){return this.setLimit("max",e,!0,C.toString(n))}lt(e,n){return this.setLimit("max",e,!1,C.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:C.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&B.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Ct.create=t=>new Ct({checks:[],typeName:L.ZodNumber,coerce:t?.coerce||!1,...H(t)});var Nt=class t extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==k.bigint)return this._getInvalidInput(e);let r,o=new be;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):B.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return _(n,{code:T.invalid_type,expected:k.bigint,received:n.parsedType}),M}gte(e,n){return this.setLimit("min",e,!0,C.toString(n))}gt(e,n){return this.setLimit("min",e,!1,C.toString(n))}lte(e,n){return this.setLimit("max",e,!0,C.toString(n))}lt(e,n){return this.setLimit("max",e,!1,C.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:C.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Nt.create=t=>new Nt({checks:[],typeName:L.ZodBigInt,coerce:t?.coerce??!1,...H(t)});var Rt=class extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==k.boolean){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.boolean,received:r.parsedType}),M}return Ee(e.data)}};Rt.create=t=>new Rt({typeName:L.ZodBoolean,coerce:t?.coerce||!1,...H(t)});var Ot=class t extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==k.date){let i=this._getOrReturnCtx(e);return _(i,{code:T.invalid_type,expected:k.date,received:i.parsedType}),M}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return _(i,{code:T.invalid_date}),M}let r=new be,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),_(o,{code:T.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),_(o,{code:T.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):B.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Ot.create=t=>new Ot({checks:[],coerce:t?.coerce||!1,typeName:L.ZodDate,...H(t)});var cn=class extends ${_parse(e){if(this._getType(e)!==k.symbol){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.symbol,received:r.parsedType}),M}return Ee(e.data)}};cn.create=t=>new cn({typeName:L.ZodSymbol,...H(t)});var Mt=class extends ${_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.undefined,received:r.parsedType}),M}return Ee(e.data)}};Mt.create=t=>new Mt({typeName:L.ZodUndefined,...H(t)});var Lt=class extends ${_parse(e){if(this._getType(e)!==k.null){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.null,received:r.parsedType}),M}return Ee(e.data)}};Lt.create=t=>new Lt({typeName:L.ZodNull,...H(t)});var Et=class extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return Ee(e.data)}};Et.create=t=>new Et({typeName:L.ZodAny,...H(t)});var dt=class extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ee(e.data)}};dt.create=t=>new dt({typeName:L.ZodUnknown,...H(t)});var Be=class extends ${_parse(e){let n=this._getOrReturnCtx(e);return _(n,{code:T.invalid_type,expected:k.never,received:n.parsedType}),M}};Be.create=t=>new Be({typeName:L.ZodNever,...H(t)});var un=class extends ${_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.void,received:r.parsedType}),M}return Ee(e.data)}};un.create=t=>new un({typeName:L.ZodVoid,...H(t)});var pt=class t extends ${_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==k.array)return _(n,{code:T.invalid_type,expected:k.array,received:n.parsedType}),M;if(o.exactLength!==null){let s=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(s||a)&&(_(n,{code:s?T.too_big:T.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(_(n,{code:T.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(_(n,{code:T.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new De(n,s,n.path,a)))).then(s=>be.mergeArray(r,s));let i=[...n.data].map((s,a)=>o.type._parseSync(new De(n,s,n.path,a)));return be.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:C.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:C.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:C.toString(n)}})}nonempty(e){return this.min(1,e)}};pt.create=(t,e)=>new pt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...H(e)});function ln(t){if(t instanceof Ie){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Pe.create(ln(r))}return new Ie({...t._def,shape:()=>e})}else return t instanceof pt?new pt({...t._def,type:ln(t.element)}):t instanceof Pe?Pe.create(ln(t.unwrap())):t instanceof et?et.create(ln(t.unwrap())):t instanceof Qe?Qe.create(t.items.map(e=>ln(e))):t}var Ie=class t extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=B.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==k.object){let c=this._getOrReturnCtx(e);return _(c,{code:T.invalid_type,expected:k.object,received:c.parsedType}),M}let{status:r,ctx:o}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Be&&this._def.unknownKeys==="strip"))for(let c in o.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let p=i[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:p._parse(new De(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Be){let c=this._def.unknownKeys;if(c==="passthrough")for(let p of a)l.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(c==="strict")a.length>0&&(_(o,{code:T.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let p of a){let m=o.data[p];l.push({key:{status:"valid",value:p},value:c._parse(new De(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let p of l){let m=await p.key,b=await p.value;c.push({key:m,value:b,alwaysSet:p.alwaysSet})}return c}).then(c=>be.mergeObjectSync(r,c)):be.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:C.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:L.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of B.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of B.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ln(this)}partial(e){let n={};for(let r of B.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of B.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Pe;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Qa(B.objectKeys(this.shape))}};Ie.create=(t,e)=>new Ie({shape:()=>t,unknownKeys:"strip",catchall:Be.create(),typeName:L.ZodObject,...H(e)});Ie.strictCreate=(t,e)=>new Ie({shape:()=>t,unknownKeys:"strict",catchall:Be.create(),typeName:L.ZodObject,...H(e)});Ie.lazycreate=(t,e)=>new Ie({shape:t,unknownKeys:"strip",catchall:Be.create(),typeName:L.ZodObject,...H(e)});var Pt=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new ke(a.ctx.common.issues));return _(n,{code:T.invalid_union,unionErrors:s}),M}if(n.common.async)return Promise.all(r.map(async i=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i,s=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:c});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(l=>new ke(l));return _(n,{code:T.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};Pt.create=(t,e)=>new Pt({options:t,typeName:L.ZodUnion,...H(e)});var ut=t=>t instanceof Ut?ut(t.schema):t instanceof Ue?ut(t.innerType()):t instanceof Ht?[t.value]:t instanceof Gt?t.options:t instanceof Ft?B.objectValues(t.enum):t instanceof $t?ut(t._def.innerType):t instanceof Mt?[void 0]:t instanceof Lt?[null]:t instanceof Pe?[void 0,...ut(t.unwrap())]:t instanceof et?[null,...ut(t.unwrap())]:t instanceof Fn||t instanceof Bt?ut(t.unwrap()):t instanceof zt?ut(t._def.innerType):[],kr=class t extends ${_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.object)return _(n,{code:T.invalid_type,expected:k.object,received:n.parsedType}),M;let r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(_(n,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let i of n){let s=ut(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,i)}}return new t({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...H(r)})}};function is(t,e){let n=Je(t),r=Je(e);if(t===e)return{valid:!0,data:t};if(n===k.object&&r===k.object){let o=B.objectKeys(e),i=B.objectKeys(t).filter(a=>o.indexOf(a)!==-1),s={...t,...e};for(let a of i){let l=is(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===k.array&&r===k.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],l=is(s,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===k.date&&r===k.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Dt=class extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(i,s)=>{if(_r(i)||_r(s))return M;let a=is(i.value,s.value);return a.valid?((Ar(i)||Ar(s))&&n.dirty(),{status:n.value,value:a.data}):(_(r,{code:T.invalid_intersection_types}),M)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Dt.create=(t,e,n)=>new Dt({left:t,right:e,typeName:L.ZodIntersection,...H(n)});var Qe=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.array)return _(r,{code:T.invalid_type,expected:k.array,received:r.parsedType}),M;if(r.data.length<this._def.items.length)return _(r,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new De(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>be.mergeArray(n,s)):be.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Qe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qe({items:t,typeName:L.ZodTuple,rest:null,...H(e)})};var Ir=class t extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.object)return _(r,{code:T.invalid_type,expected:k.object,received:r.parsedType}),M;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in r.data)o.push({key:i._parse(new De(r,a,r.path,a)),value:s._parse(new De(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?be.mergeObjectAsync(n,o):be.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof $?new t({keyType:e,valueType:n,typeName:L.ZodRecord,...H(r)}):new t({keyType:xt.create(),valueType:e,typeName:L.ZodRecord,...H(n)})}},dn=class extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.map)return _(r,{code:T.invalid_type,expected:k.map,received:r.parsedType}),M;let o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new De(r,a,r.path,[c,"key"])),value:i._parse(new De(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,p=await l.value;if(c.status==="aborted"||p.status==="aborted")return M;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,p=l.value;if(c.status==="aborted"||p.status==="aborted")return M;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}}}};dn.create=(t,e,n)=>new dn({valueType:e,keyType:t,typeName:L.ZodMap,...H(n)});var pn=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.set)return _(r,{code:T.invalid_type,expected:k.set,received:r.parsedType}),M;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(_(r,{code:T.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(_(r,{code:T.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function s(l){let c=new Set;for(let p of l){if(p.status==="aborted")return M;p.status==="dirty"&&n.dirty(),c.add(p.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>i._parse(new De(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:C.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:C.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};pn.create=(t,e)=>new pn({valueType:t,minSize:null,maxSize:null,typeName:L.ZodSet,...H(e)});var Cr=class t extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.function)return _(n,{code:T.invalid_type,expected:k.function,received:n.parsedType}),M;function r(a,l){return Gn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sn(),ct].filter(c=>!!c),issueData:{code:T.invalid_arguments,argumentsError:l}})}function o(a,l){return Gn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sn(),ct].filter(c=>!!c),issueData:{code:T.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Tt){let a=this;return Ee(async function(...l){let c=new ke([]),p=await a._def.args.parseAsync(l,i).catch(h=>{throw c.addIssue(r(l,h)),c}),m=await Reflect.apply(s,this,p);return await a._def.returns._def.type.parseAsync(m,i).catch(h=>{throw c.addIssue(o(m,h)),c})})}else{let a=this;return Ee(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new ke([r(l,c.error)]);let p=Reflect.apply(s,this,c.data),m=a._def.returns.safeParse(p,i);if(!m.success)throw new ke([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Qe.create(e).rest(dt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Qe.create([]).rest(dt.create()),returns:n||dt.create(),typeName:L.ZodFunction,...H(r)})}},Ut=class extends ${get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ut.create=(t,e)=>new Ut({getter:t,typeName:L.ZodLazy,...H(e)});var Ht=class extends ${_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return _(n,{received:n.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ht.create=(t,e)=>new Ht({value:t,typeName:L.ZodLiteral,...H(e)});function Qa(t,e){return new Gt({values:t,typeName:L.ZodEnum,...H(e)})}var Gt=class t extends ${_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return _(n,{expected:B.joinValues(r),received:n.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return _(n,{received:n.data,code:T.invalid_enum_value,options:r}),M}return Ee(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Gt.create=Qa;var Ft=class extends ${_parse(e){let n=B.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==k.string&&r.parsedType!==k.number){let o=B.objectValues(n);return _(r,{expected:B.joinValues(o),received:r.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(B.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=B.objectValues(n);return _(r,{received:r.data,code:T.invalid_enum_value,options:o}),M}return Ee(e.data)}get enum(){return this._def.values}};Ft.create=(t,e)=>new Ft({values:t,typeName:L.ZodNativeEnum,...H(e)});var Tt=class extends ${unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.promise&&n.common.async===!1)return _(n,{code:T.invalid_type,expected:k.promise,received:n.parsedType}),M;let r=n.parsedType===k.promise?n.data:Promise.resolve(n.data);return Ee(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Tt.create=(t,e)=>new Tt({type:t,typeName:L.ZodPromise,...H(e)});var Ue=class extends ${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s=>{_(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return M;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?M:l.status==="dirty"?It(l.value):n.value==="dirty"?It(l.value):l});{if(n.value==="aborted")return M;let a=this._def.schema._parseSync({data:s,path:r.path,parent:r});return a.status==="aborted"?M:a.status==="dirty"?It(a.value):n.value==="dirty"?It(a.value):a}}if(o.type==="refinement"){let s=a=>{let l=o.refinement(a,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?M:(a.status==="dirty"&&n.dirty(),s(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!yt(s))return M;let a=o.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>yt(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:n.value,value:a})):M);B.assertNever(o)}};Ue.create=(t,e,n)=>new Ue({schema:t,typeName:L.ZodEffects,effect:e,...H(n)});Ue.createWithPreprocess=(t,e,n)=>new Ue({schema:e,effect:{type:"preprocess",transform:t},typeName:L.ZodEffects,...H(n)});var Pe=class extends ${_parse(e){return this._getType(e)===k.undefined?Ee(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Pe.create=(t,e)=>new Pe({innerType:t,typeName:L.ZodOptional,...H(e)});var et=class extends ${_parse(e){return this._getType(e)===k.null?Ee(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};et.create=(t,e)=>new et({innerType:t,typeName:L.ZodNullable,...H(e)});var $t=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};$t.create=(t,e)=>new $t({innerType:t,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});var zt=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return an(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});var fn=class extends ${_parse(e){if(this._getType(e)!==k.nan){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.nan,received:r.parsedType}),M}return{status:"valid",value:e.data}}};fn.create=t=>new fn({typeName:L.ZodNaN,...H(t)});var Ld=Symbol("zod_brand"),Fn=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},$n=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?M:i.status==="dirty"?(n.dirty(),It(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?M:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:L.ZodPipeline})}},Bt=class extends ${_parse(e){let n=this._def.innerType._parse(e),r=o=>(yt(o)&&(o.value=Object.freeze(o.value)),o);return an(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Bt.create=(t,e)=>new Bt({innerType:t,typeName:L.ZodReadonly,...H(e)});function Ka(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function el(t,e={},n){return t?Et.create().superRefine((r,o)=>{let i=t(r);if(i instanceof Promise)return i.then(s=>{if(!s){let a=Ka(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!i){let s=Ka(e,r),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):Et.create()}var Pd={object:Ie.lazycreate},L;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(L||(L={}));var Dd=(t,e={message:`Input not instance of ${t.name}`})=>el(n=>n instanceof t,e),tl=xt.create,nl=Ct.create,Ud=fn.create,Hd=Nt.create,rl=Rt.create,Gd=Ot.create,Fd=cn.create,$d=Mt.create,zd=Lt.create,Bd=Et.create,jd=dt.create,Vd=Be.create,Wd=un.create,qd=pt.create,Xd=Ie.create,Kd=Ie.strictCreate,Zd=Pt.create,Yd=kr.create,Jd=Dt.create,Qd=Qe.create,ep=Ir.create,tp=dn.create,np=pn.create,rp=Cr.create,op=Ut.create,ip=Ht.create,sp=Gt.create,ap=Ft.create,lp=Tt.create,cp=Ue.create,up=Pe.create,dp=et.create,pp=Ue.createWithPreprocess,fp=$n.create,hp=()=>tl().optional(),mp=()=>nl().optional(),gp=()=>rl().optional(),vp={string:(t=>xt.create({...t,coerce:!0})),number:(t=>Ct.create({...t,coerce:!0})),boolean:(t=>Rt.create({...t,coerce:!0})),bigint:(t=>Nt.create({...t,coerce:!0})),date:(t=>Ot.create({...t,coerce:!0}))};var bp=M;var yp=u.object({name:u.string(),arguments:u.string()}),xp=u.object({id:u.string(),type:u.literal("function"),function:yp,encryptedValue:u.string().optional()}),Nr=u.object({id:u.string(),role:u.string(),content:u.string().optional(),name:u.string().optional(),encryptedValue:u.string().optional()}),Ep=u.object({type:u.literal("text"),text:u.string()}),Tp=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),Sp=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),Rr=u.discriminatedUnion("type",[Tp,Sp]),wp=u.object({type:u.literal("image"),source:Rr,metadata:u.unknown().optional()}),_p=u.object({type:u.literal("audio"),source:Rr,metadata:u.unknown().optional()}),Ap=u.object({type:u.literal("video"),source:Rr,metadata:u.unknown().optional()}),kp=u.object({type:u.literal("document"),source:Rr,metadata:u.unknown().optional()});var ol=u.object({type:u.literal("binary"),mimeType:u.string(),id:u.string().optional(),url:u.string().optional(),data:u.string().optional(),filename:u.string().optional()}),il=(t,e)=>{!t.id&&!t.url&&!t.data&&e.addIssue({code:u.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},eb=ol.superRefine((t,e)=>{il(t,e)}),Ip=u.discriminatedUnion("type",[Ep,wp,_p,Ap,kp,ol]),Cp=Ip.superRefine((t,e)=>{t.type==="binary"&&il(t,e)}),Np=Nr.extend({role:u.literal("developer"),content:u.string()}),Rp=Nr.extend({role:u.literal("system"),content:u.string()}),Op=Nr.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(xp).optional()}),Mp=Nr.extend({role:u.literal("user"),content:u.union([u.string(),u.array(Cp)])}),Lp=u.object({id:u.string(),content:u.string(),role:u.literal("tool"),toolCallId:u.string(),error:u.string().optional(),encryptedValue:u.string().optional()}),Pp=u.object({id:u.string(),role:u.literal("activity"),activityType:u.string(),content:u.record(u.any())}),Dp=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),sl=u.discriminatedUnion("role",[Np,Rp,Op,Mp,Lp,Pp,Dp]),tb=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),Up=u.object({description:u.string(),value:u.string()}),al=u.object({name:u.string(),description:u.string(),parameters:u.any(),metadata:u.record(u.any()).optional()}),Hp=u.object({id:u.string(),reason:u.string(),message:u.string().optional(),toolCallId:u.string().optional(),responseSchema:u.record(u.any()).optional(),expiresAt:u.string().optional(),metadata:u.record(u.any()).optional()}),Gp=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),Fp=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(sl),tools:u.array(al),context:u.array(Up),forwardedProps:u.any(),resume:u.array(Gp).optional()}),$p=u.any(),Q=class extends Error{constructor(t){super(t)}},ss=class extends Q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},zp=u.object({name:u.string(),description:u.string().optional()}),Bp=u.object({name:u.string().optional(),type:u.string().optional(),description:u.string().optional(),version:u.string().optional(),provider:u.string().optional(),documentationUrl:u.string().optional(),metadata:u.record(u.unknown()).optional()}),jp=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),Vp=u.object({supported:u.boolean().optional(),items:u.array(al).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),Wp=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),qp=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),Xp=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(zp).optional()}),Kp=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),Zp=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),Yp=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),Jp=u.object({input:Zp.optional(),output:Yp.optional()}),Qp=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),ef=u.object({supported:u.boolean().optional(),approvals:u.boolean().optional(),interventions:u.boolean().optional(),feedback:u.boolean().optional(),interrupts:u.boolean().optional(),approveWithEdits:u.boolean().optional()}),nb=u.object({identity:Bp.optional(),transport:jp.optional(),tools:Vp.optional(),output:Wp.optional(),state:qp.optional(),multiAgent:Xp.optional(),reasoning:Kp.optional(),multimodal:Jp.optional(),execution:Qp.optional(),humanInTheLoop:ef.optional(),custom:u.record(u.unknown()).optional()}),ll=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user")]),v=(function(t){return t.TEXT_MESSAGE_START="TEXT_MESSAGE_START",t.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",t.TEXT_MESSAGE_END="TEXT_MESSAGE_END",t.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",t.TOOL_CALL_START="TOOL_CALL_START",t.TOOL_CALL_ARGS="TOOL_CALL_ARGS",t.TOOL_CALL_END="TOOL_CALL_END",t.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",t.TOOL_CALL_RESULT="TOOL_CALL_RESULT",t.THINKING_START="THINKING_START",t.THINKING_END="THINKING_END",t.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",t.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",t.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",t.STATE_SNAPSHOT="STATE_SNAPSHOT",t.STATE_DELTA="STATE_DELTA",t.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",t.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",t.ACTIVITY_DELTA="ACTIVITY_DELTA",t.RAW="RAW",t.CUSTOM="CUSTOM",t.RUN_STARTED="RUN_STARTED",t.RUN_FINISHED="RUN_FINISHED",t.RUN_ERROR="RUN_ERROR",t.STEP_STARTED="STEP_STARTED",t.STEP_FINISHED="STEP_FINISHED",t.REASONING_START="REASONING_START",t.REASONING_MESSAGE_START="REASONING_MESSAGE_START",t.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",t.REASONING_MESSAGE_END="REASONING_MESSAGE_END",t.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",t.REASONING_END="REASONING_END",t.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",t})({}),q=u.object({type:u.nativeEnum(v),timestamp:u.number().optional(),rawEvent:u.any().optional()}).passthrough(),tf=q.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:ll.default("assistant"),name:u.string().optional()}),cl=q.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),nf=q.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),rf=q.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:ll.optional(),delta:u.string().optional(),name:u.string().optional()}),of=q.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),sf=cl.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),af=q.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),lf=q.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),cf=q.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),uf=q.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),df=q.extend({messageId:u.string(),type:u.literal(v.TOOL_CALL_RESULT),toolCallId:u.string(),content:u.string(),role:u.literal("tool").optional()}),pf=q.extend({type:u.literal(v.TOOL_CALL_CHUNK),toolCallId:u.string().optional(),toolCallName:u.string().optional(),parentMessageId:u.string().optional(),delta:u.string().optional()}),ff=q.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),hf=q.extend({type:u.literal(v.THINKING_END)}),mf=q.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:$p}),gf=q.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),vf=q.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(sl)}),bf=q.extend({type:u.literal(v.ACTIVITY_SNAPSHOT),messageId:u.string(),activityType:u.string(),content:u.record(u.any()),replace:u.boolean().optional().default(!0)}),yf=q.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),xf=q.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),Ef=q.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),Tf=q.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:Fp.optional()}),Sf=u.object({type:u.literal("success")}).strict(),wf=u.object({type:u.literal("interrupt"),interrupts:u.array(Hp).min(1)}).strict(),_f=u.discriminatedUnion("type",[Sf,wf]),Af=q.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:_f.nullable().optional().transform(t=>t??void 0)}),kf=q.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),If=q.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),Cf=q.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),Nf=u.union([u.literal("tool-call"),u.literal("message")]),Rf=q.extend({type:u.literal(v.REASONING_START),messageId:u.string()}),Of=q.extend({type:u.literal(v.REASONING_MESSAGE_START),messageId:u.string(),role:u.literal("reasoning")}),Mf=q.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),Lf=q.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),Pf=q.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),Df=q.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),Uf=q.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:Nf,entityId:u.string(),encryptedValue:u.string()}),Or=u.discriminatedUnion("type",[tf,cl,nf,rf,ff,hf,of,sf,af,lf,cf,uf,pf,df,mf,gf,vf,bf,yf,xf,Ef,Tf,Af,kf,If,Cf,Rf,Of,Mf,Lf,Pf,Df,Uf]);var as={};Ii(as,{JsonPatchError:()=>oe,_areEquals:()=>jn,applyOperation:()=>jt,applyPatch:()=>Gr,applyReducer:()=>zf,deepClone:()=>Ff,getValueByPointer:()=>Ur,validate:()=>dl,validator:()=>Hr});var Hf=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)o.hasOwnProperty(i)&&(r[i]=o[i])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Gf=Object.prototype.hasOwnProperty;function Lr(t,e){return Gf.call(t,e)}function Pr(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n<e.length;n++)e[n]=""+n;return e}if(Object.keys)return Object.keys(t);var r=[];for(var o in t)Lr(t,o)&&r.push(o);return r}function ye(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Dr(t){for(var e=0,n=t.length,r;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function tt(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function zn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Mr(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Mr(t[e]))return!0}else if(typeof t=="object"){for(var r=Pr(t),o=r.length,i=0;i<o;i++)if(Mr(t[r[i]]))return!0}}return!1}function ul(t,e){var n=[t];for(var r in e){var o=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof o<"u"&&n.push(r+": "+o)}return n.join(`
|
|
2
|
-
`)}var Bn=(function(t){Hf(e,t);function e(n,r,o,i,s){var a=this.constructor,l=t.call(this,ul(n,{name:r,index:o,operation:i,tree:s}))||this;return l.name=r,l.index=o,l.operation=i,l.tree=s,Object.setPrototypeOf(l,a.prototype),l.message=ul(n,{name:r,index:o,operation:i,tree:s}),l}return e})(Error);var oe=Bn,Ff=ye,hn={add:function(t,e,n){return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){var r=Ur(n,this.path);r&&(r=ye(r));var o=jt(n,{op:"remove",path:this.from}).removed;return jt(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=Ur(n,this.from);return jt(n,{op:"add",path:this.path,value:ye(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:jn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},$f={add:function(t,e,n){return Dr(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){var r=t.splice(e,1);return{newDocument:n,removed:r[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:hn.move,copy:hn.copy,test:hn.test,_get:hn._get};function Ur(t,e){if(e=="")return t;var n={op:"_get",path:e};return jt(t,n),n.value}function jt(t,e,n,r,o,i){if(n===void 0&&(n=!1),r===void 0&&(r=!0),o===void 0&&(o=!0),i===void 0&&(i=0),n&&(typeof n=="function"?n(e,0,t,e.path):Hr(e,0)),e.path===""){var s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=Ur(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=jn(t,e.value),s.test===!1)throw new oe("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(n)throw new oe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{r||(t=ye(t));var a=e.path||"",l=a.split("/"),c=t,p=1,m=l.length,b=void 0,h=void 0,d=void 0;for(typeof n=="function"?d=n:d=Hr;;){if(h=l[p],h&&h.indexOf("~")!=-1&&(h=zn(h)),o&&(h=="__proto__"||h=="prototype"&&p>0&&l[p-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&b===void 0&&(c[h]===void 0?b=l.slice(0,p).join("/"):p==m-1&&(b=e.path),b!==void 0&&d(e,0,t,b)),p++,Array.isArray(c)){if(h==="-")h=c.length;else{if(n&&!Dr(h))throw new oe("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);Dr(h)&&(h=~~h)}if(p>=m){if(n&&e.op==="add"&&h>c.length)throw new oe("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);var s=$f[e.op].call(e,c,h,t);if(s.test===!1)throw new oe("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}}else if(p>=m){var s=hn[e.op].call(e,c,h,t);if(s.test===!1)throw new oe("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}if(c=c[h],n&&p<m&&(!c||typeof c!="object"))throw new oe("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function Gr(t,e,n,r,o){if(r===void 0&&(r=!0),o===void 0&&(o=!0),n&&!Array.isArray(e))throw new oe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=ye(t));for(var i=new Array(e.length),s=0,a=e.length;s<a;s++)i[s]=jt(t,e[s],n,!0,o,s),t=i[s].newDocument;return i.newDocument=t,i}function zf(t,e,n){var r=jt(t,e);if(r.test===!1)throw new oe("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Hr(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new oe("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(hn[t.op]){if(typeof t.path!="string")throw new oe("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new oe('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new oe("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new oe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Mr(t.value))throw new oe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,i=r.split("/").length;if(o!==i+1&&o!==i)throw new oe("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new oe("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var s={op:"_get",path:t.from,value:void 0},a=dl([s],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new oe("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new oe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function dl(t,e,n){try{if(!Array.isArray(t))throw new oe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Gr(ye(e),ye(t),n||!0);else{n=n||Hr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof oe)return o;throw o}}function jn(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),o,i,s;if(n&&r){if(i=t.length,i!=e.length)return!1;for(o=i;o--!==0;)if(!jn(t[o],e[o]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(i=a.length,i!==Object.keys(e).length)return!1;for(o=i;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=i;o--!==0;)if(s=a[o],!jn(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var ds={};Ii(ds,{compare:()=>Zf,generate:()=>ls,observe:()=>Kf,unobserve:()=>Xf});var cs=new WeakMap,Bf=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),jf=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function Vf(t){return cs.get(t)}function Wf(t,e){return t.observers.get(e)}function qf(t,e){t.observers.delete(e.callback)}function Xf(t,e){e.unobserve()}function Kf(t,e){var n=[],r,o=Vf(t);if(!o)o=new Bf(t),cs.set(t,o);else{var i=Wf(o,e);r=i&&i.observer}if(r)return r;if(r={},o.value=ye(t),e){r.callback=e,r.next=null;var s=function(){ls(r)},a=function(){clearTimeout(r.next),r.next=setTimeout(s)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return r.patches=n,r.object=t,r.unobserve=function(){ls(r),clearTimeout(r.next),qf(o,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(e,new jf(e,r)),r}function ls(t,e){e===void 0&&(e=!1);var n=cs.get(t.object);us(n.value,t.object,t.patches,"",e),t.patches.length&&Gr(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function us(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=Pr(e),s=Pr(t),a=!1,l=!1,c=s.length-1;c>=0;c--){var p=s[c],m=t[p];if(Lr(e,p)&&!(e[p]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var b=e[p];typeof m=="object"&&m!=null&&typeof b=="object"&&b!=null&&Array.isArray(m)===Array.isArray(b)?us(m,b,n,r+"/"+tt(p),o):m!==b&&(a=!0,o&&n.push({op:"test",path:r+"/"+tt(p),value:ye(m)}),n.push({op:"replace",path:r+"/"+tt(p),value:ye(b)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+tt(p),value:ye(m)}),n.push({op:"remove",path:r+"/"+tt(p)}),l=!0):(o&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!l&&i.length==s.length))for(var c=0;c<i.length;c++){var p=i[c];!Lr(t,p)&&e[p]!==void 0&&n.push({op:"add",path:r+"/"+tt(p),value:ye(e[p])})}}}function Zf(t,e,n){n===void 0&&(n=!1);var r=[];return us(t,e,r,"",n),r}var Fr=Object.assign({},as,ds,{JsonPatchError:Bn,deepClone:ye,escapePathComponent:tt,unescapePathComponent:zn});var ps=function(t,e){return ps=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},ps(t,e)};function nt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ps(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function pl(t,e,n,r){function o(i){return i instanceof n?i:new n(function(s){s(i)})}return new(n||(n=Promise))(function(i,s){function a(p){try{c(r.next(p))}catch(m){s(m)}}function l(p){try{c(r.throw(p))}catch(m){s(m)}}function c(p){p.done?i(p.value):o(p.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}function $r(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,o,i,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(p){return l([c,p])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(n=0)),n;)try{if(r=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,o=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){n.label=c[1];break}if(c[0]===6&&n.label<i[1]){n.label=i[1],i=c;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(c);break}i[2]&&n.ops.pop(),n.trys.pop();continue}c=e.call(t,n)}catch(p){c=[6,p],o=0}finally{r=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ft(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function mn(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return i}function gn(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}function Vt(t){return this instanceof Vt?(this.v=t,this):new Vt(t)}function fl(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,i=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",s),o[Symbol.asyncIterator]=function(){return this},o;function s(h){return function(d){return Promise.resolve(d).then(h,m)}}function a(h,d){r[h]&&(o[h]=function(g){return new Promise(function(x,S){i.push([h,g,x,S])>1||l(h,g)})},d&&(o[h]=d(o[h])))}function l(h,d){try{c(r[h](d))}catch(g){b(i[0][3],g)}}function c(h){h.value instanceof Vt?Promise.resolve(h.value.v).then(p,m):b(i[0][2],h)}function p(h){l("next",h)}function m(h){l("throw",h)}function b(h,d){h(d),i.shift(),i.length&&l(i[0][0],i[0][1])}}function hl(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof ft=="function"?ft(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=t[i]&&function(s){return new Promise(function(a,l){s=t[i](s),o(a,l,s.done,s.value)})}}function o(i,s,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},s)}}function z(t){return typeof t=="function"}function vn(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var zr=vn(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
3
|
-
`+n.map(function(r,
|
|
4
|
-
`):"",this.name="UnsubscriptionError",this.errors=n}});function Vn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var bn=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=ft(s),l=a.next();!l.done;l=a.next()){var c=l.value;c.remove(this)}}catch(g){e={error:g}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}else s.remove(this);var p=this.initialTeardown;if(z(p))try{p()}catch(g){i=g instanceof zr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var b=ft(m),h=b.next();!h.done;h=b.next()){var d=h.value;try{ml(d)}catch(g){i=i??[],g instanceof zr?i=gn(gn([],mn(i)),mn(g.errors)):i.push(g)}}}catch(g){r={error:g}}finally{try{h&&!h.done&&(o=b.return)&&o.call(b)}finally{if(r)throw r.error}}}if(i)throw new zr(i)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)ml(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&Vn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&Vn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var fs=bn.EMPTY;function Br(t){return t instanceof bn||t&&"closed"in t&&z(t.remove)&&z(t.add)&&z(t.unsubscribe)}function ml(t){z(t)?t():t.unsubscribe()}var je={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var yn={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=yn.delegate;return o?.setTimeout?o.setTimeout.apply(o,gn([t,e],mn(n))):setTimeout.apply(void 0,gn([t,e],mn(n)))},clearTimeout:function(t){var e=yn.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function jr(t){yn.setTimeout(function(){var e=je.onUnhandledError;if(e)e(t);else throw t})}function Wn(){}var gl=(function(){return hs("C",void 0,void 0)})();function vl(t){return hs("E",void 0,t)}function bl(t){return hs("N",t,void 0)}function hs(t,e,n){return{kind:t,value:e,error:n}}var Wt=null;function xn(t){if(je.useDeprecatedSynchronousErrorHandling){var e=!Wt;if(e&&(Wt={errorThrown:!1,error:null}),t(),e){var n=Wt,r=n.errorThrown,o=n.error;if(Wt=null,r)throw o}}else t()}function yl(t){je.useDeprecatedSynchronousErrorHandling&&Wt&&(Wt.errorThrown=!0,Wt.error=t)}var qn=(function(t){nt(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Br(n)&&n.add(r)):r.destination=eh,r}return e.create=function(n,r,o){return new Wr(n,r,o)},e.prototype.next=function(n){this.isStopped?gs(bl(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?gs(vl(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?gs(gl,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(bn);var Yf=Function.prototype.bind;function ms(t,e){return Yf.call(t,e)}var Jf=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){Vr(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){Vr(r)}else Vr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){Vr(n)}},t})(),Wr=(function(t){nt(e,t);function e(n,r,o){var i=t.call(this)||this,s;if(z(n)||!n)s={next:n??void 0,error:r??void 0,complete:o??void 0};else{var a;i&&je.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return i.unsubscribe()},s={next:n.next&&ms(n.next,a),error:n.error&&ms(n.error,a),complete:n.complete&&ms(n.complete,a)}):s=n}return i.destination=new Jf(s),i}return e})(qn);function Vr(t){je.useDeprecatedSynchronousErrorHandling?yl(t):jr(t)}function Qf(t){throw t}function gs(t,e){var n=je.onStoppedNotification;n&&yn.setTimeout(function(){return n(t,e)})}var eh={closed:!0,next:Wn,error:Qf,complete:Wn};var En=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Tn(t){return t}function qr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return vs(t)}function vs(t){return t.length===0?Tn:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var ee=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,i=nh(e)?e:new Wr(e,n,r);return xn(function(){var s=o,a=s.operator,l=s.source;i.add(a?a.call(i,l):l?o._subscribe(i):o._trySubscribe(i))}),i},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=xl(n),new n(function(o,i){var s=new Wr({next:function(a){try{e(a)}catch(l){i(l),s.unsubscribe()}},error:i,complete:o});r.subscribe(s)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[En]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return vs(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=xl(e),new e(function(r,o){var i;n.subscribe(function(s){return i=s},function(s){return o(s)},function(){return r(i)})})},t.create=function(e){return new t(e)},t})();function xl(t){var e;return(e=t??je.Promise)!==null&&e!==void 0?e:Promise}function th(t){return t&&z(t.next)&&z(t.error)&&z(t.complete)}function nh(t){return t&&t instanceof qn||th(t)&&Br(t)}function rh(t){return z(t?.lift)}function de(t){return function(e){if(rh(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function me(t,e,n,r,o){return new oh(t,e,n,r,o)}var oh=(function(t){nt(e,t);function e(n,r,o,i,s,a){var l=t.call(this,n)||this;return l.onFinalize=s,l.shouldUnsubscribe=a,l._next=r?function(c){try{r(c)}catch(p){n.error(p)}}:t.prototype._next,l._error=i?function(c){try{i(c)}catch(p){n.error(p)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(c){n.error(c)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e})(qn);var El=vn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var rt=(function(t){nt(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new Tl(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new El},e.prototype.next=function(n){var r=this;xn(function(){var o,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var s=ft(r.currentObservers),a=s.next();!a.done;a=s.next()){var l=a.value;l.next(n)}}catch(c){o={error:c}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}}})},e.prototype.error=function(n){var r=this;xn(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;xn(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,i=o.hasError,s=o.isStopped,a=o.observers;return i||s?fs:(this.currentObservers=null,a.push(n),new bn(function(){r.currentObservers=null,Vn(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,i=r.thrownError,s=r.isStopped;o?n.error(i):s&&n.complete()},e.prototype.asObservable=function(){var n=new ee;return n.source=this,n},e.create=function(n,r){return new Tl(n,r)},e})(ee);var Tl=(function(t){nt(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:fs},e})(rt);var bs={now:function(){return(bs.delegate||Date).now()},delegate:void 0};var Xr=(function(t){nt(e,t);function e(n,r,o){n===void 0&&(n=1/0),r===void 0&&(r=1/0),o===void 0&&(o=bs);var i=t.call(this)||this;return i._bufferSize=n,i._windowTime=r,i._timestampProvider=o,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=r===1/0,i._bufferSize=Math.max(1,n),i._windowTime=Math.max(1,r),i}return e.prototype.next=function(n){var r=this,o=r.isStopped,i=r._buffer,s=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;o||(i.push(n),!s&&i.push(a.now()+l)),this._trimBuffer(),t.prototype.next.call(this,n)},e.prototype._subscribe=function(n){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(n),o=this,i=o._infiniteTimeWindow,s=o._buffer,a=s.slice(),l=0;l<a.length&&!n.closed;l+=i?1:2)n.next(a[l]);return this._checkFinalizedStatuses(n),r},e.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,o=n._timestampProvider,i=n._buffer,s=n._infiniteTimeWindow,a=(s?1:2)*r;if(r<1/0&&a<i.length&&i.splice(0,i.length-a),!s){for(var l=o.now(),c=0,p=1;p<i.length&&i[p]<=l;p+=2)c=p;c&&i.splice(0,c+1)}},e})(rt);var Kr=new ee(function(t){return t.complete()});function Sl(t){return t&&z(t.schedule)}function ih(t){return t[t.length-1]}function wl(t){return Sl(ih(t))?t.pop():void 0}var Zr=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function Yr(t){return z(t?.then)}function Jr(t){return z(t[En])}function Qr(t){return Symbol.asyncIterator&&z(t?.[Symbol.asyncIterator])}function eo(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function sh(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var to=sh();function no(t){return z(t?.[to])}function ro(t){return fl(this,arguments,function(){var n,r,o,i;return $r(this,function(s){switch(s.label){case 0:n=t.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,Vt(n.read())];case 3:return r=s.sent(),o=r.value,i=r.done,i?[4,Vt(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,Vt(o)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function oo(t){return z(t?.getReader)}function ge(t){if(t instanceof ee)return t;if(t!=null){if(Jr(t))return ah(t);if(Zr(t))return lh(t);if(Yr(t))return ch(t);if(Qr(t))return _l(t);if(no(t))return uh(t);if(oo(t))return dh(t)}throw eo(t)}function ah(t){return new ee(function(e){var n=t[En]();if(z(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function lh(t){return new ee(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function ch(t){return new ee(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,jr)})}function uh(t){return new ee(function(e){var n,r;try{for(var o=ft(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(a){n={error:a}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function _l(t){return new ee(function(e){ph(t,e).catch(function(n){return e.error(n)})})}function dh(t){return _l(ro(t))}function ph(t,e){var n,r,o,i;return pl(this,void 0,void 0,function(){var s,a;return $r(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=hl(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(s=r.value,e.next(s),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),o={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(i=n.return)?[4,i.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function He(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var i=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(i),!o)return i}function io(t,e){return e===void 0&&(e=0),de(function(n,r){n.subscribe(me(r,function(o){return He(r,t,function(){return r.next(o)},e)},function(){return He(r,t,function(){return r.complete()},e)},function(o){return He(r,t,function(){return r.error(o)},e)}))})}function so(t,e){return e===void 0&&(e=0),de(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function Al(t,e){return ge(t).pipe(so(e),io(e))}function kl(t,e){return ge(t).pipe(so(e),io(e))}function Il(t,e){return new ee(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function Cl(t,e){return new ee(function(n){var r;return He(n,e,function(){r=t[to](),He(n,e,function(){var o,i,s;try{o=r.next(),i=o.value,s=o.done}catch(a){n.error(a);return}s?n.complete():n.next(i)},0,!0)}),function(){return z(r?.return)&&r.return()}})}function ao(t,e){if(!t)throw new Error("Iterable cannot be null");return new ee(function(n){He(n,e,function(){var r=t[Symbol.asyncIterator]();He(n,e,function(){r.next().then(function(o){o.done?n.complete():n.next(o.value)})},0,!0)})})}function Nl(t,e){return ao(ro(t),e)}function Rl(t,e){if(t!=null){if(Jr(t))return Al(t,e);if(Zr(t))return Il(t,e);if(Yr(t))return kl(t,e);if(Qr(t))return ao(t,e);if(no(t))return Cl(t,e);if(oo(t))return Nl(t,e)}throw eo(t)}function qt(t,e){return e?Rl(t,e):ge(t)}function ne(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=wl(t);return qt(t,n)}function te(t,e){var n=z(t)?t:function(){return t},r=function(o){return o.error(n())};return new ee(e?function(o){return e.schedule(r,0,o)}:r)}var Ol=vn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function lo(t,e){var n=typeof e=="object";return new Promise(function(r,o){var i=!1,s;t.subscribe({next:function(a){s=a,i=!0},error:o,complete:function(){i?r(s):n?r(e.defaultValue):o(new Ol)}})})}function Xt(t,e){return de(function(n,r){var o=0;n.subscribe(me(r,function(i){r.next(t.call(e,i,o++))}))})}function Ml(t,e,n,r,o,i,s,a){var l=[],c=0,p=0,m=!1,b=function(){m&&!l.length&&!c&&e.complete()},h=function(g){return c<r?d(g):l.push(g)},d=function(g){i&&e.next(g),c++;var x=!1;ge(n(g,p++)).subscribe(me(e,function(S){o?.(S),i?h(S):e.next(S)},function(){x=!0},void 0,function(){if(x)try{c--;for(var S=function(){var E=l.shift();s?He(e,s,function(){return d(E)}):d(E)};l.length&&c<r;)S();b()}catch(E){e.error(E)}}))};return t.subscribe(me(e,h,function(){m=!0,b()})),function(){a?.()}}function Ce(t,e,n){return n===void 0&&(n=1/0),z(e)?Ce(function(r,o){return Xt(function(i,s){return e(r,i,o,s)})(ge(t(r,o)))},n):(typeof e=="number"&&(n=e),de(function(r,o){return Ml(r,o,t,n)}))}function ys(t){return t===void 0&&(t=1/0),Ce(Tn,t)}function co(t){return new ee(function(e){ge(t()).subscribe(e)})}function Xn(t){return de(function(e,n){var r=null,o=!1,i;r=e.subscribe(me(n,void 0,void 0,function(s){i=ge(t(s,Xn(t)(e))),r?(r.unsubscribe(),r=null,i.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,i.subscribe(n))})}function uo(t,e){return z(e)?Ce(t,e,1):Ce(t,1)}function xs(t){return de(function(e,n){var r=!1;e.subscribe(me(n,function(o){r=!0,n.next(o)},function(){r||n.next(t),n.complete()}))})}function Kt(t){return de(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function Es(t,e){return de(function(n,r){var o=null,i=0,s=!1,a=function(){return s&&!o&&r.complete()};n.subscribe(me(r,function(l){o?.unsubscribe();var c=0,p=i++;ge(t(l,p)).subscribe(o=me(r,function(m){return r.next(e?e(l,m,p,c++):m)},function(){o=null,a()}))},function(){s=!0,a()}))})}function po(t){return de(function(e,n){ge(t).subscribe(me(n,function(){return n.complete()},Wn)),!n.closed&&e.subscribe(n)})}function Ts(t,e,n){var r=z(t)||e||n?{next:t,error:e,complete:n}:t;return r?de(function(o,i){var s;(s=r.subscribe)===null||s===void 0||s.call(r);var a=!0;o.subscribe(me(i,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),i.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),i.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),i.error(l)},function(){var l,c;a&&((l=r.unsubscribe)===null||l===void 0||l.call(r)),(c=r.finalize)===null||c===void 0||c.call(r)}))}):Tn}function Ll(t){return` \r
|
|
5
|
-
`.indexOf(t)>=0}function fo(t){for(var e=["topLevel"],n=0,r,o,i,s=function(E){return e.push(E)},a=function(E){return e[e.length-1]=E},l=function(E){r==null&&(r=n,o=e.length,i=E)},c=function(E){E===i&&(r=void 0,o=void 0,i=void 0)},p=function(){return e.pop()},m=function(){return n--},b=function(E){if("0"<=E&&E<="9"){s("number");return}switch(E){case'"':s("string");return;case"-":s("numberNeedsDigit");return;case"t":s("true");return;case"f":s("false");return;case"n":s("null");return;case"[":s("arrayNeedsValue");return;case"{":s("objectNeedsKey");return}},h=t.length;n<h;n++){var d=t[n];switch(e[e.length-1]){case"topLevel":b(d);break;case"string":switch(d){case'"':p();break;case"\\":l("stringEscape"),s("stringEscaped");break}break;case"stringEscaped":d==="u"?s("stringUnicode"):(c("stringEscape"),p());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(c("stringEscape"),p());break;case"number":d==="."?a("numberNeedsDigit"):d==="e"||d==="E"?a("numberNeedsExponent"):(d<"0"||d>"9")&&(m(),p());break;case"numberNeedsDigit":a("number");break;case"numberNeedsExponent":a(d==="+"||d==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(d<"a"||d>"z")&&(m(),p());break;case"arrayNeedsValue":d==="]"?p():Ll(d)||(c("collectionItem"),a("arrayNeedsComma"),b(d));break;case"arrayNeedsComma":d==="]"?p():d===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":d==="}"?p():d==='"'&&(l("collectionItem"),a("objectNeedsColon"),s("string"));break;case"objectNeedsColon":d===":"&&a("objectNeedsValue");break;case"objectNeedsValue":Ll(d)||(c("collectionItem"),a("objectNeedsComma"),b(d));break;case"objectNeedsComma":d==="}"?p():d===","&&(l("collectionItem"),a("objectNeedsKey"));break}}o!=null&&(e.length=o);for(var g=[r!=null?t.slice(0,r):t],x=function(E){return g.push(E.slice(t.length-t.lastIndexOf(E[0])))},S=e.length-1;S>=0;S--)switch(e[S]){case"string":g.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":g.push("0");break;case"true":x("true");break;case"false":x("false");break;case"null":x("null");break;case"arrayNeedsValue":case"arrayNeedsComma":g.push("]");break;case"objectNeedsKey":case"objectNeedsColon":case"objectNeedsValue":case"objectNeedsComma":g.push("}");break}return g.join("")}function Dl(){let t=0,e=0;for(let r=0;r<28;r+=7){let o=this.buf[this.pos++];if(t|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let r=3;r<=31;r+=7){let o=this.buf[this.pos++];if(e|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function mo(t,e,n){for(let i=0;i<28;i=i+7){let s=t>>>i,a=!(!(s>>>7)&&e==0),l=(a?s|128:s)&255;if(n.push(l),!a)return}let r=t>>>28&15|(e&7)<<4,o=e>>3!=0;if(n.push((o?r|128:r)&255),!!o){for(let i=3;i<31;i=i+7){let s=e>>>i,a=!!(s>>>7),l=(a?s|128:s)&255;if(n.push(l),!a)return}n.push(e>>>31&1)}}var ho=4294967296;function Ss(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,o=0;function i(s,a){let l=Number(t.slice(s,a));o*=n,r=r*n+l,r>=ho&&(o=o+(r/ho|0),r=r%ho)}return i(-24,-18),i(-18,-12),i(-12,-6),i(-6),e?Hl(r,o):_s(r,o)}function Ul(t,e){let n=_s(t,e),r=n.hi&2147483648;r&&(n=Hl(n.lo,n.hi));let o=ws(n.lo,n.hi);return r?"-"+o:o}function ws(t,e){if({lo:t,hi:e}=fh(t,e),e<=2097151)return String(ho*e+t);let n=t&16777215,r=(t>>>24|e<<8)&16777215,o=e>>16&65535,i=n+r*6777216+o*6710656,s=r+o*8147497,a=o*2,l=1e7;return i>=l&&(s+=Math.floor(i/l),i%=l),s>=l&&(a+=Math.floor(s/l),s%=l),a.toString()+Pl(s)+Pl(i)}function fh(t,e){return{lo:t>>>0,hi:e>>>0}}function _s(t,e){return{lo:t|0,hi:e|0}}function Hl(t,e){return e=~e,t?t=~t+1:e+=1,_s(t,e)}var Pl=t=>{let e=String(t);return"0000000".slice(e.length)+e};function As(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function Gl(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var Ve=hh();function hh(){let t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(!!globalThis.Deno||!!globalThis.Bun||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let n=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>r||a<n)throw new Error(`invalid int64: ${s}`);return a},uParse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>i||a<o)throw new Error(`invalid uint64: ${s}`);return a},enc(s){return t.setBigInt64(0,this.parse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(s){return t.setBigInt64(0,this.uParse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigInt64(0,!0)},uDec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),Fl(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),$l(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),Fl(n),Ss(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),$l(n),Ss(n)},dec(n,r){return Ul(n,r)},uDec(n,r){return ws(n,r)}}}function Fl(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function $l(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var ks=Symbol.for("@bufbuild/protobuf/text-encoding");function Is(){if(globalThis[ks]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[ks]={encodeUtf8(r){return t.encode(r)},decodeUtf8(r,o){return o?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(r)):e.decode(r)},checkUtf8(r){try{return encodeURIComponent(r),!0}catch{return!1}}}}return globalThis[ks]}var St;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(St||(St={}));var mh=34028234663852886e22,gh=-34028234663852886e22,vh=4294967295,bh=2147483647,yh=-2147483648,G=class{constructor(e=Is().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let o=0;o<this.chunks.length;o++)e+=this.chunks[o].length;let n=new Uint8Array(e),r=0;for(let o=0;o<this.chunks.length;o++)n.set(this.chunks[o],r),r+=this.chunks[o].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(zl(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Cs(e),As(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let n=this.encodeUtf8(e);return this.uint32(n.byteLength),this.raw(n)}float(e){xh(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){zl(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){Cs(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return Cs(e),e=(e<<1^e>>31)>>>0,As(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=Ve.enc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=Ve.uEnc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}int64(e){let n=Ve.enc(e);return mo(n.lo,n.hi,this.buf),this}sint64(e){let n=Ve.enc(e),r=n.hi>>31,o=n.lo<<1^r,i=(n.hi<<1|n.lo>>>31)^r;return mo(o,i,this.buf),this}uint64(e){let n=Ve.uEnc(e);return mo(n.lo,n.hi,this.buf),this}},w=class{constructor(e,n=Is().decodeUtf8){this.decodeUtf8=n,this.varint64=Dl,this.uint32=Gl,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,n=this.uint32(),r=this.pos-e;if(r>5||r==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let o=n>>>3,i=n&7;if(o<=0||i>5)throw new Error("illegal tag: field no "+o+" wire type "+i);return[o,i]}skip(e,n,r=100){let o=this.pos;switch(e){case St.Varint:for(;this.buf[this.pos++]&128;);break;case St.Bit64:this.pos+=4;case St.Bit32:this.pos+=4;break;case St.LengthDelimited:let i=this.uint32();this.pos+=i;break;case St.StartGroup:if(r<=0)throw new Error("maximum recursion depth reached");for(;;){let[s,a]=this.tag();if(a===St.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(a,s,r-1)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(o,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return Ve.dec(...this.varint64())}uint64(){return Ve.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),r=-(e&1);return e=(e>>>1|(n&1)<<31)^r,n=n>>>1^r,Ve.dec(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Ve.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Ve.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(e){return this.decodeUtf8(this.bytes(),e)}};function Cs(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid int32: "+typeof t);if(!Number.isInteger(t)||t>bh||t<yh)throw new Error("invalid int32: "+t)}function zl(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid uint32: "+typeof t);if(!Number.isInteger(t)||t>vh||t<0)throw new Error("invalid uint32: "+t)}function xh(t){if(typeof t=="string"){let e=t;if(t=Number(t),Number.isNaN(t)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof t!="number")throw new Error("invalid float32: "+typeof t);if(Number.isFinite(t)&&(t>mh||t<gh))throw new Error("invalid float32: "+t)}var Eh=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Ns(){return{fields:{}}}var Kn={encode(t,e=new G){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&Ms.encode({key:n,value:r},e.uint32(10).fork()).join()}),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Ns();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:{if(i!==10)break;let s=Ms.decode(n,n.uint32());s.value!==void 0&&(o.fields[s.key]=s.value);continue}}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Kn.fromPartial(t??{})},fromPartial(t){let e=Ns();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,o])=>(o!==void 0&&(n[r]=o),n),{}),e},wrap(t){let e=Ns();if(t!==void 0)for(let n of Object.keys(t))e.fields[n]=t[n];return e},unwrap(t){let e={};if(t.fields)for(let n of Object.keys(t.fields))e[n]=t.fields[n];return e}};function Bl(){return{key:"",value:void 0}}var Ms={encode(t,e=new G){return t.key!==""&&e.uint32(10).string(t.key),t.value!==void 0&&R.encode(R.wrap(t.value),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Bl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.key=n.string();continue;case 2:if(i!==18)break;o.value=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ms.fromPartial(t??{})},fromPartial(t){let e=Bl();return e.key=t.key??"",e.value=t.value??void 0,e}};function Rs(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var R={encode(t,e=new G){return t.nullValue!==void 0&&e.uint32(8).int32(t.nullValue),t.numberValue!==void 0&&e.uint32(17).double(t.numberValue),t.stringValue!==void 0&&e.uint32(26).string(t.stringValue),t.boolValue!==void 0&&e.uint32(32).bool(t.boolValue),t.structValue!==void 0&&Kn.encode(Kn.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&Zn.encode(Zn.wrap(t.listValue),e.uint32(50).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Rs();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.nullValue=n.int32();continue;case 2:if(i!==17)break;o.numberValue=n.double();continue;case 3:if(i!==26)break;o.stringValue=n.string();continue;case 4:if(i!==32)break;o.boolValue=n.bool();continue;case 5:if(i!==42)break;o.structValue=Kn.unwrap(Kn.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.listValue=Zn.unwrap(Zn.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return R.fromPartial(t??{})},fromPartial(t){let e=Rs();return e.nullValue=t.nullValue??void 0,e.numberValue=t.numberValue??void 0,e.stringValue=t.stringValue??void 0,e.boolValue=t.boolValue??void 0,e.structValue=t.structValue??void 0,e.listValue=t.listValue??void 0,e},wrap(t){let e=Rs();if(t===null)e.nullValue=Eh.NULL_VALUE;else if(typeof t=="boolean")e.boolValue=t;else if(typeof t=="number")e.numberValue=t;else if(typeof t=="string")e.stringValue=t;else if(globalThis.Array.isArray(t))e.listValue=t;else if(typeof t=="object")e.structValue=t;else if(typeof t<"u")throw new globalThis.Error("Unsupported any value type: "+typeof t);return e},unwrap(t){if(t.stringValue!==void 0)return t.stringValue;if(t?.numberValue!==void 0)return t.numberValue;if(t?.boolValue!==void 0)return t.boolValue;if(t?.structValue!==void 0)return t.structValue;if(t?.listValue!==void 0)return t.listValue;if(t?.nullValue!==void 0)return null}};function Os(){return{values:[]}}var Zn={encode(t,e=new G){for(let n of t.values)R.encode(R.wrap(n),e.uint32(10).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Os();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.values.push(R.unwrap(R.decode(n,n.uint32())));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Zn.fromPartial(t??{})},fromPartial(t){let e=Os();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=Os();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},Th=(function(t){return t[t.ADD=0]="ADD",t[t.REMOVE=1]="REMOVE",t[t.REPLACE=2]="REPLACE",t[t.MOVE=3]="MOVE",t[t.COPY=4]="COPY",t[t.TEST=5]="TEST",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function jl(){return{op:0,path:"",from:void 0,value:void 0}}var vo={encode(t,e=new G){return t.op!==0&&e.uint32(8).int32(t.op),t.path!==""&&e.uint32(18).string(t.path),t.from!==void 0&&e.uint32(26).string(t.from),t.value!==void 0&&R.encode(R.wrap(t.value),e.uint32(34).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=jl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.op=n.int32();continue;case 2:if(i!==18)break;o.path=n.string();continue;case 3:if(i!==26)break;o.from=n.string();continue;case 4:if(i!==34)break;o.value=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return vo.fromPartial(t??{})},fromPartial(t){let e=jl();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function Vl(){return{id:"",type:"",function:void 0}}var bo={encode(t,e=new G){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&yo.encode(t.function,e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Vl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.type=n.string();continue;case 3:if(i!==26)break;o.function=yo.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return bo.fromPartial(t??{})},fromPartial(t){let e=Vl();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?yo.fromPartial(t.function):void 0,e}};function Wl(){return{name:"",arguments:""}}var yo={encode(t,e=new G){return t.name!==""&&e.uint32(10).string(t.name),t.arguments!==""&&e.uint32(18).string(t.arguments),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Wl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.name=n.string();continue;case 2:if(i!==18)break;o.arguments=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return yo.fromPartial(t??{})},fromPartial(t){let e=Wl();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function ql(){return{value:"",mimeType:""}}var xo={encode(t,e=new G){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==""&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=ql();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.value=n.string();continue;case 2:if(i!==18)break;o.mimeType=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return xo.fromPartial(t??{})},fromPartial(t){let e=ql();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function Xl(){return{value:"",mimeType:void 0}}var Eo={encode(t,e=new G){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==void 0&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Xl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.value=n.string();continue;case 2:if(i!==18)break;o.mimeType=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Eo.fromPartial(t??{})},fromPartial(t){let e=Xl();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function Kl(){return{data:void 0,url:void 0}}var Re={encode(t,e=new G){return t.data!==void 0&&xo.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&Eo.encode(t.url,e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Kl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.data=xo.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.url=Eo.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Re.fromPartial(t??{})},fromPartial(t){let e=Kl();return e.data=t.data!==void 0&&t.data!==null?xo.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?Eo.fromPartial(t.url):void 0,e}};function Zl(){return{text:""}}var To={encode(t,e=new G){return t.text!==""&&e.uint32(10).string(t.text),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Zl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return To.fromPartial(t??{})},fromPartial(t){let e=Zl();return e.text=t.text??"",e}};function Yl(){return{source:void 0,metadata:void 0}}var So={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Yl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Re.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return So.fromPartial(t??{})},fromPartial(t){let e=Yl();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Jl(){return{source:void 0,metadata:void 0}}var wo={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Jl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Re.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return wo.fromPartial(t??{})},fromPartial(t){let e=Jl();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Ql(){return{source:void 0,metadata:void 0}}var _o={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Ql();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Re.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return _o.fromPartial(t??{})},fromPartial(t){let e=Ql();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function ec(){return{source:void 0,metadata:void 0}}var Ao={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=ec();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Re.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ao.fromPartial(t??{})},fromPartial(t){let e=ec();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function tc(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var ko={encode(t,e=new G){return t.text!==void 0&&To.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&So.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&wo.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&_o.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&Ao.encode(t.document,e.uint32(42).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=tc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=To.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.image=So.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.audio=wo.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.video=_o.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.document=Ao.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ko.fromPartial(t??{})},fromPartial(t){let e=tc();return e.text=t.text!==void 0&&t.text!==null?To.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?So.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?wo.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?_o.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?Ao.fromPartial(t.document):void 0,e}};function nc(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var Io={encode(t,e=new G){t.id!==""&&e.uint32(10).string(t.id),t.role!==""&&e.uint32(18).string(t.role),t.content!==void 0&&e.uint32(26).string(t.content),t.name!==void 0&&e.uint32(34).string(t.name);for(let n of t.toolCalls)bo.encode(n,e.uint32(42).fork()).join();t.toolCallId!==void 0&&e.uint32(50).string(t.toolCallId),t.error!==void 0&&e.uint32(58).string(t.error);for(let n of t.contentParts)ko.encode(n,e.uint32(66).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=nc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.role=n.string();continue;case 3:if(i!==26)break;o.content=n.string();continue;case 4:if(i!==34)break;o.name=n.string();continue;case 5:if(i!==42)break;o.toolCalls.push(bo.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.toolCallId=n.string();continue;case 7:if(i!==58)break;o.error=n.string();continue;case 8:if(i!==66)break;o.contentParts.push(ko.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Io.fromPartial(t??{})},fromPartial(t){let e=nc();return e.id=t.id??"",e.role=t.role??"",e.content=t.content??void 0,e.name=t.name??void 0,e.toolCalls=t.toolCalls?.map(n=>bo.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>ko.fromPartial(n))||[],e}};function rc(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Co={encode(t,e=new G){return t.id!==""&&e.uint32(10).string(t.id),t.reason!==""&&e.uint32(18).string(t.reason),t.message!==void 0&&e.uint32(26).string(t.message),t.toolCallId!==void 0&&e.uint32(34).string(t.toolCallId),t.responseSchema!==void 0&&R.encode(R.wrap(t.responseSchema),e.uint32(42).fork()).join(),t.expiresAt!==void 0&&e.uint32(50).string(t.expiresAt),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(58).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=rc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.reason=n.string();continue;case 3:if(i!==26)break;o.message=n.string();continue;case 4:if(i!==34)break;o.toolCallId=n.string();continue;case 5:if(i!==42)break;o.responseSchema=R.unwrap(R.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.expiresAt=n.string();continue;case 7:if(i!==58)break;o.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Co.fromPartial(t??{})},fromPartial(t){let e=rc();return e.id=t.id??"",e.reason=t.reason??"",e.message=t.message??void 0,e.toolCallId=t.toolCallId??void 0,e.responseSchema=t.responseSchema??void 0,e.expiresAt=t.expiresAt??void 0,e.metadata=t.metadata??void 0,e}},Sh=(function(t){return t[t.TEXT_MESSAGE_START=0]="TEXT_MESSAGE_START",t[t.TEXT_MESSAGE_CONTENT=1]="TEXT_MESSAGE_CONTENT",t[t.TEXT_MESSAGE_END=2]="TEXT_MESSAGE_END",t[t.TOOL_CALL_START=3]="TOOL_CALL_START",t[t.TOOL_CALL_ARGS=4]="TOOL_CALL_ARGS",t[t.TOOL_CALL_END=5]="TOOL_CALL_END",t[t.STATE_SNAPSHOT=6]="STATE_SNAPSHOT",t[t.STATE_DELTA=7]="STATE_DELTA",t[t.MESSAGES_SNAPSHOT=8]="MESSAGES_SNAPSHOT",t[t.RAW=9]="RAW",t[t.CUSTOM=10]="CUSTOM",t[t.RUN_STARTED=11]="RUN_STARTED",t[t.RUN_FINISHED=12]="RUN_FINISHED",t[t.RUN_ERROR=13]="RUN_ERROR",t[t.STEP_STARTED=14]="STEP_STARTED",t[t.STEP_FINISHED=15]="STEP_FINISHED",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function oc(){return{type:0,timestamp:void 0,rawEvent:void 0}}var O={encode(t,e=new G){return t.type!==0&&e.uint32(8).int32(t.type),t.timestamp!==void 0&&e.uint32(16).int64(t.timestamp),t.rawEvent!==void 0&&R.encode(R.wrap(t.rawEvent),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=oc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.type=n.int32();continue;case 2:if(i!==16)break;o.timestamp=wh(n.int64());continue;case 3:if(i!==26)break;o.rawEvent=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return O.fromPartial(t??{})},fromPartial(t){let e=oc();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function ic(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var No={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.name!==void 0&&e.uint32(34).string(t.name),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=ic();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.role=n.string();continue;case 4:if(i!==34)break;o.name=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return No.fromPartial(t??{})},fromPartial(t){let e=ic();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.role=t.role??void 0,e.name=t.name??void 0,e}};function sc(){return{baseEvent:void 0,messageId:"",delta:""}}var Ro={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=sc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ro.fromPartial(t??{})},fromPartial(t){let e=sc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.delta=t.delta??"",e}};function ac(){return{baseEvent:void 0,messageId:""}}var Oo={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=ac();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Oo.fromPartial(t??{})},fromPartial(t){let e=ac();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function lc(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Mo={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.toolCallName!==""&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=lc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.toolCallName=n.string();continue;case 4:if(i!==34)break;o.parentMessageId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Mo.fromPartial(t??{})},fromPartial(t){let e=lc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.toolCallName=t.toolCallName??"",e.parentMessageId=t.parentMessageId??void 0,e}};function cc(){return{baseEvent:void 0,toolCallId:"",delta:""}}var Lo={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=cc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Lo.fromPartial(t??{})},fromPartial(t){let e=cc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.delta=t.delta??"",e}};function uc(){return{baseEvent:void 0,toolCallId:""}}var Po={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=uc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Po.fromPartial(t??{})},fromPartial(t){let e=uc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function dc(){return{baseEvent:void 0,snapshot:void 0}}var Do={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.snapshot!==void 0&&R.encode(R.wrap(t.snapshot),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=dc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.snapshot=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Do.fromPartial(t??{})},fromPartial(t){let e=dc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function pc(){return{baseEvent:void 0,delta:[]}}var Uo={encode(t,e=new G){t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)vo.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=pc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.delta.push(vo.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Uo.fromPartial(t??{})},fromPartial(t){let e=pc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>vo.fromPartial(n))||[],e}};function fc(){return{baseEvent:void 0,messages:[]}}var Ho={encode(t,e=new G){t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)Io.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=fc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messages.push(Io.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ho.fromPartial(t??{})},fromPartial(t){let e=fc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>Io.fromPartial(n))||[],e}};function hc(){return{baseEvent:void 0,event:void 0,source:void 0}}var Go={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.event!==void 0&&R.encode(R.wrap(t.event),e.uint32(18).fork()).join(),t.source!==void 0&&e.uint32(26).string(t.source),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=hc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.event=R.unwrap(R.decode(n,n.uint32()));continue;case 3:if(i!==26)break;o.source=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Go.fromPartial(t??{})},fromPartial(t){let e=hc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.event=t.event??void 0,e.source=t.source??void 0,e}};function mc(){return{baseEvent:void 0,name:"",value:void 0}}var Fo={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.name!==""&&e.uint32(18).string(t.name),t.value!==void 0&&R.encode(R.wrap(t.value),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=mc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.name=n.string();continue;case 3:if(i!==26)break;o.value=R.unwrap(R.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Fo.fromPartial(t??{})},fromPartial(t){let e=mc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.name=t.name??"",e.value=t.value??void 0,e}};function gc(){return{baseEvent:void 0,threadId:"",runId:""}}var $o={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=gc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.threadId=n.string();continue;case 3:if(i!==26)break;o.runId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return $o.fromPartial(t??{})},fromPartial(t){let e=gc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e}};function vc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var zo={encode(t,e=new G){t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),t.result!==void 0&&R.encode(R.wrap(t.result),e.uint32(34).fork()).join(),t.outcome!==""&&e.uint32(42).string(t.outcome);for(let n of t.interrupts)Co.encode(n,e.uint32(50).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=vc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.threadId=n.string();continue;case 3:if(i!==26)break;o.runId=n.string();continue;case 4:if(i!==34)break;o.result=R.unwrap(R.decode(n,n.uint32()));continue;case 5:if(i!==42)break;o.outcome=n.string();continue;case 6:if(i!==50)break;o.interrupts.push(Co.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return zo.fromPartial(t??{})},fromPartial(t){let e=vc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e.result=t.result??void 0,e.outcome=t.outcome??"",e.interrupts=t.interrupts?.map(n=>Co.fromPartial(n))||[],e}};function bc(){return{baseEvent:void 0,code:void 0,message:""}}var Bo={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.code!==void 0&&e.uint32(18).string(t.code),t.message!==""&&e.uint32(26).string(t.message),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=bc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.code=n.string();continue;case 3:if(i!==26)break;o.message=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Bo.fromPartial(t??{})},fromPartial(t){let e=bc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.code=t.code??void 0,e.message=t.message??"",e}};function yc(){return{baseEvent:void 0,stepName:""}}var jo={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=yc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.stepName=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return jo.fromPartial(t??{})},fromPartial(t){let e=yc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function xc(){return{baseEvent:void 0,stepName:""}}var Vo={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=xc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.stepName=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Vo.fromPartial(t??{})},fromPartial(t){let e=xc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function Ec(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var Wo={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==void 0&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.delta!==void 0&&e.uint32(34).string(t.delta),t.name!==void 0&&e.uint32(42).string(t.name),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Ec();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.role=n.string();continue;case 4:if(i!==34)break;o.delta=n.string();continue;case 5:if(i!==42)break;o.name=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Wo.fromPartial(t??{})},fromPartial(t){let e=Ec();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??void 0,e.role=t.role??void 0,e.delta=t.delta??void 0,e.name=t.name??void 0,e}};function Tc(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var qo={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==void 0&&e.uint32(18).string(t.toolCallId),t.toolCallName!==void 0&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),t.delta!==void 0&&e.uint32(42).string(t.delta),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Tc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=O.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.toolCallName=n.string();continue;case 4:if(i!==34)break;o.parentMessageId=n.string();continue;case 5:if(i!==42)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return qo.fromPartial(t??{})},fromPartial(t){let e=Tc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??void 0,e.toolCallName=t.toolCallName??void 0,e.parentMessageId=t.parentMessageId??void 0,e.delta=t.delta??void 0,e}};function Sc(){return{textMessageStart:void 0,textMessageContent:void 0,textMessageEnd:void 0,toolCallStart:void 0,toolCallArgs:void 0,toolCallEnd:void 0,stateSnapshot:void 0,stateDelta:void 0,messagesSnapshot:void 0,raw:void 0,custom:void 0,runStarted:void 0,runFinished:void 0,runError:void 0,stepStarted:void 0,stepFinished:void 0,textMessageChunk:void 0,toolCallChunk:void 0}}var wc={encode(t,e=new G){return t.textMessageStart!==void 0&&No.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&Ro.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Oo.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Mo.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&Lo.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Po.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Do.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Uo.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Ho.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Go.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&Fo.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&$o.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&zo.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&Bo.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&jo.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&Vo.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&Wo.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&qo.encode(t.toolCallChunk,e.uint32(146).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,o=Sc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.textMessageStart=No.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.textMessageContent=Ro.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.textMessageEnd=Oo.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.toolCallStart=Mo.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.toolCallArgs=Lo.decode(n,n.uint32());continue;case 6:if(i!==50)break;o.toolCallEnd=Po.decode(n,n.uint32());continue;case 7:if(i!==58)break;o.stateSnapshot=Do.decode(n,n.uint32());continue;case 8:if(i!==66)break;o.stateDelta=Uo.decode(n,n.uint32());continue;case 9:if(i!==74)break;o.messagesSnapshot=Ho.decode(n,n.uint32());continue;case 10:if(i!==82)break;o.raw=Go.decode(n,n.uint32());continue;case 11:if(i!==90)break;o.custom=Fo.decode(n,n.uint32());continue;case 12:if(i!==98)break;o.runStarted=$o.decode(n,n.uint32());continue;case 13:if(i!==106)break;o.runFinished=zo.decode(n,n.uint32());continue;case 14:if(i!==114)break;o.runError=Bo.decode(n,n.uint32());continue;case 15:if(i!==122)break;o.stepStarted=jo.decode(n,n.uint32());continue;case 16:if(i!==130)break;o.stepFinished=Vo.decode(n,n.uint32());continue;case 17:if(i!==138)break;o.textMessageChunk=Wo.decode(n,n.uint32());continue;case 18:if(i!==146)break;o.toolCallChunk=qo.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return wc.fromPartial(t??{})},fromPartial(t){let e=Sc();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?No.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?Ro.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Oo.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Mo.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?Lo.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Po.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Do.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Uo.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Ho.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Go.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?Fo.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?$o.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?zo.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?Bo.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?jo.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?Vo.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?Wo.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?qo.fromPartial(t.toolCallChunk):void 0,e}};function wh(t){let e=globalThis.Number(t.toString());if(e>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(e<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return e}var go=t=>{if(!(!t||typeof t!="object")){if(t.data)return{type:"data",value:t.data.value,mimeType:t.data.mimeType};if(t.url)return{type:"url",value:t.url.value,mimeType:t.url.mimeType}}},_h=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:go(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:go(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:go(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:go(t.document.source),metadata:t.document.metadata}}};function _c(t){let e=wc.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=Sh[n.baseEvent.type],n.timestamp=n.baseEvent.timestamp,n.rawEvent=n.baseEvent.rawEvent,delete n.baseEvent,n.type===v.MESSAGES_SNAPSHOT)for(let r of n.messages){let o=r;if(o.role==="user"&&Array.isArray(o.contentParts)){let i=o.contentParts.map(s=>_h(s)).filter(s=>s!==void 0);i.length>0&&(o.content=i)}Array.isArray(o.contentParts)&&o.contentParts.length===0&&(o.contentParts=void 0),o.toolCalls?.length===0&&(o.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,o=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,i=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,o==="interrupt"?r.outcome={type:"interrupt",interrupts:i}:o==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=Th[r.op].toLowerCase(),Object.keys(r).forEach(o=>{r[o]===void 0&&delete r[o]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Or.parse(n)}var Ls="application/vnd.ag-ui.event+proto";var kh=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Ps=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(kh);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},Ac=t=>t==="*"||t==="x"||t==="X",kc=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},Ih=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],Ch=(t,e)=>{if(Ac(t)||Ac(e))return 0;let[n,r]=Ih(kc(t),kc(e));return n>r?1:n<r?-1:0},Ds=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=Ch(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var Yn=(t,e)=>{let n=Ps(t),r=Ps(e),o=n.pop(),i=r.pop(),s=Ds(n,r);return s!==0?s:o&&i?Ds(o.split("."),i.split(".")):o||i?o?-1:1:0};var V=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function Oe(){return bt()}function Gs(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&Gs(e);return t}var Ic=512*1024;function Cc(t,e,n){let r=0,o=[t,e],i=new WeakSet;for(;o.length>0;){let s=o.pop();if(typeof s=="string"){if(r+=s.length,r>n)return!0}else if(typeof s=="object"&&s){if(i.has(s))continue;if(i.add(s),Array.isArray(s))for(let a=0;a<s.length;a++)o.push(s[a]);else{let a=Object.keys(s);for(let l=0;l<a.length;l++){let c=a[l];if(r+=c.length,r>n)return!0;o.push(s[c])}}}}return!1}async function K(t,e,n,r){let o=typeof process<"u"&&process.env!==void 0,i=o&&!!process.env.VITEST_WORKER_ID,s=o&&!!process.env.VITEST_WORKER_ID,a=s&&!Cc(e,n,Ic),l=a?V(e):e,c=a?V(n):n,p=!1,m=!1,b;for(let h of t)try{a&&(Gs(l),Gs(c));let d=await r(h,l,c);if(d===void 0)continue;let g=!1;if(d.messages!==void 0&&d.messages!==l&&(l=V(d.messages),p=!0,g=!0),d.state!==void 0&&d.state!==c&&(c=V(d.state),m=!0,g=!0),a&&g&&Cc(l,c,Ic)&&(a=!1),b=d.stopPropagation,b===!0)break}catch(d){if(s&&d instanceof TypeError){if(i)throw d;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",d)}else i||console.error("Subscriber error:",d);continue}return{...p?{messages:Object.isFrozen(l)?V(l):l}:{},...m?{state:Object.isFrozen(c)?V(c):c}:{},...b===void 0?{}:{stopPropagation:b}}}function Xo(t){if(!t)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(t===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let e=t.events??!0,n=t.lifecycle??!0,r=t.verbose??!1;return{enabled:e||n,events:e,lifecycle:n,verbose:r}}function Jn(t){if(t instanceof Fs)return t;if(t===!0)return new Fs(Xo(!0))}var Fs=class{constructor(t){this.config=t}event(t,e,n,r){this.config.events&&(this.config.verbose?console.debug(`[${t}] ${e}`,typeof n=="string"?n:JSON.stringify(n)):console.debug(`[${t}] ${e}`,r??n))}lifecycle(t,e,n){this.config.lifecycle&&(n?console.debug(`[${t}] ${e}`,n):console.debug(`[${t}] ${e}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function Us(t){return t.enabled?new Fs(t):void 0}function Nh(t,e,n){if(e){let o=t.find(s=>s.id===e);if(o?.role==="assistant")return o;o&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${o.role}' message, not assistant \u2014 falling back to toolCallId`);let i={id:o?n:e,role:"assistant",toolCalls:[]};return t.push(i),i}let r={id:n,role:"assistant",toolCalls:[]};return t.push(r),r}var Pc=(t,e,n,r,o)=>{let i=Jn(o),s=V(n.messages),a=V(t.state),l={},c=m=>{m.messages!==void 0&&(s=m.messages,l.messages=m.messages),m.state!==void 0&&(a=m.state,l.state=m.state)},p=()=>{let m=V(l);return l={},m.messages!==void 0||m.state!==void 0?ne(m):Kr};return e.pipe(uo(async m=>{let b=await K(r,s,a,(h,d,g)=>h.onEvent?.({event:m,agent:n,input:t,messages:d,state:g}));if(c(b),b.stopPropagation===!0?i?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):i?.event("APPLY","Event applied:",m,{type:m.type,subscribers:r.length}),b.stopPropagation===!0)return p();switch(m.type){case v.TEXT_MESSAGE_START:{let h=await K(r,s,a,(d,g,x)=>d.onTextMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:d,role:g="assistant",name:x}=m;if(!s.find(S=>S.id===d)){let S={id:d,role:g,content:"",...x!==void 0&&{name:x}};s.push(S),c({messages:s})}}return p()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:h,delta:d}=m,g=s.find(S=>S.id===h);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${h}'`),p();let x=await K(r,s,a,(S,E,I)=>S.onTextMessageContentEvent?.({event:m,messages:E,state:I,agent:n,input:t,textMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${d}`,c({messages:s})),p()}case v.TEXT_MESSAGE_END:{let{messageId:h}=m,d=s.find(g=>g.id===h);return d?(c(await K(r,s,a,(g,x,S)=>g.onTextMessageEndEvent?.({event:m,messages:x,state:S,agent:n,input:t,textMessageBuffer:typeof d.content=="string"?d.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:d,messages:s,state:a,agent:n,input:t})})),p()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${h}'`),p())}case v.TOOL_CALL_START:{let h=await K(r,s,a,(d,g,x)=>d.onToolCallStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{toolCallId:d,toolCallName:g,parentMessageId:x}=m,S=Nh(s,x,d);S.toolCalls??=[],S.toolCalls.push({id:d,type:"function",function:{name:g,arguments:""}}),c({messages:s})}return p()}case v.TOOL_CALL_ARGS:{let{toolCallId:h,delta:d}=m,g=s.find(E=>E.toolCalls?.some(I=>I.id===h));if(!g)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${h}'`),p();let x=g.toolCalls?.find(E=>E.id===h);if(!x)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h}'`),p();let S=await K(r,s,a,(E,I,D)=>{let P=x.function.arguments,U=x.function.name,we={};try{we=fo(P)}catch{}return E.onToolCallArgsEvent?.({event:m,messages:I,state:D,agent:n,input:t,toolCallBuffer:P,toolCallName:U,partialToolCallArgs:we})});return c(S),S.stopPropagation!==!0&&(x.function.arguments+=d,c({messages:s})),p()}case v.TOOL_CALL_END:{let{toolCallId:h}=m,d=s.find(x=>x.toolCalls?.some(S=>S.id===h));if(!d)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${h}'`),p();let g=d.toolCalls?.find(x=>x.id===h);return g?(c(await K(r,s,a,(x,S,E)=>{let I=g.function.arguments,D=g.function.name,P={};try{P=JSON.parse(I)}catch{}return x.onToolCallEndEvent?.({event:m,messages:S,state:E,agent:n,input:t,toolCallName:D,toolCallArgs:P})})),await Promise.all(r.map(x=>{x.onNewToolCall?.({toolCall:g,messages:s,state:a,agent:n,input:t})})),p()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${h}'`),p())}case v.TOOL_CALL_RESULT:{let h=await K(r,s,a,(d,g,x)=>d.onToolCallResultEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:d,toolCallId:g,content:x,role:S}=m,E={id:d,toolCallId:g,role:S||"tool",content:x},I=s.findIndex(D=>D.role==="assistant"&&D.toolCalls?.some(P=>P.id===g));if(I===-1)s.push(E);else{let D=I+1;for(;D<s.length&&s[D].role==="tool";)D++;s.splice(D,0,E)}await Promise.all(r.map(D=>{D.onNewMessage?.({message:E,messages:s,state:a,agent:n,input:t})})),c({messages:s})}return p()}case v.STATE_SNAPSHOT:{let h=await K(r,s,a,(d,g,x)=>d.onStateSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{snapshot:d}=m;a=d,c({state:a})}return p()}case v.STATE_DELTA:{let h=await K(r,s,a,(d,g,x)=>d.onStateDeltaEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{delta:d}=m;try{a=Fr.applyPatch(a,d,!0,!1).newDocument,c({state:a})}catch(g){let x=g instanceof Error?g.message:String(g);console.warn(`Failed to apply state patch:
|
|
1
|
+
var Xu=Object.defineProperty;var Oo=(t,e)=>{for(var n in e)Xu(t,n,{get:e[n],enumerable:!0})};var Sr="ag-ui-chat",Mo="ag-ui-submit",Lo="ag-ui-toggle",Po="ag-ui-state",Ye={USER:"user",ASSISTANT:"assistant"},Pn="x-destructive",Do="x-confirm",Ne="x-summary",Dn="x-navigates",Uo=10,ce={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Le={UPLOADING:"uploading",READY:"ready",ERROR:"error"},Ho=10*1024*1024,ze={INLINE:"inline",MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var Ku=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function Va(t,e){let n=[];return{text:t.replace(Ku,(i,o)=>{let s=e[o];return s==null||s===""?(n.includes(o)||n.push(o),i):String(s)}),missing:n}}function Zu(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&typeof e.prompt=="string"}function Go(t){return Array.isArray(t)?t.filter(Zu):[]}var Un=class{#n=new Map;register(e){this.#n.set(e.name,e)}has(e){return this.#n.has(e)}get(e){let n=this.#n.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#n.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function Fo(t){return t[Pn]===!0}function $o(t){return t[Dn]===!0}function wr(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Yu=wr(HTMLInputElement.prototype,"value"),Ju=wr(HTMLTextAreaElement.prototype,"value"),Qu=wr(HTMLSelectElement.prototype,"value"),ed=wr(HTMLInputElement.prototype,"checked");function kt(t,e){t instanceof HTMLTextAreaElement?Ju.call(t,e):t instanceof HTMLSelectElement?Qu.call(t,e):Yu.call(t,e)}function Hn(t,e){ed.call(t,e)}var ja="#4f46e5";function _r(t){return new Promise(e=>{setTimeout(e,t)})}async function zo(t,e,n={}){let r=n.charDelayMs??35;kt(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let i of e)kt(t,t.value+i),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await _r(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Bo(t,e={}){let n=e.highlightMs??280,r=t.style.outline,i=t.style.outlineOffset;t.style.outline=`2px solid ${ja}`,t.style.outlineOffset="2px",await _r(n),t.style.outline=r,t.style.outlineOffset=i,t.click()}function lt(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function Vo(t,e={}){let n=e.flashMs??200;t.focus();let r=t.style.boxShadow;t.style.boxShadow="0 0 0 3px rgba(79, 70, 229, 0.4)",await _r(n),t.style.boxShadow=r}var Wa="0 0 0 3px rgba(79, 70, 229, 0.4)";function qa(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function jo(t){return t<=0||qa()?Promise.resolve():_r(t)}async function Wo(t,e={}){let n=e.pressMs??140,r=t.style.transform,i=t.style.transition,o=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=Wa,await jo(n),t.style.transform=r,t.style.transition=i,t.style.boxShadow=o,t.click()}function td(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function qo(t,e,n={}){let r=td(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let i=n.highlightMs??220,o=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${ja}`,t.style.outlineOffset="2px",await jo(i),kt(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=o,t.style.outlineOffset=s}async function Xo(t,e,n={}){let r=n.flashMs??200,i=t.style.boxShadow;t.style.boxShadow=Wa,await jo(r),Hn(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=i}var Ko={SCROLL:"scroll",DRAG:"drag"};function Zo(t,e){let n=[];return t.has(Ko.SCROLL)&&n.push(nd(e)),t.has(Ko.DRAG)&&n.push(rd(e)),n}function nd(t){return{name:"scroll_to",description:"Scroll a target into view. `target` is `top`, `bottom`, or a CSS selector / page-map element id. Read-only: it changes nothing on the page.",parameters:{type:"object",properties:{target:{type:"string"}},required:["target"],[Ne]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let i=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:i,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return lt(r),{scrolled:!0,target:n}}}}function rd(t){return{name:"drag_and_drop",description:"Drag the `from` element onto the `to` element (CSS selectors or page-map element ids), firing the page's native drag-and-drop. Use for reordering sortable lists. The page decides what the drop commits.",parameters:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"],[Ne]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),i=t(n);if(i===null)throw new Error(`no element matching "${n}"`);let o=t(r);if(o===null)throw new Error(`no element matching "${r}"`);return id(i,o),{dragged:!0,from:n,to:r}}}}function id(t,e){let n=new DataTransfer;Gn(t,"dragstart",n),Gn(e,"dragenter",n),Gn(e,"dragover",n),Gn(e,"drop",n),Gn(t,"dragend",n)}function Gn(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function Yo(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Ar(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[Ne]:`Read ${t.name}`},handler:()=>t.read()}],n=t.write;return n!==void 0&&e.push({name:`set_${t.name}`,description:`Update the "${t.name}" state.`,parameters:{...t.schema??{type:"object"},[Pn]:!0,[Ne]:`Update ${t.name}`},handler:r=>n(r)}),e}var od=Ar;function Jo(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,i=r.name,o=r.summary;typeof i=="string"&&typeof o=="string"&&(e[i]=o)}return e}var Xa=/:([A-Za-z_][A-Za-z0-9_]*)/g;function sd(t){let e=[];for(let n of t.matchAll(Xa)){let r=n[1];r!==void 0&&e.push(r)}return e}function ad(t,e,n){let r={...n};return{path:e.replace(Xa,(o,s)=>{let a=n[s];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${s}"`);return delete r[s],encodeURIComponent(String(a))}),leftover:r}}function ld(t,e){let n=new URLSearchParams;for(let[i,o]of Object.entries(e))n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}function Qo(t,e){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[Ne]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:sd(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[Dn]:!0,[Ne]:"Navigate"},handler:n=>{let r=n.route_id,i=t().find(f=>f.id===r);if(i===void 0)throw new Error(`unknown route "${String(r)}"`);let o=n.params??{},{path:s,leftover:a}=ad(i.id,i.path,o),l=ld(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}var ne={title:"Assistant",chatHistory:"Chat history",newChat:"New chat",collapse:"Collapse",expand:"Expand",toggleTheme:"Toggle theme",checkpoints:"Continue a run",noCheckpoints:"Nothing to continue yet.",resumeRun:"Resume",forkRun:"Fork",forkedRun:"branched",conversation:"Conversation",thinking:"Assistant is thinking\u2026",thoughts:"Thoughts",stopped:"\u23F9 Stopped",connectionLost:"Connection lost",noResult:"No result returned.",declinedAction:"User declined the action.",navigating:"Navigating\u2026",skillNeeds:"\u201C{title}\u201D needs: {fields}",message:"Message",inputPlaceholder:"Ask anything\u2026",send:"Send",stop:"Stop",attachFiles:"Attach files",recordVoice:"Record voice",stopRecording:"Stop recording",transcribing:"Transcribing\u2026",transcriptionFailed:"Transcription failed",toolRunning:"running\u2026",toolDone:"\u2713 done",toolError:"\u26A0 error",toolDeclined:"\u2298 declined",resultLabel:"Result",errorLabel:"Error",declinedLabel:"Declined",details:"Details",confirmAction:"Confirm action",confirmRun:"Run \u201C{tool}\u201D?",confirm:"Confirm",cancel:"Cancel",approveAction:"Approve action",approvalPrompt:"Approve this action?",approve:"Approve",deny:"Deny",askUserAction:"Question",otherOption:"Other\u2026",answerPlaceholder:"Type your answer\u2026",submit:"Submit",chats:"Chats",noConversations:"No conversations yet.",rename:"Rename",renameConversation:"Rename conversation",delete:"Delete",deleteConversation:"Delete conversation",deletePrompt:"Delete?",tooLarge:"Too large (max {size})",fileTypeNotAllowed:"File type not allowed",uploadFailed:"upload failed",retry:"Retry",retryUpload:"Retry upload",remove:"Remove",removeAttachment:"Remove attachment",justNow:"just now",minutesAgo:"{n}m ago",hoursAgo:"{n}h ago",daysAgo:"{n}d ago",weeksAgo:"{n}w ago"};function es(t){let e={...ne};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function Ka(t,e){let n=document.createElement("button");return n.type="button",n.className=`approval-btn approval-btn--${t}`,n.setAttribute("part",`approval-button approval-${t}`),n.textContent=e,n}function ts(t,e,n={}){let r=n.strings??ne;return new Promise(i=>{let o=document.createElement("div");o.className="approval",o.setAttribute("part","approval"),e.toolName!==void 0&&o.setAttribute("data-tool-name",e.toolName),o.setAttribute("role","group"),o.setAttribute("aria-label",r.approveAction);let s=document.createElement("div");s.className="approval-body",s.setAttribute("part","approval-body"),s.textContent=e.message??r.approvalPrompt;let a=document.createElement("div");a.className="approval-actions",a.setAttribute("part","approval-actions");let l=Ka("deny",r.deny),c=Ka("approve",r.approve),f=!1,m=b=>{f||(f=!0,l.disabled=!0,c.disabled=!0,o.setAttribute("data-resolved",b?"approved":"denied"),i(b))};if(l.addEventListener("click",()=>m(!1)),c.addEventListener("click",()=>m(!0)),n.signal?.addEventListener("abort",()=>m(!1),{once:!0}),a.append(l,c),o.append(s,a),t.appendChild(o),n.signal?.aborted===!0){m(!1);return}c.focus()})}function ns(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild(cd(n));return e}function cd(t){let e=document.createElement("div");e.className="attachment-chip attachment-chip--ready",e.setAttribute("part","attachment-chip");let n=document.createElement("span");n.className="attachment-chip-icon",n.setAttribute("part","attachment-chip-icon"),n.textContent=rs(t.mime),n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.className="attachment-chip-name",r.setAttribute("part","attachment-chip-name"),r.textContent=t.name,r.title=t.name;let i=document.createElement("span");return i.className="attachment-chip-size",i.setAttribute("part","attachment-chip-size"),i.textContent=kr(t.size),e.append(n,r,i),e}function rs(t){return t.startsWith("image/")?"\u{1F5BC}":t==="application/pdf"?"\u{1F4D5}":t.startsWith("text/")?"\u{1F4C4}":"\u{1F4CE}"}function kr(t){if(t<1024)return`${t} B`;let e=["KB","MB","GB"],n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r+=1;return`${n<10?Math.round(n*10)/10:Math.round(n)} ${e[r]}`}var ve=[];for(let t=0;t<256;++t)ve.push((t+256).toString(16).slice(1));function Za(t,e=0){return(ve[t[e+0]]+ve[t[e+1]]+ve[t[e+2]]+ve[t[e+3]]+"-"+ve[t[e+4]]+ve[t[e+5]]+"-"+ve[t[e+6]]+ve[t[e+7]]+"-"+ve[t[e+8]]+ve[t[e+9]]+"-"+ve[t[e+10]]+ve[t[e+11]]+ve[t[e+12]]+ve[t[e+13]]+ve[t[e+14]]+ve[t[e+15]]).toLowerCase()}var is,ud=new Uint8Array(16);function os(){if(!is){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");is=crypto.getRandomValues.bind(crypto)}return is(ud)}var dd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ss={randomUUID:dd};function pd(t,e,n){if(ss.randomUUID&&!e&&!t)return ss.randomUUID();t=t||{};let r=t.random??t.rng?.()??os();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[n+i]=r[i];return e}return Za(r)}var bt=pd;var u={};Oo(u,{BRAND:()=>Hd,DIRTY:()=>It,EMPTY_PATH:()=>gd,INVALID:()=>M,NEVER:()=>Tp,OK:()=>Ee,ParseStatus:()=>be,Schema:()=>$,ZodAny:()=>Et,ZodArray:()=>pt,ZodBigInt:()=>Nt,ZodBoolean:()=>Rt,ZodBranded:()=>$n,ZodCatch:()=>zt,ZodDate:()=>Ot,ZodDefault:()=>$t,ZodDiscriminatedUnion:()=>Nr,ZodEffects:()=>Ue,ZodEnum:()=>Gt,ZodError:()=>ke,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>Or,ZodIntersection:()=>Dt,ZodIssueCode:()=>T,ZodLazy:()=>Ut,ZodLiteral:()=>Ht,ZodMap:()=>dn,ZodNaN:()=>fn,ZodNativeEnum:()=>Ft,ZodNever:()=>Be,ZodNull:()=>Lt,ZodNullable:()=>et,ZodNumber:()=>Ct,ZodObject:()=>Ie,ZodOptional:()=>Pe,ZodParsedType:()=>k,ZodPipeline:()=>zn,ZodPromise:()=>Tt,ZodReadonly:()=>Bt,ZodRecord:()=>Rr,ZodSchema:()=>$,ZodSet:()=>pn,ZodString:()=>xt,ZodSymbol:()=>cn,ZodTransformer:()=>Ue,ZodTuple:()=>Qe,ZodType:()=>$,ZodUndefined:()=>Mt,ZodUnion:()=>Pt,ZodUnknown:()=>dt,ZodVoid:()=>un,addIssueToContext:()=>_,any:()=>qd,array:()=>Yd,bigint:()=>zd,boolean:()=>al,coerce:()=>Ep,custom:()=>il,date:()=>Bd,datetimeRegex:()=>nl,defaultErrorMap:()=>ct,discriminatedUnion:()=>tp,effect:()=>fp,enum:()=>up,function:()=>ap,getErrorMap:()=>sn,getParsedType:()=>Je,instanceof:()=>Fd,intersection:()=>np,isAborted:()=>Ir,isAsync:()=>an,isDirty:()=>Cr,isValid:()=>yt,late:()=>Gd,lazy:()=>lp,literal:()=>cp,makeIssue:()=>Fn,map:()=>op,nan:()=>$d,nativeEnum:()=>dp,never:()=>Kd,null:()=>Wd,nullable:()=>mp,number:()=>sl,object:()=>Jd,objectUtil:()=>as,oboolean:()=>xp,onumber:()=>yp,optional:()=>hp,ostring:()=>bp,pipeline:()=>vp,preprocess:()=>gp,promise:()=>pp,quotelessJson:()=>fd,record:()=>ip,set:()=>sp,setErrorMap:()=>md,strictObject:()=>Qd,string:()=>ol,symbol:()=>Vd,transformer:()=>fp,tuple:()=>rp,undefined:()=>jd,union:()=>ep,unknown:()=>Xd,util:()=>B,void:()=>Zd});var B;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function n(i){throw new Error}t.assertNever=n,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(B||(B={}));var as;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(as||(as={}));var k=B.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Je=t=>{switch(typeof t){case"undefined":return k.undefined;case"string":return k.string;case"number":return Number.isNaN(t)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(t)?k.array:t===null?k.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?k.promise:typeof Map<"u"&&t instanceof Map?k.map:typeof Set<"u"&&t instanceof Set?k.set:typeof Date<"u"&&t instanceof Date?k.date:k.object;default:return k.unknown}};var T=B.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),fd=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ke=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(o){return o.message},r={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return i(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,B.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];n[o]=n[o]||[],n[o].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ke.create=t=>new ke(t);var hd=(t,e)=>{let n;switch(t.code){case T.invalid_type:t.received===k.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case T.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,B.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:n=`Unrecognized key(s) in object: ${B.joinValues(t.keys,", ")}`;break;case T.invalid_union:n="Invalid input";break;case T.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${B.joinValues(t.options)}`;break;case T.invalid_enum_value:n=`Invalid enum value. Expected ${B.joinValues(t.options)}, received '${t.received}'`;break;case T.invalid_arguments:n="Invalid function arguments";break;case T.invalid_return_type:n="Invalid function return type";break;case T.invalid_date:n="Invalid date";break;case T.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:B.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case T.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case T.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case T.custom:n="Invalid input";break;case T.invalid_intersection_types:n="Intersection results could not be merged";break;case T.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case T.not_finite:n="Number must be finite";break;default:n=e.defaultError,B.assertNever(t)}return{message:n}},ct=hd;var Ya=ct;function md(t){Ya=t}function sn(){return Ya}var Fn=t=>{let{data:e,path:n,errorMaps:r,issueData:i}=t,o=[...n,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},gd=[];function _(t,e){let n=sn(),r=Fn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ct?void 0:ct].filter(i=>!!i)});t.common.issues.push(r)}var be=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let i of n){if(i.status==="aborted")return M;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let i of n){let o=await i.key,s=await i.value;r.push({key:o,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let i of n){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return M;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(r[o.value]=s.value)}return{status:e.value,value:r}}},M=Object.freeze({status:"aborted"}),It=t=>({status:"dirty",value:t}),Ee=t=>({status:"valid",value:t}),Ir=t=>t.status==="aborted",Cr=t=>t.status==="dirty",yt=t=>t.status==="valid",an=t=>typeof Promise<"u"&&t instanceof Promise;var C;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(C||(C={}));var De=class{constructor(e,n,r,i){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ja=(t,e)=>{if(yt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ke(t.common.issues);return this._error=n,this._error}}};function H(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:i}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{let{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:i}}var $=class{get description(){return this._def.description}_getType(e){return Je(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new be,ctx:{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(an(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)},i=this._parseSync({data:e,path:r.path,parent:r});return Ja(r,i)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return yt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>yt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)},i=this._parse({data:e,path:r.path,parent:r}),o=await(an(i)?i:Promise.resolve(i));return Ja(r,o)}refine(e,n){let r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:T.custom,...r(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(e){return new Ue({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Pe.create(this,this._def)}nullable(){return et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return Tt.create(this,this._def)}or(e){return Pt.create([this,e],this._def)}and(e){return Dt.create(this,e,this._def)}transform(e){return new Ue({...H(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new $t({...H(this._def),innerType:this,defaultValue:n,typeName:L.ZodDefault})}brand(){return new $n({typeName:L.ZodBranded,type:this,...H(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new zt({...H(this._def),innerType:this,catchValue:n,typeName:L.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return zn.create(this,e)}readonly(){return Bt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},vd=/^c[^\s-]{8,}$/i,bd=/^[0-9a-z]+$/,yd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ed=/^[a-z0-9_-]{21}$/i,Td=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Sd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,wd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_d="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ls,Ad=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,kd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Id=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Cd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Nd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,el="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Od=new RegExp(`^${el}$`);function tl(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Md(t){return new RegExp(`^${tl(t)}$`)}function nl(t){let e=`${el}T${tl(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Ld(t,e){return!!((e==="v4"||!e)&&Ad.test(t)||(e==="v6"||!e)&&Id.test(t))}function Pd(t,e){if(!Td.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Dd(t,e){return!!((e==="v4"||!e)&&kd.test(t)||(e==="v6"||!e)&&Cd.test(t))}var xt=class t extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==k.string){let o=this._getOrReturnCtx(e);return _(o,{code:T.invalid_type,expected:k.string,received:o.parsedType}),M}let r=new be,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),_(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),_(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?_(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&_(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")wd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"email",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")ls||(ls=new RegExp(_d,"u")),ls.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"emoji",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")xd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"uuid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Ed.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"nanoid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")vd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"cuid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")bd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"cuid2",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")yd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"ulid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),_(i,{validation:"url",code:T.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"regex",code:T.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?nl(o).test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Od.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Md(o).test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Sd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"duration",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Ld(e.data,o.version)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"ip",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?Pd(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"jwt",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Dd(e.data,o.version)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"cidr",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Nd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"base64",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Rd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"base64url",code:T.invalid_string,message:o.message}),r.dirty()):B.assertNever(o);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(i=>e.test(i),{validation:n,code:T.invalid_string,...C.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...C.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...C.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...C.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...C.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...C.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...C.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...C.errToObj(n)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};xt.create=t=>new xt({checks:[],typeName:L.ZodString,coerce:t?.coerce??!1,...H(t)});function Ud(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}var Ct=class t extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==k.number){let o=this._getOrReturnCtx(e);return _(o,{code:T.invalid_type,expected:k.number,received:o.parsedType}),M}let r,i=new be;for(let o of this._def.checks)o.kind==="int"?B.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{code:T.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Ud(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{code:T.not_finite,message:o.message}),i.dirty()):B.assertNever(o);return{status:i.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,C.toString(n))}gt(e,n){return this.setLimit("min",e,!1,C.toString(n))}lte(e,n){return this.setLimit("max",e,!0,C.toString(n))}lt(e,n){return this.setLimit("max",e,!1,C.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:C.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&B.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Ct.create=t=>new Ct({checks:[],typeName:L.ZodNumber,coerce:t?.coerce||!1,...H(t)});var Nt=class t extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==k.bigint)return this._getInvalidInput(e);let r,i=new be;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):B.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return _(n,{code:T.invalid_type,expected:k.bigint,received:n.parsedType}),M}gte(e,n){return this.setLimit("min",e,!0,C.toString(n))}gt(e,n){return this.setLimit("min",e,!1,C.toString(n))}lte(e,n){return this.setLimit("max",e,!0,C.toString(n))}lt(e,n){return this.setLimit("max",e,!1,C.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:C.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Nt.create=t=>new Nt({checks:[],typeName:L.ZodBigInt,coerce:t?.coerce??!1,...H(t)});var Rt=class extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==k.boolean){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.boolean,received:r.parsedType}),M}return Ee(e.data)}};Rt.create=t=>new Rt({typeName:L.ZodBoolean,coerce:t?.coerce||!1,...H(t)});var Ot=class t extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==k.date){let o=this._getOrReturnCtx(e);return _(o,{code:T.invalid_type,expected:k.date,received:o.parsedType}),M}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return _(o,{code:T.invalid_date}),M}let r=new be,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),_(i,{code:T.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),_(i,{code:T.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):B.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Ot.create=t=>new Ot({checks:[],coerce:t?.coerce||!1,typeName:L.ZodDate,...H(t)});var cn=class extends ${_parse(e){if(this._getType(e)!==k.symbol){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.symbol,received:r.parsedType}),M}return Ee(e.data)}};cn.create=t=>new cn({typeName:L.ZodSymbol,...H(t)});var Mt=class extends ${_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.undefined,received:r.parsedType}),M}return Ee(e.data)}};Mt.create=t=>new Mt({typeName:L.ZodUndefined,...H(t)});var Lt=class extends ${_parse(e){if(this._getType(e)!==k.null){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.null,received:r.parsedType}),M}return Ee(e.data)}};Lt.create=t=>new Lt({typeName:L.ZodNull,...H(t)});var Et=class extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return Ee(e.data)}};Et.create=t=>new Et({typeName:L.ZodAny,...H(t)});var dt=class extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ee(e.data)}};dt.create=t=>new dt({typeName:L.ZodUnknown,...H(t)});var Be=class extends ${_parse(e){let n=this._getOrReturnCtx(e);return _(n,{code:T.invalid_type,expected:k.never,received:n.parsedType}),M}};Be.create=t=>new Be({typeName:L.ZodNever,...H(t)});var un=class extends ${_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.void,received:r.parsedType}),M}return Ee(e.data)}};un.create=t=>new un({typeName:L.ZodVoid,...H(t)});var pt=class t extends ${_parse(e){let{ctx:n,status:r}=this._processInputParams(e),i=this._def;if(n.parsedType!==k.array)return _(n,{code:T.invalid_type,expected:k.array,received:n.parsedType}),M;if(i.exactLength!==null){let s=n.data.length>i.exactLength.value,a=n.data.length<i.exactLength.value;(s||a)&&(_(n,{code:s?T.too_big:T.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(_(n,{code:T.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(_(n,{code:T.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>i.type._parseAsync(new De(n,s,n.path,a)))).then(s=>be.mergeArray(r,s));let o=[...n.data].map((s,a)=>i.type._parseSync(new De(n,s,n.path,a)));return be.mergeArray(r,o)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:C.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:C.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:C.toString(n)}})}nonempty(e){return this.min(1,e)}};pt.create=(t,e)=>new pt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...H(e)});function ln(t){if(t instanceof Ie){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Pe.create(ln(r))}return new Ie({...t._def,shape:()=>e})}else return t instanceof pt?new pt({...t._def,type:ln(t.element)}):t instanceof Pe?Pe.create(ln(t.unwrap())):t instanceof et?et.create(ln(t.unwrap())):t instanceof Qe?Qe.create(t.items.map(e=>ln(e))):t}var Ie=class t extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=B.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==k.object){let c=this._getOrReturnCtx(e);return _(c,{code:T.invalid_type,expected:k.object,received:c.parsedType}),M}let{status:r,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Be&&this._def.unknownKeys==="strip"))for(let c in i.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let f=o[c],m=i.data[c];l.push({key:{status:"valid",value:c},value:f._parse(new De(i,m,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof Be){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of a)l.push({key:{status:"valid",value:f},value:{status:"valid",value:i.data[f]}});else if(c==="strict")a.length>0&&(_(i,{code:T.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of a){let m=i.data[f];l.push({key:{status:"valid",value:f},value:c._parse(new De(i,m,i.path,f)),alwaysSet:f in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of l){let m=await f.key,b=await f.value;c.push({key:m,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>be.mergeObjectSync(r,c)):be.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:C.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:L.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of B.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of B.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ln(this)}partial(e){let n={};for(let r of B.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?n[r]=i:n[r]=i.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of B.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Pe;)o=o._def.innerType;n[r]=o}return new t({...this._def,shape:()=>n})}keyof(){return rl(B.objectKeys(this.shape))}};Ie.create=(t,e)=>new Ie({shape:()=>t,unknownKeys:"strip",catchall:Be.create(),typeName:L.ZodObject,...H(e)});Ie.strictCreate=(t,e)=>new Ie({shape:()=>t,unknownKeys:"strict",catchall:Be.create(),typeName:L.ZodObject,...H(e)});Ie.lazycreate=(t,e)=>new Ie({shape:t,unknownKeys:"strip",catchall:Be.create(),typeName:L.ZodObject,...H(e)});var Pt=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new ke(a.ctx.common.issues));return _(n,{code:T.invalid_union,unionErrors:s}),M}if(n.common.async)return Promise.all(r.map(async o=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},f=l._parseSync({data:n.data,path:n.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!o&&(o={result:f,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(l=>new ke(l));return _(n,{code:T.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};Pt.create=(t,e)=>new Pt({options:t,typeName:L.ZodUnion,...H(e)});var ut=t=>t instanceof Ut?ut(t.schema):t instanceof Ue?ut(t.innerType()):t instanceof Ht?[t.value]:t instanceof Gt?t.options:t instanceof Ft?B.objectValues(t.enum):t instanceof $t?ut(t._def.innerType):t instanceof Mt?[void 0]:t instanceof Lt?[null]:t instanceof Pe?[void 0,...ut(t.unwrap())]:t instanceof et?[null,...ut(t.unwrap())]:t instanceof $n||t instanceof Bt?ut(t.unwrap()):t instanceof zt?ut(t._def.innerType):[],Nr=class t extends ${_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.object)return _(n,{code:T.invalid_type,expected:k.object,received:n.parsedType}),M;let r=this.discriminator,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(_(n,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let i=new Map;for(let o of n){let s=ut(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...H(r)})}};function cs(t,e){let n=Je(t),r=Je(e);if(t===e)return{valid:!0,data:t};if(n===k.object&&r===k.object){let i=B.objectKeys(e),o=B.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let l=cs(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===k.array&&r===k.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],l=cs(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===k.date&&r===k.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Dt=class extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=(o,s)=>{if(Ir(o)||Ir(s))return M;let a=cs(o.value,s.value);return a.valid?((Cr(o)||Cr(s))&&n.dirty(),{status:n.value,value:a.data}):(_(r,{code:T.invalid_intersection_types}),M)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Dt.create=(t,e,n)=>new Dt({left:t,right:e,typeName:L.ZodIntersection,...H(n)});var Qe=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.array)return _(r,{code:T.invalid_type,expected:k.array,received:r.parsedType}),M;if(r.data.length<this._def.items.length)return _(r,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new De(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(o).then(s=>be.mergeArray(n,s)):be.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Qe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qe({items:t,typeName:L.ZodTuple,rest:null,...H(e)})};var Rr=class t extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.object)return _(r,{code:T.invalid_type,expected:k.object,received:r.parsedType}),M;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in r.data)i.push({key:o._parse(new De(r,a,r.path,a)),value:s._parse(new De(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?be.mergeObjectAsync(n,i):be.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof $?new t({keyType:e,valueType:n,typeName:L.ZodRecord,...H(r)}):new t({keyType:xt.create(),valueType:e,typeName:L.ZodRecord,...H(n)})}},dn=class extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.map)return _(r,{code:T.invalid_type,expected:k.map,received:r.parsedType}),M;let i=this._def.keyType,o=this._def.valueType,s=[...r.data.entries()].map(([a,l],c)=>({key:i._parse(new De(r,a,r.path,[c,"key"])),value:o._parse(new De(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,f=await l.value;if(c.status==="aborted"||f.status==="aborted")return M;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(c.value,f.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,f=l.value;if(c.status==="aborted"||f.status==="aborted")return M;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(c.value,f.value)}return{status:n.value,value:a}}}};dn.create=(t,e,n)=>new dn({valueType:e,keyType:t,typeName:L.ZodMap,...H(n)});var pn=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.set)return _(r,{code:T.invalid_type,expected:k.set,received:r.parsedType}),M;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(_(r,{code:T.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(_(r,{code:T.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let o=this._def.valueType;function s(l){let c=new Set;for(let f of l){if(f.status==="aborted")return M;f.status==="dirty"&&n.dirty(),c.add(f.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>o._parse(new De(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:C.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:C.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};pn.create=(t,e)=>new pn({valueType:t,minSize:null,maxSize:null,typeName:L.ZodSet,...H(e)});var Or=class t extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.function)return _(n,{code:T.invalid_type,expected:k.function,received:n.parsedType}),M;function r(a,l){return Fn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sn(),ct].filter(c=>!!c),issueData:{code:T.invalid_arguments,argumentsError:l}})}function i(a,l){return Fn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sn(),ct].filter(c=>!!c),issueData:{code:T.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Tt){let a=this;return Ee(async function(...l){let c=new ke([]),f=await a._def.args.parseAsync(l,o).catch(h=>{throw c.addIssue(r(l,h)),c}),m=await Reflect.apply(s,this,f);return await a._def.returns._def.type.parseAsync(m,o).catch(h=>{throw c.addIssue(i(m,h)),c})})}else{let a=this;return Ee(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new ke([r(l,c.error)]);let f=Reflect.apply(s,this,c.data),m=a._def.returns.safeParse(f,o);if(!m.success)throw new ke([i(f,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Qe.create(e).rest(dt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Qe.create([]).rest(dt.create()),returns:n||dt.create(),typeName:L.ZodFunction,...H(r)})}},Ut=class extends ${get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ut.create=(t,e)=>new Ut({getter:t,typeName:L.ZodLazy,...H(e)});var Ht=class extends ${_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return _(n,{received:n.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ht.create=(t,e)=>new Ht({value:t,typeName:L.ZodLiteral,...H(e)});function rl(t,e){return new Gt({values:t,typeName:L.ZodEnum,...H(e)})}var Gt=class t extends ${_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return _(n,{expected:B.joinValues(r),received:n.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return _(n,{received:n.data,code:T.invalid_enum_value,options:r}),M}return Ee(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Gt.create=rl;var Ft=class extends ${_parse(e){let n=B.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==k.string&&r.parsedType!==k.number){let i=B.objectValues(n);return _(r,{expected:B.joinValues(i),received:r.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(B.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=B.objectValues(n);return _(r,{received:r.data,code:T.invalid_enum_value,options:i}),M}return Ee(e.data)}get enum(){return this._def.values}};Ft.create=(t,e)=>new Ft({values:t,typeName:L.ZodNativeEnum,...H(e)});var Tt=class extends ${unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.promise&&n.common.async===!1)return _(n,{code:T.invalid_type,expected:k.promise,received:n.parsedType}),M;let r=n.parsedType===k.promise?n.data:Promise.resolve(n.data);return Ee(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Tt.create=(t,e)=>new Tt({type:t,typeName:L.ZodPromise,...H(e)});var Ue=class extends ${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{_(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(r.data,o);if(r.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return M;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?M:l.status==="dirty"?It(l.value):n.value==="dirty"?It(l.value):l});{if(n.value==="aborted")return M;let a=this._def.schema._parseSync({data:s,path:r.path,parent:r});return a.status==="aborted"?M:a.status==="dirty"?It(a.value):n.value==="dirty"?It(a.value):a}}if(i.type==="refinement"){let s=a=>{let l=i.refinement(a,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?M:(a.status==="dirty"&&n.dirty(),s(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(i.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!yt(s))return M;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>yt(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:n.value,value:a})):M);B.assertNever(i)}};Ue.create=(t,e,n)=>new Ue({schema:t,typeName:L.ZodEffects,effect:e,...H(n)});Ue.createWithPreprocess=(t,e,n)=>new Ue({schema:e,effect:{type:"preprocess",transform:t},typeName:L.ZodEffects,...H(n)});var Pe=class extends ${_parse(e){return this._getType(e)===k.undefined?Ee(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Pe.create=(t,e)=>new Pe({innerType:t,typeName:L.ZodOptional,...H(e)});var et=class extends ${_parse(e){return this._getType(e)===k.null?Ee(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};et.create=(t,e)=>new et({innerType:t,typeName:L.ZodNullable,...H(e)});var $t=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};$t.create=(t,e)=>new $t({innerType:t,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});var zt=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return an(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});var fn=class extends ${_parse(e){if(this._getType(e)!==k.nan){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.nan,received:r.parsedType}),M}return{status:"valid",value:e.data}}};fn.create=t=>new fn({typeName:L.ZodNaN,...H(t)});var Hd=Symbol("zod_brand"),$n=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},zn=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?M:o.status==="dirty"?(n.dirty(),It(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?M:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:L.ZodPipeline})}},Bt=class extends ${_parse(e){let n=this._def.innerType._parse(e),r=i=>(yt(i)&&(i.value=Object.freeze(i.value)),i);return an(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};Bt.create=(t,e)=>new Bt({innerType:t,typeName:L.ZodReadonly,...H(e)});function Qa(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function il(t,e={},n){return t?Et.create().superRefine((r,i)=>{let o=t(r);if(o instanceof Promise)return o.then(s=>{if(!s){let a=Qa(e,r),l=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:l})}});if(!o){let s=Qa(e,r),a=s.fatal??n??!0;i.addIssue({code:"custom",...s,fatal:a})}}):Et.create()}var Gd={object:Ie.lazycreate},L;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(L||(L={}));var Fd=(t,e={message:`Input not instance of ${t.name}`})=>il(n=>n instanceof t,e),ol=xt.create,sl=Ct.create,$d=fn.create,zd=Nt.create,al=Rt.create,Bd=Ot.create,Vd=cn.create,jd=Mt.create,Wd=Lt.create,qd=Et.create,Xd=dt.create,Kd=Be.create,Zd=un.create,Yd=pt.create,Jd=Ie.create,Qd=Ie.strictCreate,ep=Pt.create,tp=Nr.create,np=Dt.create,rp=Qe.create,ip=Rr.create,op=dn.create,sp=pn.create,ap=Or.create,lp=Ut.create,cp=Ht.create,up=Gt.create,dp=Ft.create,pp=Tt.create,fp=Ue.create,hp=Pe.create,mp=et.create,gp=Ue.createWithPreprocess,vp=zn.create,bp=()=>ol().optional(),yp=()=>sl().optional(),xp=()=>al().optional(),Ep={string:(t=>xt.create({...t,coerce:!0})),number:(t=>Ct.create({...t,coerce:!0})),boolean:(t=>Rt.create({...t,coerce:!0})),bigint:(t=>Nt.create({...t,coerce:!0})),date:(t=>Ot.create({...t,coerce:!0}))};var Tp=M;var Sp=u.object({name:u.string(),arguments:u.string()}),wp=u.object({id:u.string(),type:u.literal("function"),function:Sp,encryptedValue:u.string().optional()}),Mr=u.object({id:u.string(),role:u.string(),content:u.string().optional(),name:u.string().optional(),encryptedValue:u.string().optional()}),_p=u.object({type:u.literal("text"),text:u.string()}),Ap=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),kp=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),Lr=u.discriminatedUnion("type",[Ap,kp]),Ip=u.object({type:u.literal("image"),source:Lr,metadata:u.unknown().optional()}),Cp=u.object({type:u.literal("audio"),source:Lr,metadata:u.unknown().optional()}),Np=u.object({type:u.literal("video"),source:Lr,metadata:u.unknown().optional()}),Rp=u.object({type:u.literal("document"),source:Lr,metadata:u.unknown().optional()});var ll=u.object({type:u.literal("binary"),mimeType:u.string(),id:u.string().optional(),url:u.string().optional(),data:u.string().optional(),filename:u.string().optional()}),cl=(t,e)=>{!t.id&&!t.url&&!t.data&&e.addIssue({code:u.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},ib=ll.superRefine((t,e)=>{cl(t,e)}),Op=u.discriminatedUnion("type",[_p,Ip,Cp,Np,Rp,ll]),Mp=Op.superRefine((t,e)=>{t.type==="binary"&&cl(t,e)}),Lp=Mr.extend({role:u.literal("developer"),content:u.string()}),Pp=Mr.extend({role:u.literal("system"),content:u.string()}),Dp=Mr.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(wp).optional()}),Up=Mr.extend({role:u.literal("user"),content:u.union([u.string(),u.array(Mp)])}),Hp=u.object({id:u.string(),content:u.string(),role:u.literal("tool"),toolCallId:u.string(),error:u.string().optional(),encryptedValue:u.string().optional()}),Gp=u.object({id:u.string(),role:u.literal("activity"),activityType:u.string(),content:u.record(u.any())}),Fp=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),ul=u.discriminatedUnion("role",[Lp,Pp,Dp,Up,Hp,Gp,Fp]),ob=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),$p=u.object({description:u.string(),value:u.string()}),dl=u.object({name:u.string(),description:u.string(),parameters:u.any(),metadata:u.record(u.any()).optional()}),zp=u.object({id:u.string(),reason:u.string(),message:u.string().optional(),toolCallId:u.string().optional(),responseSchema:u.record(u.any()).optional(),expiresAt:u.string().optional(),metadata:u.record(u.any()).optional()}),Bp=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),Vp=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(ul),tools:u.array(dl),context:u.array($p),forwardedProps:u.any(),resume:u.array(Bp).optional()}),jp=u.any(),Q=class extends Error{constructor(t){super(t)}},us=class extends Q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},Wp=u.object({name:u.string(),description:u.string().optional()}),qp=u.object({name:u.string().optional(),type:u.string().optional(),description:u.string().optional(),version:u.string().optional(),provider:u.string().optional(),documentationUrl:u.string().optional(),metadata:u.record(u.unknown()).optional()}),Xp=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),Kp=u.object({supported:u.boolean().optional(),items:u.array(dl).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),Zp=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),Yp=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),Jp=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(Wp).optional()}),Qp=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),ef=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),tf=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),nf=u.object({input:ef.optional(),output:tf.optional()}),rf=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),of=u.object({supported:u.boolean().optional(),approvals:u.boolean().optional(),interventions:u.boolean().optional(),feedback:u.boolean().optional(),interrupts:u.boolean().optional(),approveWithEdits:u.boolean().optional()}),sb=u.object({identity:qp.optional(),transport:Xp.optional(),tools:Kp.optional(),output:Zp.optional(),state:Yp.optional(),multiAgent:Jp.optional(),reasoning:Qp.optional(),multimodal:nf.optional(),execution:rf.optional(),humanInTheLoop:of.optional(),custom:u.record(u.unknown()).optional()}),pl=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user")]),v=(function(t){return t.TEXT_MESSAGE_START="TEXT_MESSAGE_START",t.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",t.TEXT_MESSAGE_END="TEXT_MESSAGE_END",t.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",t.TOOL_CALL_START="TOOL_CALL_START",t.TOOL_CALL_ARGS="TOOL_CALL_ARGS",t.TOOL_CALL_END="TOOL_CALL_END",t.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",t.TOOL_CALL_RESULT="TOOL_CALL_RESULT",t.THINKING_START="THINKING_START",t.THINKING_END="THINKING_END",t.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",t.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",t.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",t.STATE_SNAPSHOT="STATE_SNAPSHOT",t.STATE_DELTA="STATE_DELTA",t.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",t.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",t.ACTIVITY_DELTA="ACTIVITY_DELTA",t.RAW="RAW",t.CUSTOM="CUSTOM",t.RUN_STARTED="RUN_STARTED",t.RUN_FINISHED="RUN_FINISHED",t.RUN_ERROR="RUN_ERROR",t.STEP_STARTED="STEP_STARTED",t.STEP_FINISHED="STEP_FINISHED",t.REASONING_START="REASONING_START",t.REASONING_MESSAGE_START="REASONING_MESSAGE_START",t.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",t.REASONING_MESSAGE_END="REASONING_MESSAGE_END",t.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",t.REASONING_END="REASONING_END",t.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",t})({}),q=u.object({type:u.nativeEnum(v),timestamp:u.number().optional(),rawEvent:u.any().optional()}).passthrough(),sf=q.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:pl.default("assistant"),name:u.string().optional()}),fl=q.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),af=q.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),lf=q.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:pl.optional(),delta:u.string().optional(),name:u.string().optional()}),cf=q.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),uf=fl.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),df=q.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),pf=q.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),ff=q.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),hf=q.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),mf=q.extend({messageId:u.string(),type:u.literal(v.TOOL_CALL_RESULT),toolCallId:u.string(),content:u.string(),role:u.literal("tool").optional()}),gf=q.extend({type:u.literal(v.TOOL_CALL_CHUNK),toolCallId:u.string().optional(),toolCallName:u.string().optional(),parentMessageId:u.string().optional(),delta:u.string().optional()}),vf=q.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),bf=q.extend({type:u.literal(v.THINKING_END)}),yf=q.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:jp}),xf=q.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),Ef=q.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(ul)}),Tf=q.extend({type:u.literal(v.ACTIVITY_SNAPSHOT),messageId:u.string(),activityType:u.string(),content:u.record(u.any()),replace:u.boolean().optional().default(!0)}),Sf=q.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),wf=q.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),_f=q.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),Af=q.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:Vp.optional()}),kf=u.object({type:u.literal("success")}).strict(),If=u.object({type:u.literal("interrupt"),interrupts:u.array(zp).min(1)}).strict(),Cf=u.discriminatedUnion("type",[kf,If]),Nf=q.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:Cf.nullable().optional().transform(t=>t??void 0)}),Rf=q.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),Of=q.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),Mf=q.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),Lf=u.union([u.literal("tool-call"),u.literal("message")]),Pf=q.extend({type:u.literal(v.REASONING_START),messageId:u.string()}),Df=q.extend({type:u.literal(v.REASONING_MESSAGE_START),messageId:u.string(),role:u.literal("reasoning")}),Uf=q.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),Hf=q.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),Gf=q.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),Ff=q.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),$f=q.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:Lf,entityId:u.string(),encryptedValue:u.string()}),Pr=u.discriminatedUnion("type",[sf,fl,af,lf,vf,bf,cf,uf,df,pf,ff,hf,gf,mf,yf,xf,Ef,Tf,Sf,wf,_f,Af,Nf,Rf,Of,Mf,Pf,Df,Uf,Hf,Gf,Ff,$f]);var ds={};Oo(ds,{JsonPatchError:()=>ie,_areEquals:()=>jn,applyOperation:()=>Vt,applyPatch:()=>zr,applyReducer:()=>Wf,deepClone:()=>Vf,getValueByPointer:()=>Fr,validate:()=>ml,validator:()=>$r});var zf=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var o in i)i.hasOwnProperty(o)&&(r[o]=i[o])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Bf=Object.prototype.hasOwnProperty;function Ur(t,e){return Bf.call(t,e)}function Hr(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n<e.length;n++)e[n]=""+n;return e}if(Object.keys)return Object.keys(t);var r=[];for(var i in t)Ur(t,i)&&r.push(i);return r}function ye(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Gr(t){for(var e=0,n=t.length,r;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function tt(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Bn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Dr(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Dr(t[e]))return!0}else if(typeof t=="object"){for(var r=Hr(t),i=r.length,o=0;o<i;o++)if(Dr(t[r[o]]))return!0}}return!1}function hl(t,e){var n=[t];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&n.push(r+": "+i)}return n.join(`
|
|
2
|
+
`)}var Vn=(function(t){zf(e,t);function e(n,r,i,o,s){var a=this.constructor,l=t.call(this,hl(n,{name:r,index:i,operation:o,tree:s}))||this;return l.name=r,l.index=i,l.operation=o,l.tree=s,Object.setPrototypeOf(l,a.prototype),l.message=hl(n,{name:r,index:i,operation:o,tree:s}),l}return e})(Error);var ie=Vn,Vf=ye,hn={add:function(t,e,n){return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){var r=Fr(n,this.path);r&&(r=ye(r));var i=Vt(n,{op:"remove",path:this.from}).removed;return Vt(n,{op:"add",path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=Fr(n,this.from);return Vt(n,{op:"add",path:this.path,value:ye(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:jn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},jf={add:function(t,e,n){return Gr(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){var r=t.splice(e,1);return{newDocument:n,removed:r[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:hn.move,copy:hn.copy,test:hn.test,_get:hn._get};function Fr(t,e){if(e=="")return t;var n={op:"_get",path:e};return Vt(t,n),n.value}function Vt(t,e,n,r,i,o){if(n===void 0&&(n=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),o===void 0&&(o=0),n&&(typeof n=="function"?n(e,0,t,e.path):$r(e,0)),e.path===""){var s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=Fr(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=jn(t,e.value),s.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(n)throw new ie("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return s}}else{r||(t=ye(t));var a=e.path||"",l=a.split("/"),c=t,f=1,m=l.length,b=void 0,h=void 0,d=void 0;for(typeof n=="function"?d=n:d=$r;;){if(h=l[f],h&&h.indexOf("~")!=-1&&(h=Bn(h)),i&&(h=="__proto__"||h=="prototype"&&f>0&&l[f-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&b===void 0&&(c[h]===void 0?b=l.slice(0,f).join("/"):f==m-1&&(b=e.path),b!==void 0&&d(e,0,t,b)),f++,Array.isArray(c)){if(h==="-")h=c.length;else{if(n&&!Gr(h))throw new ie("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,e,t);Gr(h)&&(h=~~h)}if(f>=m){if(n&&e.op==="add"&&h>c.length)throw new ie("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,t);var s=jf[e.op].call(e,c,h,t);if(s.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}}else if(f>=m){var s=hn[e.op].call(e,c,h,t);if(s.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(c=c[h],n&&f<m&&(!c||typeof c!="object"))throw new ie("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function zr(t,e,n,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),n&&!Array.isArray(e))throw new ie("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=ye(t));for(var o=new Array(e.length),s=0,a=e.length;s<a;s++)o[s]=Vt(t,e[s],n,!0,i,s),t=o[s].newDocument;return o.newDocument=t,o}function Wf(t,e,n){var r=Vt(t,e);if(r.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function $r(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new ie("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(hn[t.op]){if(typeof t.path!="string")throw new ie("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ie('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ie("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new ie("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Dr(t.value))throw new ie("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var i=t.path.split("/").length,o=r.split("/").length;if(i!==o+1&&i!==o)throw new ie("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new ie("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var s={op:"_get",path:t.from,value:void 0},a=ml([s],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new ie("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new ie("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function ml(t,e,n){try{if(!Array.isArray(t))throw new ie("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)zr(ye(e),ye(t),n||!0);else{n=n||$r;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(i){if(i instanceof ie)return i;throw i}}function jn(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),i,o,s;if(n&&r){if(o=t.length,o!=e.length)return!1;for(i=o;i--!==0;)if(!jn(t[i],e[i]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(o=a.length,o!==Object.keys(e).length)return!1;for(i=o;i--!==0;)if(!e.hasOwnProperty(a[i]))return!1;for(i=o;i--!==0;)if(s=a[i],!jn(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var ms={};Oo(ms,{compare:()=>eh,generate:()=>ps,observe:()=>Qf,unobserve:()=>Jf});var fs=new WeakMap,qf=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),Xf=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function Kf(t){return fs.get(t)}function Zf(t,e){return t.observers.get(e)}function Yf(t,e){t.observers.delete(e.callback)}function Jf(t,e){e.unobserve()}function Qf(t,e){var n=[],r,i=Kf(t);if(!i)i=new qf(t),fs.set(t,i);else{var o=Zf(i,e);r=o&&o.observer}if(r)return r;if(r={},i.value=ye(t),e){r.callback=e,r.next=null;var s=function(){ps(r)},a=function(){clearTimeout(r.next),r.next=setTimeout(s)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return r.patches=n,r.object=t,r.unobserve=function(){ps(r),clearTimeout(r.next),Yf(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},i.observers.set(e,new Xf(e,r)),r}function ps(t,e){e===void 0&&(e=!1);var n=fs.get(t.object);hs(n.value,t.object,t.patches,"",e),t.patches.length&&zr(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function hs(t,e,n,r,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=Hr(e),s=Hr(t),a=!1,l=!1,c=s.length-1;c>=0;c--){var f=s[c],m=t[f];if(Ur(e,f)&&!(e[f]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var b=e[f];typeof m=="object"&&m!=null&&typeof b=="object"&&b!=null&&Array.isArray(m)===Array.isArray(b)?hs(m,b,n,r+"/"+tt(f),i):m!==b&&(a=!0,i&&n.push({op:"test",path:r+"/"+tt(f),value:ye(m)}),n.push({op:"replace",path:r+"/"+tt(f),value:ye(b)}))}else Array.isArray(t)===Array.isArray(e)?(i&&n.push({op:"test",path:r+"/"+tt(f),value:ye(m)}),n.push({op:"remove",path:r+"/"+tt(f)}),l=!0):(i&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!l&&o.length==s.length))for(var c=0;c<o.length;c++){var f=o[c];!Ur(t,f)&&e[f]!==void 0&&n.push({op:"add",path:r+"/"+tt(f),value:ye(e[f])})}}}function eh(t,e,n){n===void 0&&(n=!1);var r=[];return hs(t,e,r,"",n),r}var Br=Object.assign({},ds,ms,{JsonPatchError:Vn,deepClone:ye,escapePathComponent:tt,unescapePathComponent:Bn});var gs=function(t,e){return gs=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i])},gs(t,e)};function nt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");gs(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function gl(t,e,n,r){function i(o){return o instanceof n?o:new n(function(s){s(o)})}return new(n||(n=Promise))(function(o,s){function a(f){try{c(r.next(f))}catch(m){s(m)}}function l(f){try{c(r.throw(f))}catch(m){s(m)}}function c(f){f.done?o(f.value):i(f.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}function Vr(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(f){return l([c,f])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(n=0)),n;)try{if(r=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,i=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){n.label=c[1];break}if(c[0]===6&&n.label<o[1]){n.label=o[1],o=c;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(c);break}o[2]&&n.ops.pop(),n.trys.pop();continue}c=e.call(t,n)}catch(f){c=[6,f],i=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ft(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function mn(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o}function gn(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,o;r<i;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return t.concat(o||Array.prototype.slice.call(e))}function jt(t){return this instanceof jt?(this.v=t,this):new jt(t)}function vl(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,o=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",s),i[Symbol.asyncIterator]=function(){return this},i;function s(h){return function(d){return Promise.resolve(d).then(h,m)}}function a(h,d){r[h]&&(i[h]=function(g){return new Promise(function(x,S){o.push([h,g,x,S])>1||l(h,g)})},d&&(i[h]=d(i[h])))}function l(h,d){try{c(r[h](d))}catch(g){b(o[0][3],g)}}function c(h){h.value instanceof jt?Promise.resolve(h.value.v).then(f,m):b(o[0][2],h)}function f(h){l("next",h)}function m(h){l("throw",h)}function b(h,d){h(d),o.shift(),o.length&&l(o[0][0],o[0][1])}}function bl(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof ft=="function"?ft(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(o){n[o]=t[o]&&function(s){return new Promise(function(a,l){s=t[o](s),i(a,l,s.done,s.value)})}}function i(o,s,a,l){Promise.resolve(l).then(function(c){o({value:c,done:a})},s)}}function z(t){return typeof t=="function"}function vn(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var jr=vn(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
3
|
+
`+n.map(function(r,i){return i+1+") "+r.toString()}).join(`
|
|
4
|
+
`):"",this.name="UnsubscriptionError",this.errors=n}});function Wn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var bn=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,i,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=ft(s),l=a.next();!l.done;l=a.next()){var c=l.value;c.remove(this)}}catch(g){e={error:g}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}else s.remove(this);var f=this.initialTeardown;if(z(f))try{f()}catch(g){o=g instanceof jr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var b=ft(m),h=b.next();!h.done;h=b.next()){var d=h.value;try{yl(d)}catch(g){o=o??[],g instanceof jr?o=gn(gn([],mn(o)),mn(g.errors)):o.push(g)}}}catch(g){r={error:g}}finally{try{h&&!h.done&&(i=b.return)&&i.call(b)}finally{if(r)throw r.error}}}if(o)throw new jr(o)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)yl(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&Wn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&Wn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var vs=bn.EMPTY;function Wr(t){return t instanceof bn||t&&"closed"in t&&z(t.remove)&&z(t.add)&&z(t.unsubscribe)}function yl(t){z(t)?t():t.unsubscribe()}var Ve={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var yn={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=yn.delegate;return i?.setTimeout?i.setTimeout.apply(i,gn([t,e],mn(n))):setTimeout.apply(void 0,gn([t,e],mn(n)))},clearTimeout:function(t){var e=yn.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function qr(t){yn.setTimeout(function(){var e=Ve.onUnhandledError;if(e)e(t);else throw t})}function qn(){}var xl=(function(){return bs("C",void 0,void 0)})();function El(t){return bs("E",void 0,t)}function Tl(t){return bs("N",t,void 0)}function bs(t,e,n){return{kind:t,value:e,error:n}}var Wt=null;function xn(t){if(Ve.useDeprecatedSynchronousErrorHandling){var e=!Wt;if(e&&(Wt={errorThrown:!1,error:null}),t(),e){var n=Wt,r=n.errorThrown,i=n.error;if(Wt=null,r)throw i}}else t()}function Sl(t){Ve.useDeprecatedSynchronousErrorHandling&&Wt&&(Wt.errorThrown=!0,Wt.error=t)}var Xn=(function(t){nt(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Wr(n)&&n.add(r)):r.destination=ih,r}return e.create=function(n,r,i){return new Kr(n,r,i)},e.prototype.next=function(n){this.isStopped?xs(Tl(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?xs(El(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?xs(xl,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(bn);var th=Function.prototype.bind;function ys(t,e){return th.call(t,e)}var nh=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){Xr(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){Xr(r)}else Xr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){Xr(n)}},t})(),Kr=(function(t){nt(e,t);function e(n,r,i){var o=t.call(this)||this,s;if(z(n)||!n)s={next:n??void 0,error:r??void 0,complete:i??void 0};else{var a;o&&Ve.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return o.unsubscribe()},s={next:n.next&&ys(n.next,a),error:n.error&&ys(n.error,a),complete:n.complete&&ys(n.complete,a)}):s=n}return o.destination=new nh(s),o}return e})(Xn);function Xr(t){Ve.useDeprecatedSynchronousErrorHandling?Sl(t):qr(t)}function rh(t){throw t}function xs(t,e){var n=Ve.onStoppedNotification;n&&yn.setTimeout(function(){return n(t,e)})}var ih={closed:!0,next:qn,error:rh,complete:qn};var En=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Tn(t){return t}function Zr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Es(t)}function Es(t){return t.length===0?Tn:t.length===1?t[0]:function(n){return t.reduce(function(r,i){return i(r)},n)}}var ee=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var i=this,o=sh(e)?e:new Kr(e,n,r);return xn(function(){var s=i,a=s.operator,l=s.source;o.add(a?a.call(o,l):l?i._subscribe(o):i._trySubscribe(o))}),o},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=wl(n),new n(function(i,o){var s=new Kr({next:function(a){try{e(a)}catch(l){o(l),s.unsubscribe()}},error:o,complete:i});r.subscribe(s)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[En]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Es(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=wl(e),new e(function(r,i){var o;n.subscribe(function(s){return o=s},function(s){return i(s)},function(){return r(o)})})},t.create=function(e){return new t(e)},t})();function wl(t){var e;return(e=t??Ve.Promise)!==null&&e!==void 0?e:Promise}function oh(t){return t&&z(t.next)&&z(t.error)&&z(t.complete)}function sh(t){return t&&t instanceof Xn||oh(t)&&Wr(t)}function ah(t){return z(t?.lift)}function de(t){return function(e){if(ah(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function me(t,e,n,r,i){return new lh(t,e,n,r,i)}var lh=(function(t){nt(e,t);function e(n,r,i,o,s,a){var l=t.call(this,n)||this;return l.onFinalize=s,l.shouldUnsubscribe=a,l._next=r?function(c){try{r(c)}catch(f){n.error(f)}}:t.prototype._next,l._error=o?function(c){try{o(c)}catch(f){n.error(f)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=i?function(){try{i()}catch(c){n.error(c)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e})(Xn);var _l=vn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var rt=(function(t){nt(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new Al(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new _l},e.prototype.next=function(n){var r=this;xn(function(){var i,o;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var s=ft(r.currentObservers),a=s.next();!a.done;a=s.next()){var l=a.value;l.next(n)}}catch(c){i={error:c}}finally{try{a&&!a.done&&(o=s.return)&&o.call(s)}finally{if(i)throw i.error}}}})},e.prototype.error=function(n){var r=this;xn(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var i=r.observers;i.length;)i.shift().error(n)}})},e.prototype.complete=function(){var n=this;xn(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,i=this,o=i.hasError,s=i.isStopped,a=i.observers;return o||s?vs:(this.currentObservers=null,a.push(n),new bn(function(){r.currentObservers=null,Wn(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,i=r.hasError,o=r.thrownError,s=r.isStopped;i?n.error(o):s&&n.complete()},e.prototype.asObservable=function(){var n=new ee;return n.source=this,n},e.create=function(n,r){return new Al(n,r)},e})(ee);var Al=(function(t){nt(e,t);function e(n,r){var i=t.call(this)||this;return i.destination=n,i.source=r,i}return e.prototype.next=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,n)},e.prototype.error=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&i!==void 0?i:vs},e})(rt);var Ts={now:function(){return(Ts.delegate||Date).now()},delegate:void 0};var Yr=(function(t){nt(e,t);function e(n,r,i){n===void 0&&(n=1/0),r===void 0&&(r=1/0),i===void 0&&(i=Ts);var o=t.call(this)||this;return o._bufferSize=n,o._windowTime=r,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=r===1/0,o._bufferSize=Math.max(1,n),o._windowTime=Math.max(1,r),o}return e.prototype.next=function(n){var r=this,i=r.isStopped,o=r._buffer,s=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;i||(o.push(n),!s&&o.push(a.now()+l)),this._trimBuffer(),t.prototype.next.call(this,n)},e.prototype._subscribe=function(n){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(n),i=this,o=i._infiniteTimeWindow,s=i._buffer,a=s.slice(),l=0;l<a.length&&!n.closed;l+=o?1:2)n.next(a[l]);return this._checkFinalizedStatuses(n),r},e.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,i=n._timestampProvider,o=n._buffer,s=n._infiniteTimeWindow,a=(s?1:2)*r;if(r<1/0&&a<o.length&&o.splice(0,o.length-a),!s){for(var l=i.now(),c=0,f=1;f<o.length&&o[f]<=l;f+=2)c=f;c&&o.splice(0,c+1)}},e})(rt);var Jr=new ee(function(t){return t.complete()});function kl(t){return t&&z(t.schedule)}function ch(t){return t[t.length-1]}function Il(t){return kl(ch(t))?t.pop():void 0}var Qr=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function ei(t){return z(t?.then)}function ti(t){return z(t[En])}function ni(t){return Symbol.asyncIterator&&z(t?.[Symbol.asyncIterator])}function ri(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function uh(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ii=uh();function oi(t){return z(t?.[ii])}function si(t){return vl(this,arguments,function(){var n,r,i,o;return Vr(this,function(s){switch(s.label){case 0:n=t.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,jt(n.read())];case 3:return r=s.sent(),i=r.value,o=r.done,o?[4,jt(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,jt(i)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function ai(t){return z(t?.getReader)}function ge(t){if(t instanceof ee)return t;if(t!=null){if(ti(t))return dh(t);if(Qr(t))return ph(t);if(ei(t))return fh(t);if(ni(t))return Cl(t);if(oi(t))return hh(t);if(ai(t))return mh(t)}throw ri(t)}function dh(t){return new ee(function(e){var n=t[En]();if(z(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function ph(t){return new ee(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function fh(t){return new ee(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,qr)})}function hh(t){return new ee(function(e){var n,r;try{for(var i=ft(t),o=i.next();!o.done;o=i.next()){var s=o.value;if(e.next(s),e.closed)return}}catch(a){n={error:a}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}e.complete()})}function Cl(t){return new ee(function(e){gh(t,e).catch(function(n){return e.error(n)})})}function mh(t){return Cl(si(t))}function gh(t,e){var n,r,i,o;return gl(this,void 0,void 0,function(){var s,a;return Vr(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=bl(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(s=r.value,e.next(s),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),i={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(o=n.return)?[4,o.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function He(t,e,n,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var o=e.schedule(function(){n(),i?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(o),!i)return o}function li(t,e){return e===void 0&&(e=0),de(function(n,r){n.subscribe(me(r,function(i){return He(r,t,function(){return r.next(i)},e)},function(){return He(r,t,function(){return r.complete()},e)},function(i){return He(r,t,function(){return r.error(i)},e)}))})}function ci(t,e){return e===void 0&&(e=0),de(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function Nl(t,e){return ge(t).pipe(ci(e),li(e))}function Rl(t,e){return ge(t).pipe(ci(e),li(e))}function Ol(t,e){return new ee(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function Ml(t,e){return new ee(function(n){var r;return He(n,e,function(){r=t[ii](),He(n,e,function(){var i,o,s;try{i=r.next(),o=i.value,s=i.done}catch(a){n.error(a);return}s?n.complete():n.next(o)},0,!0)}),function(){return z(r?.return)&&r.return()}})}function ui(t,e){if(!t)throw new Error("Iterable cannot be null");return new ee(function(n){He(n,e,function(){var r=t[Symbol.asyncIterator]();He(n,e,function(){r.next().then(function(i){i.done?n.complete():n.next(i.value)})},0,!0)})})}function Ll(t,e){return ui(si(t),e)}function Pl(t,e){if(t!=null){if(ti(t))return Nl(t,e);if(Qr(t))return Ol(t,e);if(ei(t))return Rl(t,e);if(ni(t))return ui(t,e);if(oi(t))return Ml(t,e);if(ai(t))return Ll(t,e)}throw ri(t)}function qt(t,e){return e?Pl(t,e):ge(t)}function re(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=Il(t);return qt(t,n)}function te(t,e){var n=z(t)?t:function(){return t},r=function(i){return i.error(n())};return new ee(e?function(i){return e.schedule(r,0,i)}:r)}var Dl=vn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function di(t,e){var n=typeof e=="object";return new Promise(function(r,i){var o=!1,s;t.subscribe({next:function(a){s=a,o=!0},error:i,complete:function(){o?r(s):n?r(e.defaultValue):i(new Dl)}})})}function Xt(t,e){return de(function(n,r){var i=0;n.subscribe(me(r,function(o){r.next(t.call(e,o,i++))}))})}function Ul(t,e,n,r,i,o,s,a){var l=[],c=0,f=0,m=!1,b=function(){m&&!l.length&&!c&&e.complete()},h=function(g){return c<r?d(g):l.push(g)},d=function(g){o&&e.next(g),c++;var x=!1;ge(n(g,f++)).subscribe(me(e,function(S){i?.(S),o?h(S):e.next(S)},function(){x=!0},void 0,function(){if(x)try{c--;for(var S=function(){var E=l.shift();s?He(e,s,function(){return d(E)}):d(E)};l.length&&c<r;)S();b()}catch(E){e.error(E)}}))};return t.subscribe(me(e,h,function(){m=!0,b()})),function(){a?.()}}function Ce(t,e,n){return n===void 0&&(n=1/0),z(e)?Ce(function(r,i){return Xt(function(o,s){return e(r,o,i,s)})(ge(t(r,i)))},n):(typeof e=="number"&&(n=e),de(function(r,i){return Ul(r,i,t,n)}))}function Ss(t){return t===void 0&&(t=1/0),Ce(Tn,t)}function pi(t){return new ee(function(e){ge(t()).subscribe(e)})}function Kn(t){return de(function(e,n){var r=null,i=!1,o;r=e.subscribe(me(n,void 0,void 0,function(s){o=ge(t(s,Kn(t)(e))),r?(r.unsubscribe(),r=null,o.subscribe(n)):i=!0})),i&&(r.unsubscribe(),r=null,o.subscribe(n))})}function fi(t,e){return z(e)?Ce(t,e,1):Ce(t,1)}function ws(t){return de(function(e,n){var r=!1;e.subscribe(me(n,function(i){r=!0,n.next(i)},function(){r||n.next(t),n.complete()}))})}function Kt(t){return de(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function _s(t,e){return de(function(n,r){var i=null,o=0,s=!1,a=function(){return s&&!i&&r.complete()};n.subscribe(me(r,function(l){i?.unsubscribe();var c=0,f=o++;ge(t(l,f)).subscribe(i=me(r,function(m){return r.next(e?e(l,m,f,c++):m)},function(){i=null,a()}))},function(){s=!0,a()}))})}function hi(t){return de(function(e,n){ge(t).subscribe(me(n,function(){return n.complete()},qn)),!n.closed&&e.subscribe(n)})}function As(t,e,n){var r=z(t)||e||n?{next:t,error:e,complete:n}:t;return r?de(function(i,o){var s;(s=r.subscribe)===null||s===void 0||s.call(r);var a=!0;i.subscribe(me(o,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),o.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),o.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),o.error(l)},function(){var l,c;a&&((l=r.unsubscribe)===null||l===void 0||l.call(r)),(c=r.finalize)===null||c===void 0||c.call(r)}))}):Tn}function Hl(t){return` \r
|
|
5
|
+
`.indexOf(t)>=0}function mi(t){for(var e=["topLevel"],n=0,r,i,o,s=function(E){return e.push(E)},a=function(E){return e[e.length-1]=E},l=function(E){r==null&&(r=n,i=e.length,o=E)},c=function(E){E===o&&(r=void 0,i=void 0,o=void 0)},f=function(){return e.pop()},m=function(){return n--},b=function(E){if("0"<=E&&E<="9"){s("number");return}switch(E){case'"':s("string");return;case"-":s("numberNeedsDigit");return;case"t":s("true");return;case"f":s("false");return;case"n":s("null");return;case"[":s("arrayNeedsValue");return;case"{":s("objectNeedsKey");return}},h=t.length;n<h;n++){var d=t[n];switch(e[e.length-1]){case"topLevel":b(d);break;case"string":switch(d){case'"':f();break;case"\\":l("stringEscape"),s("stringEscaped");break}break;case"stringEscaped":d==="u"?s("stringUnicode"):(c("stringEscape"),f());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(c("stringEscape"),f());break;case"number":d==="."?a("numberNeedsDigit"):d==="e"||d==="E"?a("numberNeedsExponent"):(d<"0"||d>"9")&&(m(),f());break;case"numberNeedsDigit":a("number");break;case"numberNeedsExponent":a(d==="+"||d==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(d<"a"||d>"z")&&(m(),f());break;case"arrayNeedsValue":d==="]"?f():Hl(d)||(c("collectionItem"),a("arrayNeedsComma"),b(d));break;case"arrayNeedsComma":d==="]"?f():d===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":d==="}"?f():d==='"'&&(l("collectionItem"),a("objectNeedsColon"),s("string"));break;case"objectNeedsColon":d===":"&&a("objectNeedsValue");break;case"objectNeedsValue":Hl(d)||(c("collectionItem"),a("objectNeedsComma"),b(d));break;case"objectNeedsComma":d==="}"?f():d===","&&(l("collectionItem"),a("objectNeedsKey"));break}}i!=null&&(e.length=i);for(var g=[r!=null?t.slice(0,r):t],x=function(E){return g.push(E.slice(t.length-t.lastIndexOf(E[0])))},S=e.length-1;S>=0;S--)switch(e[S]){case"string":g.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":g.push("0");break;case"true":x("true");break;case"false":x("false");break;case"null":x("null");break;case"arrayNeedsValue":case"arrayNeedsComma":g.push("]");break;case"objectNeedsKey":case"objectNeedsColon":case"objectNeedsValue":case"objectNeedsComma":g.push("}");break}return g.join("")}function Fl(){let t=0,e=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<r,(i&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let r=3;r<=31;r+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<r,(i&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function vi(t,e,n){for(let o=0;o<28;o=o+7){let s=t>>>o,a=!(!(s>>>7)&&e==0),l=(a?s|128:s)&255;if(n.push(l),!a)return}let r=t>>>28&15|(e&7)<<4,i=e>>3!=0;if(n.push((i?r|128:r)&255),!!i){for(let o=3;o<31;o=o+7){let s=e>>>o,a=!!(s>>>7),l=(a?s|128:s)&255;if(n.push(l),!a)return}n.push(e>>>31&1)}}var gi=4294967296;function ks(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,i=0;function o(s,a){let l=Number(t.slice(s,a));i*=n,r=r*n+l,r>=gi&&(i=i+(r/gi|0),r=r%gi)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),e?zl(r,i):Cs(r,i)}function $l(t,e){let n=Cs(t,e),r=n.hi&2147483648;r&&(n=zl(n.lo,n.hi));let i=Is(n.lo,n.hi);return r?"-"+i:i}function Is(t,e){if({lo:t,hi:e}=vh(t,e),e<=2097151)return String(gi*e+t);let n=t&16777215,r=(t>>>24|e<<8)&16777215,i=e>>16&65535,o=n+r*6777216+i*6710656,s=r+i*8147497,a=i*2,l=1e7;return o>=l&&(s+=Math.floor(o/l),o%=l),s>=l&&(a+=Math.floor(s/l),s%=l),a.toString()+Gl(s)+Gl(o)}function vh(t,e){return{lo:t>>>0,hi:e>>>0}}function Cs(t,e){return{lo:t|0,hi:e|0}}function zl(t,e){return e=~e,t?t=~t+1:e+=1,Cs(t,e)}var Gl=t=>{let e=String(t);return"0000000".slice(e.length)+e};function Ns(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function Bl(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var je=bh();function bh(){let t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(!!globalThis.Deno||!!globalThis.Bun||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let n=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),i=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>r||a<n)throw new Error(`invalid int64: ${s}`);return a},uParse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>o||a<i)throw new Error(`invalid uint64: ${s}`);return a},enc(s){return t.setBigInt64(0,this.parse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(s){return t.setBigInt64(0,this.uParse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigInt64(0,!0)},uDec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),Vl(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),jl(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),Vl(n),ks(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),jl(n),ks(n)},dec(n,r){return $l(n,r)},uDec(n,r){return Is(n,r)}}}function Vl(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function jl(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var Rs=Symbol.for("@bufbuild/protobuf/text-encoding");function Os(){if(globalThis[Rs]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[Rs]={encodeUtf8(r){return t.encode(r)},decodeUtf8(r,i){return i?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(r)):e.decode(r)},checkUtf8(r){try{return encodeURIComponent(r),!0}catch{return!1}}}}return globalThis[Rs]}var St;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(St||(St={}));var yh=34028234663852886e22,xh=-34028234663852886e22,Eh=4294967295,Th=2147483647,Sh=-2147483648,G=class{constructor(e=Os().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let n=new Uint8Array(e),r=0;for(let i=0;i<this.chunks.length;i++)n.set(this.chunks[i],r),r+=this.chunks[i].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Wl(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ms(e),Ns(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let n=this.encodeUtf8(e);return this.uint32(n.byteLength),this.raw(n)}float(e){wh(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){Wl(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){Ms(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return Ms(e),e=(e<<1^e>>31)>>>0,Ns(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),i=je.enc(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),i=je.uEnc(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(n)}int64(e){let n=je.enc(e);return vi(n.lo,n.hi,this.buf),this}sint64(e){let n=je.enc(e),r=n.hi>>31,i=n.lo<<1^r,o=(n.hi<<1|n.lo>>>31)^r;return vi(i,o,this.buf),this}uint64(e){let n=je.uEnc(e);return vi(n.lo,n.hi,this.buf),this}},w=class{constructor(e,n=Os().decodeUtf8){this.decodeUtf8=n,this.varint64=Fl,this.uint32=Bl,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,n=this.uint32(),r=this.pos-e;if(r>5||r==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let i=n>>>3,o=n&7;if(i<=0||o>5)throw new Error("illegal tag: field no "+i+" wire type "+o);return[i,o]}skip(e,n,r=100){let i=this.pos;switch(e){case St.Varint:for(;this.buf[this.pos++]&128;);break;case St.Bit64:this.pos+=4;case St.Bit32:this.pos+=4;break;case St.LengthDelimited:let o=this.uint32();this.pos+=o;break;case St.StartGroup:if(r<=0)throw new Error("maximum recursion depth reached");for(;;){let[s,a]=this.tag();if(a===St.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(a,s,r-1)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return je.dec(...this.varint64())}uint64(){return je.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),r=-(e&1);return e=(e>>>1|(n&1)<<31)^r,n=n>>>1^r,je.dec(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return je.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return je.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(e){return this.decodeUtf8(this.bytes(),e)}};function Ms(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid int32: "+typeof t);if(!Number.isInteger(t)||t>Th||t<Sh)throw new Error("invalid int32: "+t)}function Wl(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid uint32: "+typeof t);if(!Number.isInteger(t)||t>Eh||t<0)throw new Error("invalid uint32: "+t)}function wh(t){if(typeof t=="string"){let e=t;if(t=Number(t),Number.isNaN(t)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof t!="number")throw new Error("invalid float32: "+typeof t);if(Number.isFinite(t)&&(t>yh||t<xh))throw new Error("invalid float32: "+t)}var _h=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Ls(){return{fields:{}}}var Zn={encode(t,e=new G){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&Us.encode({key:n,value:r},e.uint32(10).fork()).join()}),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Ls();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:{if(o!==10)break;let s=Us.decode(n,n.uint32());s.value!==void 0&&(i.fields[s.key]=s.value);continue}}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Zn.fromPartial(t??{})},fromPartial(t){let e=Ls();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,i])=>(i!==void 0&&(n[r]=i),n),{}),e},wrap(t){let e=Ls();if(t!==void 0)for(let n of Object.keys(t))e.fields[n]=t[n];return e},unwrap(t){let e={};if(t.fields)for(let n of Object.keys(t.fields))e[n]=t.fields[n];return e}};function ql(){return{key:"",value:void 0}}var Us={encode(t,e=new G){return t.key!==""&&e.uint32(10).string(t.key),t.value!==void 0&&R.encode(R.wrap(t.value),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=ql();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.key=n.string();continue;case 2:if(o!==18)break;i.value=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Us.fromPartial(t??{})},fromPartial(t){let e=ql();return e.key=t.key??"",e.value=t.value??void 0,e}};function Ps(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var R={encode(t,e=new G){return t.nullValue!==void 0&&e.uint32(8).int32(t.nullValue),t.numberValue!==void 0&&e.uint32(17).double(t.numberValue),t.stringValue!==void 0&&e.uint32(26).string(t.stringValue),t.boolValue!==void 0&&e.uint32(32).bool(t.boolValue),t.structValue!==void 0&&Zn.encode(Zn.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&Yn.encode(Yn.wrap(t.listValue),e.uint32(50).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Ps();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==8)break;i.nullValue=n.int32();continue;case 2:if(o!==17)break;i.numberValue=n.double();continue;case 3:if(o!==26)break;i.stringValue=n.string();continue;case 4:if(o!==32)break;i.boolValue=n.bool();continue;case 5:if(o!==42)break;i.structValue=Zn.unwrap(Zn.decode(n,n.uint32()));continue;case 6:if(o!==50)break;i.listValue=Yn.unwrap(Yn.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return R.fromPartial(t??{})},fromPartial(t){let e=Ps();return e.nullValue=t.nullValue??void 0,e.numberValue=t.numberValue??void 0,e.stringValue=t.stringValue??void 0,e.boolValue=t.boolValue??void 0,e.structValue=t.structValue??void 0,e.listValue=t.listValue??void 0,e},wrap(t){let e=Ps();if(t===null)e.nullValue=_h.NULL_VALUE;else if(typeof t=="boolean")e.boolValue=t;else if(typeof t=="number")e.numberValue=t;else if(typeof t=="string")e.stringValue=t;else if(globalThis.Array.isArray(t))e.listValue=t;else if(typeof t=="object")e.structValue=t;else if(typeof t<"u")throw new globalThis.Error("Unsupported any value type: "+typeof t);return e},unwrap(t){if(t.stringValue!==void 0)return t.stringValue;if(t?.numberValue!==void 0)return t.numberValue;if(t?.boolValue!==void 0)return t.boolValue;if(t?.structValue!==void 0)return t.structValue;if(t?.listValue!==void 0)return t.listValue;if(t?.nullValue!==void 0)return null}};function Ds(){return{values:[]}}var Yn={encode(t,e=new G){for(let n of t.values)R.encode(R.wrap(n),e.uint32(10).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Ds();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.values.push(R.unwrap(R.decode(n,n.uint32())));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Yn.fromPartial(t??{})},fromPartial(t){let e=Ds();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=Ds();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},Ah=(function(t){return t[t.ADD=0]="ADD",t[t.REMOVE=1]="REMOVE",t[t.REPLACE=2]="REPLACE",t[t.MOVE=3]="MOVE",t[t.COPY=4]="COPY",t[t.TEST=5]="TEST",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Xl(){return{op:0,path:"",from:void 0,value:void 0}}var yi={encode(t,e=new G){return t.op!==0&&e.uint32(8).int32(t.op),t.path!==""&&e.uint32(18).string(t.path),t.from!==void 0&&e.uint32(26).string(t.from),t.value!==void 0&&R.encode(R.wrap(t.value),e.uint32(34).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Xl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==8)break;i.op=n.int32();continue;case 2:if(o!==18)break;i.path=n.string();continue;case 3:if(o!==26)break;i.from=n.string();continue;case 4:if(o!==34)break;i.value=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return yi.fromPartial(t??{})},fromPartial(t){let e=Xl();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function Kl(){return{id:"",type:"",function:void 0}}var xi={encode(t,e=new G){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&Ei.encode(t.function,e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Kl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.id=n.string();continue;case 2:if(o!==18)break;i.type=n.string();continue;case 3:if(o!==26)break;i.function=Ei.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return xi.fromPartial(t??{})},fromPartial(t){let e=Kl();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?Ei.fromPartial(t.function):void 0,e}};function Zl(){return{name:"",arguments:""}}var Ei={encode(t,e=new G){return t.name!==""&&e.uint32(10).string(t.name),t.arguments!==""&&e.uint32(18).string(t.arguments),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Zl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.name=n.string();continue;case 2:if(o!==18)break;i.arguments=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ei.fromPartial(t??{})},fromPartial(t){let e=Zl();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function Yl(){return{value:"",mimeType:""}}var Ti={encode(t,e=new G){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==""&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Yl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.value=n.string();continue;case 2:if(o!==18)break;i.mimeType=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ti.fromPartial(t??{})},fromPartial(t){let e=Yl();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function Jl(){return{value:"",mimeType:void 0}}var Si={encode(t,e=new G){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==void 0&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Jl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.value=n.string();continue;case 2:if(o!==18)break;i.mimeType=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Si.fromPartial(t??{})},fromPartial(t){let e=Jl();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function Ql(){return{data:void 0,url:void 0}}var Re={encode(t,e=new G){return t.data!==void 0&&Ti.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&Si.encode(t.url,e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Ql();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.data=Ti.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.url=Si.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Re.fromPartial(t??{})},fromPartial(t){let e=Ql();return e.data=t.data!==void 0&&t.data!==null?Ti.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?Si.fromPartial(t.url):void 0,e}};function ec(){return{text:""}}var wi={encode(t,e=new G){return t.text!==""&&e.uint32(10).string(t.text),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=ec();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.text=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return wi.fromPartial(t??{})},fromPartial(t){let e=ec();return e.text=t.text??"",e}};function tc(){return{source:void 0,metadata:void 0}}var _i={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=tc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Re.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return _i.fromPartial(t??{})},fromPartial(t){let e=tc();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function nc(){return{source:void 0,metadata:void 0}}var Ai={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=nc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Re.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ai.fromPartial(t??{})},fromPartial(t){let e=nc();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function rc(){return{source:void 0,metadata:void 0}}var ki={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=rc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Re.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return ki.fromPartial(t??{})},fromPartial(t){let e=rc();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function ic(){return{source:void 0,metadata:void 0}}var Ii={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=ic();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Re.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ii.fromPartial(t??{})},fromPartial(t){let e=ic();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function oc(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var Ci={encode(t,e=new G){return t.text!==void 0&&wi.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&_i.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&Ai.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&ki.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&Ii.encode(t.document,e.uint32(42).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=oc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.text=wi.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.image=_i.decode(n,n.uint32());continue;case 3:if(o!==26)break;i.audio=Ai.decode(n,n.uint32());continue;case 4:if(o!==34)break;i.video=ki.decode(n,n.uint32());continue;case 5:if(o!==42)break;i.document=Ii.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ci.fromPartial(t??{})},fromPartial(t){let e=oc();return e.text=t.text!==void 0&&t.text!==null?wi.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?_i.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?Ai.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?ki.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?Ii.fromPartial(t.document):void 0,e}};function sc(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var Ni={encode(t,e=new G){t.id!==""&&e.uint32(10).string(t.id),t.role!==""&&e.uint32(18).string(t.role),t.content!==void 0&&e.uint32(26).string(t.content),t.name!==void 0&&e.uint32(34).string(t.name);for(let n of t.toolCalls)xi.encode(n,e.uint32(42).fork()).join();t.toolCallId!==void 0&&e.uint32(50).string(t.toolCallId),t.error!==void 0&&e.uint32(58).string(t.error);for(let n of t.contentParts)Ci.encode(n,e.uint32(66).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=sc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.id=n.string();continue;case 2:if(o!==18)break;i.role=n.string();continue;case 3:if(o!==26)break;i.content=n.string();continue;case 4:if(o!==34)break;i.name=n.string();continue;case 5:if(o!==42)break;i.toolCalls.push(xi.decode(n,n.uint32()));continue;case 6:if(o!==50)break;i.toolCallId=n.string();continue;case 7:if(o!==58)break;i.error=n.string();continue;case 8:if(o!==66)break;i.contentParts.push(Ci.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ni.fromPartial(t??{})},fromPartial(t){let e=sc();return e.id=t.id??"",e.role=t.role??"",e.content=t.content??void 0,e.name=t.name??void 0,e.toolCalls=t.toolCalls?.map(n=>xi.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>Ci.fromPartial(n))||[],e}};function ac(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Ri={encode(t,e=new G){return t.id!==""&&e.uint32(10).string(t.id),t.reason!==""&&e.uint32(18).string(t.reason),t.message!==void 0&&e.uint32(26).string(t.message),t.toolCallId!==void 0&&e.uint32(34).string(t.toolCallId),t.responseSchema!==void 0&&R.encode(R.wrap(t.responseSchema),e.uint32(42).fork()).join(),t.expiresAt!==void 0&&e.uint32(50).string(t.expiresAt),t.metadata!==void 0&&R.encode(R.wrap(t.metadata),e.uint32(58).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=ac();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.id=n.string();continue;case 2:if(o!==18)break;i.reason=n.string();continue;case 3:if(o!==26)break;i.message=n.string();continue;case 4:if(o!==34)break;i.toolCallId=n.string();continue;case 5:if(o!==42)break;i.responseSchema=R.unwrap(R.decode(n,n.uint32()));continue;case 6:if(o!==50)break;i.expiresAt=n.string();continue;case 7:if(o!==58)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ri.fromPartial(t??{})},fromPartial(t){let e=ac();return e.id=t.id??"",e.reason=t.reason??"",e.message=t.message??void 0,e.toolCallId=t.toolCallId??void 0,e.responseSchema=t.responseSchema??void 0,e.expiresAt=t.expiresAt??void 0,e.metadata=t.metadata??void 0,e}},kh=(function(t){return t[t.TEXT_MESSAGE_START=0]="TEXT_MESSAGE_START",t[t.TEXT_MESSAGE_CONTENT=1]="TEXT_MESSAGE_CONTENT",t[t.TEXT_MESSAGE_END=2]="TEXT_MESSAGE_END",t[t.TOOL_CALL_START=3]="TOOL_CALL_START",t[t.TOOL_CALL_ARGS=4]="TOOL_CALL_ARGS",t[t.TOOL_CALL_END=5]="TOOL_CALL_END",t[t.STATE_SNAPSHOT=6]="STATE_SNAPSHOT",t[t.STATE_DELTA=7]="STATE_DELTA",t[t.MESSAGES_SNAPSHOT=8]="MESSAGES_SNAPSHOT",t[t.RAW=9]="RAW",t[t.CUSTOM=10]="CUSTOM",t[t.RUN_STARTED=11]="RUN_STARTED",t[t.RUN_FINISHED=12]="RUN_FINISHED",t[t.RUN_ERROR=13]="RUN_ERROR",t[t.STEP_STARTED=14]="STEP_STARTED",t[t.STEP_FINISHED=15]="STEP_FINISHED",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function lc(){return{type:0,timestamp:void 0,rawEvent:void 0}}var O={encode(t,e=new G){return t.type!==0&&e.uint32(8).int32(t.type),t.timestamp!==void 0&&e.uint32(16).int64(t.timestamp),t.rawEvent!==void 0&&R.encode(R.wrap(t.rawEvent),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=lc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==8)break;i.type=n.int32();continue;case 2:if(o!==16)break;i.timestamp=Ih(n.int64());continue;case 3:if(o!==26)break;i.rawEvent=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return O.fromPartial(t??{})},fromPartial(t){let e=lc();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function cc(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Oi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.name!==void 0&&e.uint32(34).string(t.name),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=cc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue;case 3:if(o!==26)break;i.role=n.string();continue;case 4:if(o!==34)break;i.name=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Oi.fromPartial(t??{})},fromPartial(t){let e=cc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.role=t.role??void 0,e.name=t.name??void 0,e}};function uc(){return{baseEvent:void 0,messageId:"",delta:""}}var Mi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=uc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue;case 3:if(o!==26)break;i.delta=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Mi.fromPartial(t??{})},fromPartial(t){let e=uc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.delta=t.delta??"",e}};function dc(){return{baseEvent:void 0,messageId:""}}var Li={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=dc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Li.fromPartial(t??{})},fromPartial(t){let e=dc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function pc(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Pi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.toolCallName!==""&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=pc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue;case 3:if(o!==26)break;i.toolCallName=n.string();continue;case 4:if(o!==34)break;i.parentMessageId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Pi.fromPartial(t??{})},fromPartial(t){let e=pc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.toolCallName=t.toolCallName??"",e.parentMessageId=t.parentMessageId??void 0,e}};function fc(){return{baseEvent:void 0,toolCallId:"",delta:""}}var Di={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=fc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue;case 3:if(o!==26)break;i.delta=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Di.fromPartial(t??{})},fromPartial(t){let e=fc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.delta=t.delta??"",e}};function hc(){return{baseEvent:void 0,toolCallId:""}}var Ui={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=hc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ui.fromPartial(t??{})},fromPartial(t){let e=hc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function mc(){return{baseEvent:void 0,snapshot:void 0}}var Hi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.snapshot!==void 0&&R.encode(R.wrap(t.snapshot),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=mc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.snapshot=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Hi.fromPartial(t??{})},fromPartial(t){let e=mc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function gc(){return{baseEvent:void 0,delta:[]}}var Gi={encode(t,e=new G){t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)yi.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=gc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.delta.push(yi.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Gi.fromPartial(t??{})},fromPartial(t){let e=gc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>yi.fromPartial(n))||[],e}};function vc(){return{baseEvent:void 0,messages:[]}}var Fi={encode(t,e=new G){t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)Ni.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=vc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messages.push(Ni.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Fi.fromPartial(t??{})},fromPartial(t){let e=vc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>Ni.fromPartial(n))||[],e}};function bc(){return{baseEvent:void 0,event:void 0,source:void 0}}var $i={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.event!==void 0&&R.encode(R.wrap(t.event),e.uint32(18).fork()).join(),t.source!==void 0&&e.uint32(26).string(t.source),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=bc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.event=R.unwrap(R.decode(n,n.uint32()));continue;case 3:if(o!==26)break;i.source=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return $i.fromPartial(t??{})},fromPartial(t){let e=bc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.event=t.event??void 0,e.source=t.source??void 0,e}};function yc(){return{baseEvent:void 0,name:"",value:void 0}}var zi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.name!==""&&e.uint32(18).string(t.name),t.value!==void 0&&R.encode(R.wrap(t.value),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=yc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.name=n.string();continue;case 3:if(o!==26)break;i.value=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return zi.fromPartial(t??{})},fromPartial(t){let e=yc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.name=t.name??"",e.value=t.value??void 0,e}};function xc(){return{baseEvent:void 0,threadId:"",runId:""}}var Bi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=xc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.threadId=n.string();continue;case 3:if(o!==26)break;i.runId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Bi.fromPartial(t??{})},fromPartial(t){let e=xc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e}};function Ec(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var Vi={encode(t,e=new G){t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),t.result!==void 0&&R.encode(R.wrap(t.result),e.uint32(34).fork()).join(),t.outcome!==""&&e.uint32(42).string(t.outcome);for(let n of t.interrupts)Ri.encode(n,e.uint32(50).fork()).join();return e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Ec();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.threadId=n.string();continue;case 3:if(o!==26)break;i.runId=n.string();continue;case 4:if(o!==34)break;i.result=R.unwrap(R.decode(n,n.uint32()));continue;case 5:if(o!==42)break;i.outcome=n.string();continue;case 6:if(o!==50)break;i.interrupts.push(Ri.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Vi.fromPartial(t??{})},fromPartial(t){let e=Ec();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e.result=t.result??void 0,e.outcome=t.outcome??"",e.interrupts=t.interrupts?.map(n=>Ri.fromPartial(n))||[],e}};function Tc(){return{baseEvent:void 0,code:void 0,message:""}}var ji={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.code!==void 0&&e.uint32(18).string(t.code),t.message!==""&&e.uint32(26).string(t.message),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Tc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.code=n.string();continue;case 3:if(o!==26)break;i.message=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return ji.fromPartial(t??{})},fromPartial(t){let e=Tc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.code=t.code??void 0,e.message=t.message??"",e}};function Sc(){return{baseEvent:void 0,stepName:""}}var Wi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Sc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.stepName=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Wi.fromPartial(t??{})},fromPartial(t){let e=Sc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function wc(){return{baseEvent:void 0,stepName:""}}var qi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=wc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.stepName=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return qi.fromPartial(t??{})},fromPartial(t){let e=wc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function _c(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var Xi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==void 0&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.delta!==void 0&&e.uint32(34).string(t.delta),t.name!==void 0&&e.uint32(42).string(t.name),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=_c();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue;case 3:if(o!==26)break;i.role=n.string();continue;case 4:if(o!==34)break;i.delta=n.string();continue;case 5:if(o!==42)break;i.name=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Xi.fromPartial(t??{})},fromPartial(t){let e=_c();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??void 0,e.role=t.role??void 0,e.delta=t.delta??void 0,e.name=t.name??void 0,e}};function Ac(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var Ki={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==void 0&&e.uint32(18).string(t.toolCallId),t.toolCallName!==void 0&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),t.delta!==void 0&&e.uint32(42).string(t.delta),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=Ac();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue;case 3:if(o!==26)break;i.toolCallName=n.string();continue;case 4:if(o!==34)break;i.parentMessageId=n.string();continue;case 5:if(o!==42)break;i.delta=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ki.fromPartial(t??{})},fromPartial(t){let e=Ac();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??void 0,e.toolCallName=t.toolCallName??void 0,e.parentMessageId=t.parentMessageId??void 0,e.delta=t.delta??void 0,e}};function kc(){return{textMessageStart:void 0,textMessageContent:void 0,textMessageEnd:void 0,toolCallStart:void 0,toolCallArgs:void 0,toolCallEnd:void 0,stateSnapshot:void 0,stateDelta:void 0,messagesSnapshot:void 0,raw:void 0,custom:void 0,runStarted:void 0,runFinished:void 0,runError:void 0,stepStarted:void 0,stepFinished:void 0,textMessageChunk:void 0,toolCallChunk:void 0}}var Ic={encode(t,e=new G){return t.textMessageStart!==void 0&&Oi.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&Mi.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Li.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Pi.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&Di.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Ui.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Hi.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Gi.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Fi.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&$i.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&zi.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&Bi.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&Vi.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&ji.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&Wi.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&qi.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&Xi.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&Ki.encode(t.toolCallChunk,e.uint32(146).fork()).join(),e},decode(t,e){let n=t instanceof w?t:new w(t),r=e===void 0?n.len:n.pos+e,i=kc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.textMessageStart=Oi.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.textMessageContent=Mi.decode(n,n.uint32());continue;case 3:if(o!==26)break;i.textMessageEnd=Li.decode(n,n.uint32());continue;case 4:if(o!==34)break;i.toolCallStart=Pi.decode(n,n.uint32());continue;case 5:if(o!==42)break;i.toolCallArgs=Di.decode(n,n.uint32());continue;case 6:if(o!==50)break;i.toolCallEnd=Ui.decode(n,n.uint32());continue;case 7:if(o!==58)break;i.stateSnapshot=Hi.decode(n,n.uint32());continue;case 8:if(o!==66)break;i.stateDelta=Gi.decode(n,n.uint32());continue;case 9:if(o!==74)break;i.messagesSnapshot=Fi.decode(n,n.uint32());continue;case 10:if(o!==82)break;i.raw=$i.decode(n,n.uint32());continue;case 11:if(o!==90)break;i.custom=zi.decode(n,n.uint32());continue;case 12:if(o!==98)break;i.runStarted=Bi.decode(n,n.uint32());continue;case 13:if(o!==106)break;i.runFinished=Vi.decode(n,n.uint32());continue;case 14:if(o!==114)break;i.runError=ji.decode(n,n.uint32());continue;case 15:if(o!==122)break;i.stepStarted=Wi.decode(n,n.uint32());continue;case 16:if(o!==130)break;i.stepFinished=qi.decode(n,n.uint32());continue;case 17:if(o!==138)break;i.textMessageChunk=Xi.decode(n,n.uint32());continue;case 18:if(o!==146)break;i.toolCallChunk=Ki.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ic.fromPartial(t??{})},fromPartial(t){let e=kc();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?Oi.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?Mi.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Li.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Pi.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?Di.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Ui.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Hi.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Gi.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Fi.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?$i.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?zi.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?Bi.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?Vi.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?ji.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?Wi.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?qi.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?Xi.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?Ki.fromPartial(t.toolCallChunk):void 0,e}};function Ih(t){let e=globalThis.Number(t.toString());if(e>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(e<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return e}var bi=t=>{if(!(!t||typeof t!="object")){if(t.data)return{type:"data",value:t.data.value,mimeType:t.data.mimeType};if(t.url)return{type:"url",value:t.url.value,mimeType:t.url.mimeType}}},Ch=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:bi(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:bi(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:bi(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:bi(t.document.source),metadata:t.document.metadata}}};function Cc(t){let e=Ic.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=kh[n.baseEvent.type],n.timestamp=n.baseEvent.timestamp,n.rawEvent=n.baseEvent.rawEvent,delete n.baseEvent,n.type===v.MESSAGES_SNAPSHOT)for(let r of n.messages){let i=r;if(i.role==="user"&&Array.isArray(i.contentParts)){let o=i.contentParts.map(s=>Ch(s)).filter(s=>s!==void 0);o.length>0&&(i.content=o)}Array.isArray(i.contentParts)&&i.contentParts.length===0&&(i.contentParts=void 0),i.toolCalls?.length===0&&(i.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,i=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,o=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,i==="interrupt"?r.outcome={type:"interrupt",interrupts:o}:i==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=Ah[r.op].toLowerCase(),Object.keys(r).forEach(i=>{r[i]===void 0&&delete r[i]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Pr.parse(n)}var Hs="application/vnd.ag-ui.event+proto";var Rh=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Gs=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(Rh);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},Nc=t=>t==="*"||t==="x"||t==="X",Rc=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},Oh=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],Mh=(t,e)=>{if(Nc(t)||Nc(e))return 0;let[n,r]=Oh(Rc(t),Rc(e));return n>r?1:n<r?-1:0},Fs=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=Mh(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var Jn=(t,e)=>{let n=Gs(t),r=Gs(e),i=n.pop(),o=r.pop(),s=Fs(n,r);return s!==0?s:i&&o?Fs(i.split("."),o.split(".")):i||o?i?-1:1:0};var j=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function Oe(){return bt()}function Bs(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&Bs(e);return t}var Oc=512*1024;function Mc(t,e,n){let r=0,i=[t,e],o=new WeakSet;for(;i.length>0;){let s=i.pop();if(typeof s=="string"){if(r+=s.length,r>n)return!0}else if(typeof s=="object"&&s){if(o.has(s))continue;if(o.add(s),Array.isArray(s))for(let a=0;a<s.length;a++)i.push(s[a]);else{let a=Object.keys(s);for(let l=0;l<a.length;l++){let c=a[l];if(r+=c.length,r>n)return!0;i.push(s[c])}}}}return!1}async function K(t,e,n,r){let i=typeof process<"u"&&process.env!==void 0,o=i&&!!process.env.VITEST_WORKER_ID,s=i&&!!process.env.VITEST_WORKER_ID,a=s&&!Mc(e,n,Oc),l=a?j(e):e,c=a?j(n):n,f=!1,m=!1,b;for(let h of t)try{a&&(Bs(l),Bs(c));let d=await r(h,l,c);if(d===void 0)continue;let g=!1;if(d.messages!==void 0&&d.messages!==l&&(l=j(d.messages),f=!0,g=!0),d.state!==void 0&&d.state!==c&&(c=j(d.state),m=!0,g=!0),a&&g&&Mc(l,c,Oc)&&(a=!1),b=d.stopPropagation,b===!0)break}catch(d){if(s&&d instanceof TypeError){if(o)throw d;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",d)}else o||console.error("Subscriber error:",d);continue}return{...f?{messages:Object.isFrozen(l)?j(l):l}:{},...m?{state:Object.isFrozen(c)?j(c):c}:{},...b===void 0?{}:{stopPropagation:b}}}function Zi(t){if(!t)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(t===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let e=t.events??!0,n=t.lifecycle??!0,r=t.verbose??!1;return{enabled:e||n,events:e,lifecycle:n,verbose:r}}function Qn(t){if(t instanceof Vs)return t;if(t===!0)return new Vs(Zi(!0))}var Vs=class{constructor(t){this.config=t}event(t,e,n,r){this.config.events&&(this.config.verbose?console.debug(`[${t}] ${e}`,typeof n=="string"?n:JSON.stringify(n)):console.debug(`[${t}] ${e}`,r??n))}lifecycle(t,e,n){this.config.lifecycle&&(n?console.debug(`[${t}] ${e}`,n):console.debug(`[${t}] ${e}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function $s(t){return t.enabled?new Vs(t):void 0}function Lh(t,e,n){if(e){let i=t.find(s=>s.id===e);if(i?.role==="assistant")return i;i&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${i.role}' message, not assistant \u2014 falling back to toolCallId`);let o={id:i?n:e,role:"assistant",toolCalls:[]};return t.push(o),o}let r={id:n,role:"assistant",toolCalls:[]};return t.push(r),r}var Gc=(t,e,n,r,i)=>{let o=Qn(i),s=j(n.messages),a=j(t.state),l={},c=m=>{m.messages!==void 0&&(s=m.messages,l.messages=m.messages),m.state!==void 0&&(a=m.state,l.state=m.state)},f=()=>{let m=j(l);return l={},m.messages!==void 0||m.state!==void 0?re(m):Jr};return e.pipe(fi(async m=>{let b=await K(r,s,a,(h,d,g)=>h.onEvent?.({event:m,agent:n,input:t,messages:d,state:g}));if(c(b),b.stopPropagation===!0?o?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):o?.event("APPLY","Event applied:",m,{type:m.type,subscribers:r.length}),b.stopPropagation===!0)return f();switch(m.type){case v.TEXT_MESSAGE_START:{let h=await K(r,s,a,(d,g,x)=>d.onTextMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:d,role:g="assistant",name:x}=m;if(!s.find(S=>S.id===d)){let S={id:d,role:g,content:"",...x!==void 0&&{name:x}};s.push(S),c({messages:s})}}return f()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:h,delta:d}=m,g=s.find(S=>S.id===h);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${h}'`),f();let x=await K(r,s,a,(S,E,I)=>S.onTextMessageContentEvent?.({event:m,messages:E,state:I,agent:n,input:t,textMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${d}`,c({messages:s})),f()}case v.TEXT_MESSAGE_END:{let{messageId:h}=m,d=s.find(g=>g.id===h);return d?(c(await K(r,s,a,(g,x,S)=>g.onTextMessageEndEvent?.({event:m,messages:x,state:S,agent:n,input:t,textMessageBuffer:typeof d.content=="string"?d.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:d,messages:s,state:a,agent:n,input:t})})),f()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${h}'`),f())}case v.TOOL_CALL_START:{let h=await K(r,s,a,(d,g,x)=>d.onToolCallStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{toolCallId:d,toolCallName:g,parentMessageId:x}=m,S=Lh(s,x,d);S.toolCalls??=[],S.toolCalls.push({id:d,type:"function",function:{name:g,arguments:""}}),c({messages:s})}return f()}case v.TOOL_CALL_ARGS:{let{toolCallId:h,delta:d}=m,g=s.find(E=>E.toolCalls?.some(I=>I.id===h));if(!g)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${h}'`),f();let x=g.toolCalls?.find(E=>E.id===h);if(!x)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h}'`),f();let S=await K(r,s,a,(E,I,D)=>{let P=x.function.arguments,U=x.function.name,we={};try{we=mi(P)}catch{}return E.onToolCallArgsEvent?.({event:m,messages:I,state:D,agent:n,input:t,toolCallBuffer:P,toolCallName:U,partialToolCallArgs:we})});return c(S),S.stopPropagation!==!0&&(x.function.arguments+=d,c({messages:s})),f()}case v.TOOL_CALL_END:{let{toolCallId:h}=m,d=s.find(x=>x.toolCalls?.some(S=>S.id===h));if(!d)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${h}'`),f();let g=d.toolCalls?.find(x=>x.id===h);return g?(c(await K(r,s,a,(x,S,E)=>{let I=g.function.arguments,D=g.function.name,P={};try{P=JSON.parse(I)}catch{}return x.onToolCallEndEvent?.({event:m,messages:S,state:E,agent:n,input:t,toolCallName:D,toolCallArgs:P})})),await Promise.all(r.map(x=>{x.onNewToolCall?.({toolCall:g,messages:s,state:a,agent:n,input:t})})),f()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${h}'`),f())}case v.TOOL_CALL_RESULT:{let h=await K(r,s,a,(d,g,x)=>d.onToolCallResultEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:d,toolCallId:g,content:x,role:S}=m,E={id:d,toolCallId:g,role:S||"tool",content:x},I=s.findIndex(D=>D.role==="assistant"&&D.toolCalls?.some(P=>P.id===g));if(I===-1)s.push(E);else{let D=I+1;for(;D<s.length&&s[D].role==="tool";)D++;s.splice(D,0,E)}await Promise.all(r.map(D=>{D.onNewMessage?.({message:E,messages:s,state:a,agent:n,input:t})})),c({messages:s})}return f()}case v.STATE_SNAPSHOT:{let h=await K(r,s,a,(d,g,x)=>d.onStateSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{snapshot:d}=m;a=d,c({state:a})}return f()}case v.STATE_DELTA:{let h=await K(r,s,a,(d,g,x)=>d.onStateDeltaEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{delta:d}=m;try{a=Br.applyPatch(a,d,!0,!1).newDocument,c({state:a})}catch(g){let x=g instanceof Error?g.message:String(g);console.warn(`Failed to apply state patch:
|
|
6
6
|
Current state: ${JSON.stringify(a,null,2)}
|
|
7
7
|
Patch operations: ${JSON.stringify(d,null,2)}
|
|
8
|
-
Error: ${x}`)}}return p()}case v.MESSAGES_SNAPSHOT:{let h=await K(r,s,a,(d,g,x)=>d.onMessagesSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messages:d}=m,g=new Map(d.map(I=>[I.id,I])),x=d.some(I=>I.role==="reasoning"),S=I=>I.role==="activity"||I.role==="reasoning"&&!x;s=s.filter(I=>S(I)||g.has(I.id)).map(I=>S(I)?I:g.get(I.id));let E=new Set(s.map(I=>I.id));for(let I of d)E.has(I.id)||s.push(I);c({messages:s})}return p()}case v.ACTIVITY_SNAPSHOT:{let h=m,d=s.findIndex(I=>I.id===h.messageId),g=d>=0?s[d]:void 0,x=g?.role==="activity"?g:void 0,S=h.replace??!0,E=await K(r,s,a,(I,D,P)=>I.onActivitySnapshotEvent?.({event:h,messages:D,state:P,agent:n,input:t,activityMessage:x,existingMessage:g}));if(c(E),E.stopPropagation!==!0){let I={id:h.messageId,role:"activity",activityType:h.activityType,content:V(h.content)},D;d===-1?(s.push(I),D=I):x?S&&(s[d]={...x,activityType:h.activityType,content:V(h.content)}):S&&(s[d]=I,D=I),c({messages:s}),D&&await Promise.all(r.map(P=>P.onNewMessage?.({message:D,messages:s,state:a,agent:n,input:t})))}return p()}case v.ACTIVITY_DELTA:{let h=m,d=s.findIndex(E=>E.id===h.messageId);if(d===-1)return p();let g=s[d];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${h.messageId}' is not an activity message`),p();let x=g,S=await K(r,s,a,(E,I,D)=>E.onActivityDeltaEvent?.({event:h,messages:I,state:D,agent:n,input:t,activityMessage:x}));if(c(S),S.stopPropagation!==!0)try{let E=V(x.content??{}),I=Fr.applyPatch(E,h.patch??[],!0,!1).newDocument;s[d]={...x,content:V(I),activityType:h.activityType},c({messages:s})}catch(E){let I=E instanceof Error?E.message:String(E);console.warn(`Failed to apply activity patch for '${h.messageId}': ${I}`)}return p()}case v.RAW:return c(await K(r,s,a,(h,d,g)=>h.onRawEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),p();case v.CUSTOM:return c(await K(r,s,a,(h,d,g)=>h.onCustomEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),p();case v.RUN_STARTED:{let h=await K(r,s,a,(d,g,x)=>d.onRunStartedEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let d=m;if(d.input?.messages){for(let g of d.input.messages)s.find(x=>x.id===g.id)||s.push(g);c({messages:s})}}return p()}case v.RUN_FINISHED:{let h=m,d=h.outcome?.type==="interrupt"?{event:h,outcome:"interrupt",interrupts:h.outcome.interrupts}:{event:h,outcome:"success",result:h.result},g=await K(r,s,a,(x,S,E)=>x.onRunFinishedEvent?.({...d,messages:S,state:E,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=d.outcome==="interrupt"?[...d.interrupts]:[]),p()}case v.RUN_ERROR:return c(await K(r,s,a,(h,d,g)=>h.onRunErrorEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),p();case v.STEP_STARTED:return c(await K(r,s,a,(h,d,g)=>h.onStepStartedEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),p();case v.STEP_FINISHED:return c(await K(r,s,a,(h,d,g)=>h.onStepFinishedEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),p();case v.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case v.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be tranformed before being applied");case v.THINKING_START:return p();case v.THINKING_END:return p();case v.THINKING_TEXT_MESSAGE_START:return p();case v.THINKING_TEXT_MESSAGE_CONTENT:return p();case v.THINKING_TEXT_MESSAGE_END:return p();case v.REASONING_START:return c(await K(r,s,a,(h,d,g)=>h.onReasoningStartEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),p();case v.REASONING_MESSAGE_START:{let h=await K(r,s,a,(d,g,x)=>d.onReasoningMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:d}=m;if(!s.find(g=>g.id===d)){let g={id:d,role:"reasoning",content:""};s.push(g),c({messages:s})}}return p()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:h,delta:d}=m,g=s.find(S=>S.id===h);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${h}'`),p();let x=await K(r,s,a,(S,E,I)=>S.onReasoningMessageContentEvent?.({event:m,messages:E,state:I,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${d}`,c({messages:s})),p()}case v.REASONING_MESSAGE_END:{let{messageId:h}=m,d=s.find(g=>g.id===h);return d?(c(await K(r,s,a,(g,x,S)=>g.onReasoningMessageEndEvent?.({event:m,messages:x,state:S,agent:n,input:t,reasoningMessageBuffer:typeof d.content=="string"?d.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:d,messages:s,state:a,agent:n,input:t})})),p()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${h}'`),p())}case v.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case v.REASONING_END:return c(await K(r,s,a,(h,d,g)=>h.onReasoningEndEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),p();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:h,entityId:d,encryptedValue:g}=m,x=await K(r,s,a,(S,E,I)=>S.onReasoningEncryptedValueEvent?.({event:m,messages:E,state:I,agent:n,input:t}));if(c(x),x.stopPropagation!==!0){let S=!1;if(h==="tool-call"){for(let E of s)if(E.role==="assistant"&&E.toolCalls){let I=E.toolCalls.find(D=>D.id===d);if(I){I.encryptedValue=g,S=!0;break}}}else{let E=s.find(I=>I.id===d);E?.role!=="activity"&&E&&(E.encryptedValue=g,S=!0)}S&&(l.messages=s)}return p()}}return m.type,p()}),ys(),r.length>0?xs({}):m=>m)},Hs=t=>e=>{let n=Jn(t),r=new Map,o=new Map,i=!1,s=!1,a=!1,l=new Map,c=!1,p=!1,m=!1,b=()=>{r.clear(),o.clear(),l.clear(),c=!1,p=!1,i=!1,s=!1,m=!0};return e.pipe(Ce(h=>{let d=h.type;if(n?.event("VERIFY","Event:",h,{type:h.type}),s)return te(()=>new Q(`Cannot send event type '${d}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(i&&d!==v.RUN_ERROR&&d!==v.RUN_STARTED)return te(()=>new Q(`Cannot send event type '${d}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(a){if(d===v.RUN_STARTED){if(m&&!i)return te(()=>new Q("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));i&&b()}}else if(a=!0,d!==v.RUN_STARTED&&d!==v.RUN_ERROR)return te(()=>new Q("First event must be 'RUN_STARTED'"));switch(d){case v.TEXT_MESSAGE_START:{let g=h.messageId;return r.has(g)?te(()=>new Q(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${g}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(r.set(g,!0),ne(h))}case v.TEXT_MESSAGE_CONTENT:{let g=h.messageId;return r.has(g)?ne(h):te(()=>new Q(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${g}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case v.TEXT_MESSAGE_END:{let g=h.messageId;return r.has(g)?(r.delete(g),ne(h)):te(()=>new Q(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${g}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case v.TOOL_CALL_START:{let g=h.toolCallId;return o.has(g)?te(()=>new Q(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${g}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(o.set(g,!0),ne(h))}case v.TOOL_CALL_ARGS:{let g=h.toolCallId;return o.has(g)?ne(h):te(()=>new Q(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${g}'. Start a tool call with 'TOOL_CALL_START' first.`))}case v.TOOL_CALL_END:{let g=h.toolCallId;return o.has(g)?(o.delete(g),ne(h)):te(()=>new Q(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${g}'. A 'TOOL_CALL_START' event must be sent first.`))}case v.STEP_STARTED:{let g=h.stepName;return l.has(g)?te(()=>new Q(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),ne(h))}case v.STEP_FINISHED:{let g=h.stepName;return l.has(g)?(l.delete(g),ne(h)):te(()=>new Q(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,ne(h);case v.RUN_FINISHED:if(l.size>0){let g=Array.from(l.keys()).join(", ");return te(()=>new Q(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(r.size>0){let g=Array.from(r.keys()).join(", ");return te(()=>new Q(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(o.size>0){let g=Array.from(o.keys()).join(", ");return te(()=>new Q(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return i=!0,ne(h);case v.RUN_ERROR:return s=!0,ne(h);case v.CUSTOM:return ne(h);case v.THINKING_TEXT_MESSAGE_START:return c?p?te(()=>new Q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(p=!0,ne(h)):te(()=>new Q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case v.THINKING_TEXT_MESSAGE_CONTENT:return p?ne(h):te(()=>new Q("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case v.THINKING_TEXT_MESSAGE_END:return p?(p=!1,ne(h)):te(()=>new Q("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case v.THINKING_START:return c?te(()=>new Q("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(c=!0,ne(h));case v.THINKING_END:return c?(c=!1,ne(h)):te(()=>new Q("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return ne(h)}}))},Zt=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),Rh=t=>co(()=>qt(t())).pipe(Es(e=>{if(!e.ok){let o=e.headers.get("content-type")||"";return qt(e.text()).pipe(Ce(i=>{let s=i;if(o.includes("application/json"))try{s=JSON.parse(i)}catch{}let a=Error(`HTTP ${e.status}: ${typeof s=="string"?s:JSON.stringify(s)}`);return a.status=e.status,a.payload=s,te(()=>a)}))}let n={type:Zt.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new ee(o=>(o.next(n),(async()=>{try{for(;;){let{done:i,value:s}=await r.read();if(i)break;let a={type:Zt.DATA,data:s};o.next(a)}o.complete()}catch(i){o.error(i)}})(),()=>{r.cancel().catch(i=>{if(i?.name!=="AbortError")throw i})})):te(()=>Error("Failed to getReader() from response"))})),Oh=(t,e)=>{let n=Jn(e),r=new rt,o=new TextDecoder("utf-8",{fatal:!1}),i="";t.subscribe({next:a=>{if(a.type!==Zt.HEADERS&&a.type===Zt.DATA&&a.data){let l=o.decode(a.data,{stream:!0});i+=l;let c=i.split(/\n\n/);i=c.pop()||"";for(let p of c)s(p)}},error:a=>r.error(a),complete:()=>{i&&(i+=o.decode(),s(i)),r.complete()}});function s(a){let l=a.split(`
|
|
9
|
-
`),c=[];for(let
|
|
10
|
-
`),m=JSON.parse(
|
|
11
|
-
`)},qh=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,c=null,p=[],m={},b=h=>{typeof h=="object"&&h&&("messages"in h&&delete h.messages,o=h)};return r.pipe(Ce(h=>{switch(h.type){case v.TEXT_MESSAGE_START:{let d=h;return[{type:Y.enum.TextMessageStart,messageId:d.messageId,role:d.role}]}case v.TEXT_MESSAGE_CONTENT:{let d=h;return[{type:Y.enum.TextMessageContent,messageId:d.messageId,content:d.delta}]}case v.TEXT_MESSAGE_END:{let d=h;return[{type:Y.enum.TextMessageEnd,messageId:d.messageId}]}case v.TOOL_CALL_START:{let d=h;return p.push({id:d.toolCallId,type:"function",function:{name:d.toolCallName,arguments:""}}),s=!0,m[d.toolCallId]=d.toolCallName,[{type:Y.enum.ActionExecutionStart,actionExecutionId:d.toolCallId,actionName:d.toolCallName,parentMessageId:d.parentMessageId}]}case v.TOOL_CALL_ARGS:{let d=h,g=p.find(S=>S.id===d.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${d.toolCallId}'`),[];g.function.arguments+=d.delta;let x=!1;if(c){let S=c.find(E=>E.tool==g.function.name);if(S)try{let E=JSON.parse(fo(g.function.arguments));S.tool_argument&&S.tool_argument in E?(b({...o,[S.state_key]:E[S.tool_argument]}),x=!0):S.tool_argument||(b({...o,[S.state_key]:E}),x=!0)}catch{}}return[{type:Y.enum.ActionExecutionArgs,actionExecutionId:d.toolCallId,args:d.delta},...x?[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]:[]]}case v.TOOL_CALL_END:{let d=h;return[{type:Y.enum.ActionExecutionEnd,actionExecutionId:d.toolCallId}]}case v.TOOL_CALL_RESULT:{let d=h;return[{type:Y.enum.ActionExecutionResult,actionExecutionId:d.toolCallId,result:d.content,actionName:m[d.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let d=h;switch(d.name){case"Exit":i=!1;break;case"PredictState":c=d.value;break}return[{type:Y.enum.MetaEvent,name:d.name,value:d.value}]}case v.STATE_SNAPSHOT:return b(h.snapshot),[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}];case v.STATE_DELTA:{let d=h,g=Fr.applyPatch(o,d.delta,!0,!1);return g?(b(g.newDocument),[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]):[]}case v.MESSAGES_SNAPSHOT:return l=h.messages,[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return l&&(o.messages=l),Object.keys(o).length===0?[]:[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:Xh(l)}:{}}),active:!1}];case v.RUN_ERROR:{let d=h;return[{type:Y.enum.RunError,message:d.message,code:d.code}]}case v.STEP_STARTED:return a=h.stepName,p=[],c=null,[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!0}];case v.STEP_FINISHED:return p=[],c=null,[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function Xh(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=Wh(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let i={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(i)}}else if(n.role==="tool"){let r="unknown";for(let i of t)if(i.role==="assistant"&&i.toolCalls?.length){for(let s of i.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var Ko=t=>e=>{let n=Jn(t),r,o,i,s,a=()=>{if(!r||s!=="text")throw Error("No text message to close");let m={type:v.TEXT_MESSAGE_END,messageId:r.messageId};return s=void 0,r=void 0,n?.event("TRANSFORM","TEXT_MESSAGE_END",m,{messageId:m.messageId}),m},l=()=>{if(!o||s!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:o.toolCallId};return s=void 0,o=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},c=()=>{if(!i||s!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:i.messageId};return s=void 0,i=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},p=()=>s==="text"?[a()]:s==="tool"?[l()]:s==="reasoning"?[c()]:[];return e.pipe(Ce(m=>{switch(m.type){case v.TEXT_MESSAGE_START:case v.TEXT_MESSAGE_CONTENT:case v.TEXT_MESSAGE_END:case v.TOOL_CALL_START:case v.TOOL_CALL_ARGS:case v.TOOL_CALL_END:case v.TOOL_CALL_RESULT:case v.STATE_SNAPSHOT:case v.STATE_DELTA:case v.MESSAGES_SNAPSHOT:case v.CUSTOM:case v.RUN_STARTED:case v.RUN_FINISHED:case v.RUN_ERROR:case v.STEP_STARTED:case v.STEP_FINISHED:case v.THINKING_START:case v.THINKING_END:case v.THINKING_TEXT_MESSAGE_START:case v.THINKING_TEXT_MESSAGE_CONTENT:case v.THINKING_TEXT_MESSAGE_END:case v.REASONING_START:case v.REASONING_MESSAGE_START:case v.REASONING_MESSAGE_CONTENT:case v.REASONING_MESSAGE_END:case v.REASONING_END:return[...p(),m];case v.RAW:case v.ACTIVITY_SNAPSHOT:case v.ACTIVITY_DELTA:case v.REASONING_ENCRYPTED_VALUE:return[m];case v.TEXT_MESSAGE_CHUNK:let b=m,h=[];if((s!=="text"||b.messageId!==void 0&&b.messageId!==r?.messageId)&&h.push(...p()),s!=="text"){if(b.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:b.messageId,name:b.name},s="text";let E={type:v.TEXT_MESSAGE_START,messageId:b.messageId,role:b.role||"assistant",...b.name!==void 0&&{name:b.name}};h.push(E),n?.event("TRANSFORM","TEXT_MESSAGE_START",E,{messageId:b.messageId})}if(b.delta!==void 0){let E={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:b.delta};h.push(E),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",E,{messageId:r.messageId})}return h;case v.TOOL_CALL_CHUNK:let d=m,g=[];if((s!=="tool"||d.toolCallId!==void 0&&d.toolCallId!==o?.toolCallId)&&g.push(...p()),s!=="tool"){if(d.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(d.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId},s="tool";let E={type:v.TOOL_CALL_START,toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId};g.push(E),n?.event("TRANSFORM","TOOL_CALL_START",E,{toolCallId:d.toolCallId,toolCallName:d.toolCallName})}if(d.delta!==void 0){let E={type:v.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:d.delta};g.push(E),n?.event("TRANSFORM","TOOL_CALL_ARGS",E,{toolCallId:o.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let x=m,S=[];if((s!=="reasoning"||x.messageId&&x.messageId!==i?.messageId)&&S.push(...p()),s!=="reasoning"){if(x.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");i={messageId:x.messageId},s="reasoning";let E={type:v.REASONING_MESSAGE_START,messageId:x.messageId};S.push(E),n?.event("TRANSFORM","REASONING_MESSAGE_START",E,{messageId:x.messageId})}if(x.delta!==void 0){let E={type:v.REASONING_MESSAGE_CONTENT,messageId:i.messageId,delta:x.delta};S.push(E),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",E,{messageId:i.messageId})}return S}return m.type,[]}),Kt(()=>{p()}))};function Kh(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function Dc(t,e){let n=new Set(t.map(s=>s.id)),r=new Set(Object.keys(e)),o=[...n].filter(s=>!r.has(s));if(o.length>0)throw Error(`buildResumeArray: missing responses for open interrupts: ${o.join(", ")}`);let i=[...r].filter(s=>!n.has(s));if(i.length>0)throw Error(`buildResumeArray: responses reference unknown interrupt ids: ${i.join(", ")}`);return t.map(s=>{let a=e[s.id];if(a.status==="resolved"){let l={interruptId:s.id,status:"resolved"};return a.payload!==void 0&&(l.payload=a.payload),l}return{interruptId:s.id,status:"cancelled"}})}var Zo=class{runNext(t,e){return e.run(t).pipe(Ko(!1))}runNextWithState(t,e){let n=V(t.messages||[]),r=V(t.state||{}),o=new Xr;return Pc(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(uo(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:V(n),state:V(r)})))}},Zh=class extends Zo{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function Yh(t){let e=t.content;if(Array.isArray(e)){let n=e.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...t,content:n}}return typeof e=="string"?t:{...t,content:""}}var Jh=class extends Zo{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(Yh)};return this.runNext(o,e)}},Nc="THINKING_START",Rc="THINKING_END",Oc="THINKING_TEXT_MESSAGE_START",Mc="THINKING_TEXT_MESSAGE_CONTENT",Lc="THINKING_TEXT_MESSAGE_END",Qh=class extends Zo{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(Xt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Nc:{this.currentReasoningId=Oe();let{title:e,...n}=t;return this.warnAboutTransformation(Nc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case Oc:return this.currentMessageId=Oe(),this.warnAboutTransformation(Oc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Mc:{let{delta:e,...n}=t;return this.warnAboutTransformation(Mc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Oe(),delta:e}}case Lc:{let e=this.currentMessageId??Oe();return this.warnAboutTransformation(Lc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case Rc:{let e=this.currentReasoningId??Oe();return this.warnAboutTransformation(Rc,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function em(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function tm(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function nm(t){let e=em(t.mimeType);return t.data?{type:e,source:{type:"data",value:t.data,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t.url?{type:e,source:{type:"url",value:t.url,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t}function rm(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>tm(r)?nm(r):r);return{...t,content:n}}var om=class extends Zo{run(t,e){let n={...t,messages:t.messages.map(rm)};return this.runNext(n,e)}},im="0.0.57",sm=class{get maxVersion(){return im}get debug(){return this._debug}set debug(t){this._debug=Xo(t),this._debugLogger=Us(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?Us(Xo(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:i}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??bt(),this.messages=V(r??[]),this.state=V(o??{}),this._debug=Xo(i),this._debugLogger=Us(this._debug),Yn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new Jh),Yn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new Qh),Yn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new om)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(n=>typeof n=="function"?new Zh(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??bt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new rt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await lo(qr(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:p=>c.run(p,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),Ko(this.debugLogger),Hs(this.debugLogger),l=>l.pipe(po(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),Xn(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,i))),Kt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(ne(null)));let a=V(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new ss}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??bt();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new rt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await lo(qr(()=>co(()=>this.connect(n)),Ko(this.debugLogger),Hs(this.debugLogger),l=>l.pipe(po(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),Xn(l=>(this.isRunning=!1,l instanceof ss?Kr:this.onError(n,l,i))),Kt(()=>{this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(ne(null)),{defaultValue:void 0});let a=V(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return Pc(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(Ts(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=V(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:t?.runId||bt(),tools:V(t?.tools??[]),context:V(t?.context??[]),forwardedProps:V(t?.forwardedProps??{}),state:V(this.state),messages:e,...t?.resume===void 0?{}:{resume:V(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(i=>i.interruptId)),o=this.pendingInterrupts.map(i=>i.id).filter(i=>!r.has(i));if(o.length>0)throw new Q(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let i of this.pendingInterrupts)if(Kh(i))throw new Q(`Interrupt ${i.id} expired at ${i.expiresAt}`)}let n=await K(e,this.messages,this.state,(r,o,i)=>r.onRunInitialized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}onError(t,e,n){return qt(K(n,this.messages,this.state,(r,o,i)=>r.onRunFailed?.({error:e,messages:o,state:i,agent:this,input:t}))).pipe(Xt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let i=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||i==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await K(e,this.messages,this.state,(r,o,i)=>r.onRunFinalized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=V(this.messages),t.state=V(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=V(this.pendingInterrupts),t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let n of this.subscribers)await n.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let n of e.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=V(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=V(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??bt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Ko(this.debugLogger),Hs(this.debugLogger),qh(this.threadId,e.runId,this.agentId),n=>n.pipe(Xt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},Uc=class extends sm{requestInit(t){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t,e){return this.abortController=t?.abortController??new AbortController,super.runAgent(t,e)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(t){super(t),this.abortController=new AbortController,this.url=t.url,this.headers=V(t.headers??{}),this.fetch=t.fetch??((e,n)=>fetch(e,n))}run(t){return Lh(Rh(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=V(this.headers??{}),t.fetch=this.fetch;let e=new AbortController,n=this.abortController.signal;return n.aborted&&e.abort(n.reason),t.abortController=e,t}};var Yo=class{element;#n;#e;#t=[];constructor(e){this.#n=e,this.#e=e.strings??re,this.element=document.createElement("div"),this.element.className="attachment-tray",this.element.setAttribute("part","attachment-tray"),this.element.hidden=!0}add(e){let n={localId:Oe(),file:e,status:Le.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#t.push(n);let r=this.#i(e);if(r!==null){n.status=Le.ERROR,n.error=r,this.#s(),this.#n.onChange?.();return}this.#s(),this.#n.onChange?.(),this.#r(n)}readyRefs(){let e=[];for(let n of this.#t)n.ref!==null&&e.push(n.ref);return e}hasPending(){return this.#t.some(e=>e.status===Le.UPLOADING)}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===Le.UPLOADING),this.#s()}clear(){for(let e of this.#t)e.controller?.abort();this.#t=[],this.#s()}dispose(){for(let e of this.#t)e.controller?.abort()}#i(e){return this.#n.maxBytes>0&&e.size>this.#n.maxBytes?this.#e.tooLarge.replace("{size}",wr(this.#n.maxBytes)):am(this.#n.accept,e)?null:this.#e.fileTypeNotAllowed}#r(e){let n=this.#i(e.file);if(n!==null){e.status=Le.ERROR,e.error=n,this.#s(),this.#n.onChange?.();return}e.status=Le.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#s(),this.#n.upload(e.file,o=>{e.progress=o,this.#s()},r.signal).then(o=>{e.status=Le.READY,e.ref=o}).catch(o=>{e.status=Le.ERROR,e.error=o instanceof Error?o.message:this.#e.uploadFailed}).finally(()=>{e.controller=null,this.#s(),this.#n.onChange?.()})}#a(e){e.controller?.abort(),this.#t=this.#t.filter(n=>n!==e),this.#s(),this.#n.onChange?.()}#s(){this.element.replaceChildren(),this.element.hidden=this.#t.length===0;for(let e of this.#t)this.element.appendChild(this.#o(e))}#o(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`,n.setAttribute("part","attachment-chip");let r=document.createElement("span");r.className="attachment-chip-icon",r.setAttribute("part","attachment-chip-icon"),r.textContent=Qi(e.file.type),r.setAttribute("aria-hidden","true");let o=document.createElement("span");o.className="attachment-chip-name",o.setAttribute("part","attachment-chip-name"),o.textContent=e.file.name,o.title=e.file.name;let i=document.createElement("span");if(i.className="attachment-chip-size",i.setAttribute("part","attachment-chip-size"),i.textContent=e.status===Le.ERROR?e.error:wr(e.file.size),n.append(r,o,i),e.status===Le.UPLOADING){let a=document.createElement("div");a.className="attachment-chip-bar",a.setAttribute("part","attachment-chip-bar");let l=document.createElement("div");l.className="attachment-chip-bar-fill",l.setAttribute("part","attachment-chip-bar-fill"),l.style.width=`${Math.round(e.progress*100)}%`,a.appendChild(l),n.appendChild(a)}if(e.status===Le.ERROR){let a=document.createElement("button");a.type="button",a.className="attachment-chip-retry",a.setAttribute("part","attachment-chip-retry"),a.title=this.#e.retry,a.setAttribute("aria-label",this.#e.retryUpload),a.textContent="\u21BB",a.addEventListener("click",()=>this.#r(e)),n.appendChild(a)}let s=document.createElement("button");return s.type="button",s.className="attachment-chip-remove",s.setAttribute("part","attachment-chip-remove"),s.title=this.#e.remove,s.setAttribute("aria-label",this.#e.removeAttachment),s.textContent="\u2715",s.addEventListener("click",()=>this.#a(e)),n.appendChild(s),n}};function am(t,e){let n=t.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return n.some(i=>i.startsWith(".")?o.endsWith(i):i.endsWith("/*")?r.startsWith(i.slice(0,-1)):r===i)}function Hc(t,e){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${t}`,n.setAttribute("part",`confirm-button confirm-${t}`),n.textContent=e,n}function $s(t,e,n={}){let r=n.strings??re;return new Promise(o=>{let i=document.createElement("div");i.className="confirm",i.setAttribute("part","confirm"),i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.confirmAction);let s=document.createElement("div");s.className="confirm-body",s.setAttribute("part","confirm-body"),s.textContent=e.message??r.confirmRun.replace("{tool}",e.toolName);let a=document.createElement("pre");a.className="confirm-args",a.setAttribute("part","confirm-args"),a.textContent=JSON.stringify(e.args,null,2);let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let c=Hc("cancel",r.cancel),p=Hc("confirm",r.confirm),m=!1,b=h=>{m||(m=!0,c.disabled=!0,p.disabled=!0,i.setAttribute("data-resolved",h?"confirmed":"declined"),o(h))};if(c.addEventListener("click",()=>b(!1)),p.addEventListener("click",()=>b(!0)),n.signal?.addEventListener("abort",()=>b(!1),{once:!0}),l.append(c,p),i.append(s,a,l),t.appendChild(i),n.signal?.aborted===!0){b(!1);return}p.focus()})}function zs(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function lm(t){let e=document.createElement("input");return e.type="text",e.className="question-input",e.setAttribute("part","question-input"),e.placeholder=t,e}function Bs(t,e,n={}){let r=n.strings??re,o=e.options??[],i=o.length>0,s=!i||e.allowCustom===!0;return new Promise(a=>{let l=document.createElement("div");l.className="question",l.setAttribute("part","question"),l.setAttribute("role","group"),l.setAttribute("aria-label",r.askUserAction);let c=document.createElement("div");c.className="question-body",c.setAttribute("part","question-body"),c.textContent=e.question;let p=document.createElement("div");p.className="question-options",p.setAttribute("part","question-options");let m=`q-${o.length}-${e.question.length}`,b=[];for(let P of o){let U=document.createElement("label");U.className="question-choice",U.setAttribute("part","question-choice");let we=document.createElement("input");we.type="radio",we.name=m,we.value=P,we.setAttribute("part","question-radio");let mt=document.createElement("span");mt.setAttribute("part","question-choice-text"),mt.textContent=P,U.append(we,mt),p.appendChild(U),b.push(we)}let h=null,d=null;if(s){if(d=lm(r.answerPlaceholder),i){let P=document.createElement("label");P.className="question-choice",P.setAttribute("part","question-choice"),h=document.createElement("input"),h.type="radio",h.name=m,h.value="",h.setAttribute("part","question-radio");let U=document.createElement("span");U.setAttribute("part","question-choice-text"),U.textContent=r.otherOption,P.append(h,U),p.appendChild(P),d.disabled=!0}p.appendChild(d)}let g=document.createElement("div");g.className="question-actions",g.setAttribute("part","question-actions");let x=document.createElement("button");x.type="button",x.className="question-btn",x.setAttribute("part","question-button"),x.textContent=r.submit,g.appendChild(x);let S=!1,E=()=>{let P=b.find(U=>U.checked);if(P!==void 0)return P.value;if(d!==null&&(h===null||h.checked)){let U=d.value.trim();return U===""?null:U}return null},I=()=>{d!==null&&h!==null&&(d.disabled=!h.checked),x.disabled=E()===null},D=P=>{if(!S){S=!0,x.disabled=!0;for(let U of b)U.disabled=!0;h!==null&&(h.disabled=!0),d!==null&&(d.disabled=!0),l.setAttribute("data-resolved",P===""?"cancelled":"answered"),a(P)}};for(let P of[...b,...h!==null?[h]:[]])P.addEventListener("change",I);if(d?.addEventListener("input",I),d?.addEventListener("keydown",P=>{if(P.key==="Enter"){P.preventDefault();let U=E();U!==null&&D(U)}}),x.addEventListener("click",()=>{let P=E();P!==null&&D(P)}),n.signal?.addEventListener("abort",()=>D(""),{once:!0}),l.append(c,p,g),t.appendChild(l),n.signal?.aborted===!0){D("");return}I(),(i?b[0]:d)?.focus()})}function Gc(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function cm(t){if(Array.isArray(t))return t}function um(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,i,s,a=[],l=!0,c=!1;try{if(i=(n=n.call(t)).next,e!==0)for(;!(l=(r=i.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(p){c=!0,o=p}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw o}}return a}}function dm(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
12
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pm(t,e){return cm(t)||um(t,e)||fm(t,e)||dm()}function fm(t,e){if(t){if(typeof t=="string")return Gc(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Gc(t,e):void 0}}var Jc=Object.entries,Fc=Object.setPrototypeOf,hm=Object.isFrozen,mm=Object.getPrototypeOf,gm=Object.getOwnPropertyDescriptor,Ae=Object.freeze,Ge=Object.seal,An=Object.create,Qc=typeof Reflect<"u"&&Reflect,Ks=Qc.apply,Zs=Qc.construct;Ae||(Ae=function(e){return e});Ge||(Ge=function(e){return e});Ks||(Ks=function(e,n){for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];return e.apply(n,o)});Zs||(Zs=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return new e(...r)});var Sn=pe(Array.prototype.forEach),vm=pe(Array.prototype.lastIndexOf),$c=pe(Array.prototype.pop),wn=pe(Array.prototype.push),bm=pe(Array.prototype.splice),_e=Array.isArray,tr=pe(String.prototype.toLowerCase),js=pe(String.prototype.toString),zc=pe(String.prototype.match),_n=pe(String.prototype.replace),Bc=pe(String.prototype.indexOf),ym=pe(String.prototype.trim),xm=pe(Number.prototype.toString),Em=pe(Boolean.prototype.toString),jc=typeof BigInt>"u"?null:pe(BigInt.prototype.toString),Vc=typeof Symbol>"u"?null:pe(Symbol.prototype.toString),ie=pe(Object.prototype.hasOwnProperty),Qn=pe(Object.prototype.toString),xe=pe(RegExp.prototype.test),er=Tm(TypeError);function pe(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return Ks(t,e,r)}}function Tm(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return Zs(t,n)}}function F(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:tr;if(Fc&&Fc(t,null),!_e(e))return t;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let i=n(o);i!==o&&(hm(e)||(e[r]=i),o=i)}t[o]=!0}return t}function Sm(t){for(let e=0;e<t.length;e++)ie(t,e)||(t[e]=null);return t}function Te(t){let e=An(null);for(let r of Jc(t)){var n=pm(r,2);let o=n[0],i=n[1];ie(t,o)&&(_e(i)?e[o]=Sm(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=Te(i):e[o]=i)}return e}function wm(t){switch(typeof t){case"string":return t;case"number":return xm(t);case"boolean":return Em(t);case"bigint":return jc?jc(t):"0";case"symbol":return Vc?Vc(t):"Symbol()";case"undefined":return Qn(t);case"function":case"object":{if(t===null)return Qn(t);let e=t,n=it(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:Qn(r)}return Qn(t)}default:return Qn(t)}}function it(t,e){for(;t!==null;){let r=gm(t,e);if(r){if(r.get)return pe(r.get);if(typeof r.value=="function")return pe(r.value)}t=mm(t)}function n(){return null}return n}function _m(t){try{return xe(t,""),!0}catch{return!1}}var Wc=Ae(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Vs=Ae(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Ws=Ae(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Am=Ae(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),qs=Ae(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),km=Ae(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),qc=Ae(["#text"]),Xc=Ae(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Xs=Ae(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Kc=Ae(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Jo=Ae(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Im=Ge(/{{[\w\W]*|^[\w\W]*}}/g),Cm=Ge(/<%[\w\W]*|^[\w\W]*%>/g),Nm=Ge(/\${[\w\W]*/g),Rm=Ge(/^data-[\-\w.\u00B7-\uFFFF]+$/),Om=Ge(/^aria-[\-\w]+$/),Zc=Ge(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Mm=Ge(/^(?:\w+script|data):/i),Lm=Ge(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Pm=Ge(/^html$/i),Dm=Ge(/^[a-z][.\w]*(-[.\w]+)+$/i),ot={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Um=function(){return typeof window>"u"?null:window},Hm=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Yc=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function eu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Um(),e=N=>eu(N);if(e.version="3.4.7",e.removed=[],!t||!t.document||t.document.nodeType!==ot.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,o=r.currentScript;t.DocumentFragment;let i=t.HTMLTemplateElement,s=t.Node,a=t.Element,l=t.NodeFilter,c=t.NamedNodeMap;c===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let p=t.DOMParser,m=t.trustedTypes,b=a.prototype,h=it(b,"cloneNode"),d=it(b,"remove"),g=it(b,"nextSibling"),x=it(b,"childNodes"),S=it(b,"parentNode"),E=it(b,"shadowRoot"),I=it(b,"attributes"),D=s&&s.prototype?it(s.prototype,"nodeType"):null,P=s&&s.prototype?it(s.prototype,"nodeName"):null;if(typeof i=="function"){let N=n.createElement("template");N.content&&N.content.ownerDocument&&(n=N.content.ownerDocument)}let U,we="",mt=n,fi=mt.implementation,ga=mt.createNodeIterator,Ru=mt.createDocumentFragment,Ou=mt.getElementsByTagName,Mu=r.importNode,fe=Yc();e.isSupported=typeof Jc=="function"&&typeof S=="function"&&fi&&fi.createHTMLDocument!==void 0;let ur=Im,dr=Cm,pr=Nm,Lu=Rm,Pu=Om,Du=Mm,va=Lm,Uu=Dm,ba=Zc,se=null,hi=F({},[...Wc,...Vs,...Ws,...qs,...qc]),ue=null,mi=F({},[...Xc,...Xs,...Kc,...Jo]),ae=Object.seal(An(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Cn=null,fr=null,gt=Object.seal(An(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ya=!0,gi=!0,xa=!1,Ea=!0,vt=!1,Nn=!0,_t=!1,vi=!1,bi=!1,en=!1,hr=!1,mr=!1,Ta=!0,Sa=!1,wa="user-content-",yi=!0,Rn=!1,tn={},Xe=null,xi=F({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),_a=null,Aa=F({},["audio","video","img","source","image","track"]),Ei=null,ka=F({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),gr="http://www.w3.org/1998/Math/MathML",vr="http://www.w3.org/2000/svg",Ke="http://www.w3.org/1999/xhtml",nn=Ke,Ti=!1,Si=null,Hu=F({},[gr,vr,Ke],js),wi=F({},["mi","mo","mn","ms","mtext"]),_i=F({},["annotation-xml"]),Gu=F({},["title","style","font","a","script"]),On=null,Fu=["application/xhtml+xml","text/html"],$u="text/html",le=null,rn=null,zu=n.createElement("form"),Ia=function(f){return f instanceof RegExp||f instanceof Function},Ai=function(){let f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(rn&&rn===f)return;(!f||typeof f!="object")&&(f={}),f=Te(f),On=Fu.indexOf(f.PARSER_MEDIA_TYPE)===-1?$u:f.PARSER_MEDIA_TYPE,le=On==="application/xhtml+xml"?js:tr,se=ie(f,"ALLOWED_TAGS")&&_e(f.ALLOWED_TAGS)?F({},f.ALLOWED_TAGS,le):hi,ue=ie(f,"ALLOWED_ATTR")&&_e(f.ALLOWED_ATTR)?F({},f.ALLOWED_ATTR,le):mi,Si=ie(f,"ALLOWED_NAMESPACES")&&_e(f.ALLOWED_NAMESPACES)?F({},f.ALLOWED_NAMESPACES,js):Hu,Ei=ie(f,"ADD_URI_SAFE_ATTR")&&_e(f.ADD_URI_SAFE_ATTR)?F(Te(ka),f.ADD_URI_SAFE_ATTR,le):ka,_a=ie(f,"ADD_DATA_URI_TAGS")&&_e(f.ADD_DATA_URI_TAGS)?F(Te(Aa),f.ADD_DATA_URI_TAGS,le):Aa,Xe=ie(f,"FORBID_CONTENTS")&&_e(f.FORBID_CONTENTS)?F({},f.FORBID_CONTENTS,le):xi,Cn=ie(f,"FORBID_TAGS")&&_e(f.FORBID_TAGS)?F({},f.FORBID_TAGS,le):Te({}),fr=ie(f,"FORBID_ATTR")&&_e(f.FORBID_ATTR)?F({},f.FORBID_ATTR,le):Te({}),tn=ie(f,"USE_PROFILES")?f.USE_PROFILES&&typeof f.USE_PROFILES=="object"?Te(f.USE_PROFILES):f.USE_PROFILES:!1,ya=f.ALLOW_ARIA_ATTR!==!1,gi=f.ALLOW_DATA_ATTR!==!1,xa=f.ALLOW_UNKNOWN_PROTOCOLS||!1,Ea=f.ALLOW_SELF_CLOSE_IN_ATTR!==!1,vt=f.SAFE_FOR_TEMPLATES||!1,Nn=f.SAFE_FOR_XML!==!1,_t=f.WHOLE_DOCUMENT||!1,en=f.RETURN_DOM||!1,hr=f.RETURN_DOM_FRAGMENT||!1,mr=f.RETURN_TRUSTED_TYPE||!1,bi=f.FORCE_BODY||!1,Ta=f.SANITIZE_DOM!==!1,Sa=f.SANITIZE_NAMED_PROPS||!1,yi=f.KEEP_CONTENT!==!1,Rn=f.IN_PLACE||!1,ba=_m(f.ALLOWED_URI_REGEXP)?f.ALLOWED_URI_REGEXP:Zc,nn=typeof f.NAMESPACE=="string"?f.NAMESPACE:Ke,wi=ie(f,"MATHML_TEXT_INTEGRATION_POINTS")&&f.MATHML_TEXT_INTEGRATION_POINTS&&typeof f.MATHML_TEXT_INTEGRATION_POINTS=="object"?Te(f.MATHML_TEXT_INTEGRATION_POINTS):F({},["mi","mo","mn","ms","mtext"]),_i=ie(f,"HTML_INTEGRATION_POINTS")&&f.HTML_INTEGRATION_POINTS&&typeof f.HTML_INTEGRATION_POINTS=="object"?Te(f.HTML_INTEGRATION_POINTS):F({},["annotation-xml"]);let y=ie(f,"CUSTOM_ELEMENT_HANDLING")&&f.CUSTOM_ELEMENT_HANDLING&&typeof f.CUSTOM_ELEMENT_HANDLING=="object"?Te(f.CUSTOM_ELEMENT_HANDLING):An(null);if(ae=An(null),ie(y,"tagNameCheck")&&Ia(y.tagNameCheck)&&(ae.tagNameCheck=y.tagNameCheck),ie(y,"attributeNameCheck")&&Ia(y.attributeNameCheck)&&(ae.attributeNameCheck=y.attributeNameCheck),ie(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(ae.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),vt&&(gi=!1),hr&&(en=!0),tn&&(se=F({},qc),ue=An(null),tn.html===!0&&(F(se,Wc),F(ue,Xc)),tn.svg===!0&&(F(se,Vs),F(ue,Xs),F(ue,Jo)),tn.svgFilters===!0&&(F(se,Ws),F(ue,Xs),F(ue,Jo)),tn.mathMl===!0&&(F(se,qs),F(ue,Kc),F(ue,Jo))),gt.tagCheck=null,gt.attributeCheck=null,ie(f,"ADD_TAGS")&&(typeof f.ADD_TAGS=="function"?gt.tagCheck=f.ADD_TAGS:_e(f.ADD_TAGS)&&(se===hi&&(se=Te(se)),F(se,f.ADD_TAGS,le))),ie(f,"ADD_ATTR")&&(typeof f.ADD_ATTR=="function"?gt.attributeCheck=f.ADD_ATTR:_e(f.ADD_ATTR)&&(ue===mi&&(ue=Te(ue)),F(ue,f.ADD_ATTR,le))),ie(f,"ADD_URI_SAFE_ATTR")&&_e(f.ADD_URI_SAFE_ATTR)&&F(Ei,f.ADD_URI_SAFE_ATTR,le),ie(f,"FORBID_CONTENTS")&&_e(f.FORBID_CONTENTS)&&(Xe===xi&&(Xe=Te(Xe)),F(Xe,f.FORBID_CONTENTS,le)),ie(f,"ADD_FORBID_CONTENTS")&&_e(f.ADD_FORBID_CONTENTS)&&(Xe===xi&&(Xe=Te(Xe)),F(Xe,f.ADD_FORBID_CONTENTS,le)),yi&&(se["#text"]=!0),_t&&F(se,["html","head","body"]),se.table&&(F(se,["tbody"]),delete Cn.tbody),f.TRUSTED_TYPES_POLICY){if(typeof f.TRUSTED_TYPES_POLICY.createHTML!="function")throw er('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof f.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw er('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');U=f.TRUSTED_TYPES_POLICY,we=U.createHTML("")}else U===void 0&&(U=Hm(m,o)),U!==null&&typeof we=="string"&&(we=U.createHTML(""));(fe.uponSanitizeElement.length>0||fe.uponSanitizeAttribute.length>0)&&se===hi&&(se=Te(se)),fe.uponSanitizeAttribute.length>0&&ue===mi&&(ue=Te(ue)),Ae&&Ae(f),rn=f},Ca=F({},[...Vs,...Ws,...Am]),Na=F({},[...qs,...km]),Bu=function(f){let y=S(f);(!y||!y.tagName)&&(y={namespaceURI:nn,tagName:"template"});let A=tr(f.tagName),X=tr(y.tagName);return Si[f.namespaceURI]?f.namespaceURI===vr?y.namespaceURI===Ke?A==="svg":y.namespaceURI===gr?A==="svg"&&(X==="annotation-xml"||wi[X]):!!Ca[A]:f.namespaceURI===gr?y.namespaceURI===Ke?A==="math":y.namespaceURI===vr?A==="math"&&_i[X]:!!Na[A]:f.namespaceURI===Ke?y.namespaceURI===vr&&!_i[X]||y.namespaceURI===gr&&!wi[X]?!1:!Na[A]&&(Gu[A]||!Ca[A]):!!(On==="application/xhtml+xml"&&Si[f.namespaceURI]):!1},Fe=function(f){wn(e.removed,{element:f});try{S(f).removeChild(f)}catch{d(f)}},At=function(f,y){try{wn(e.removed,{attribute:y.getAttributeNode(f),from:y})}catch{wn(e.removed,{attribute:null,from:y})}if(y.removeAttribute(f),f==="is")if(en||hr)try{Fe(y)}catch{}else try{y.setAttribute(f,"")}catch{}},Ra=function(f){let y=null,A=null;if(bi)f="<remove></remove>"+f;else{let J=zc(f,/^[\r\n\t ]+/);A=J&&J[0]}On==="application/xhtml+xml"&&nn===Ke&&(f='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+f+"</body></html>");let X=U?U.createHTML(f):f;if(nn===Ke)try{y=new p().parseFromString(X,On)}catch{}if(!y||!y.documentElement){y=fi.createDocument(nn,"template",null);try{y.documentElement.innerHTML=Ti?we:X}catch{}}let j=y.body||y.documentElement;return f&&A&&j.insertBefore(n.createTextNode(A),j.childNodes[0]||null),nn===Ke?Ou.call(y,_t?"html":"body")[0]:_t?y.documentElement:j},Oa=function(f){return ga.call(f.ownerDocument||f,f,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ma=function(f){f.normalize();let y=ga.call(f.ownerDocument||f,f,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),A=y.nextNode();for(;A;){let X=A.data;Sn([ur,dr,pr],j=>{X=_n(X,j," ")}),A.data=X,A=y.nextNode()}},br=function(f){let y=P?P(f):null;return typeof y!="string"||le(y)!=="form"?!1:typeof f.nodeName!="string"||typeof f.textContent!="string"||typeof f.removeChild!="function"||f.attributes!==I(f)||typeof f.removeAttribute!="function"||typeof f.setAttribute!="function"||typeof f.namespaceURI!="string"||typeof f.insertBefore!="function"||typeof f.hasChildNodes!="function"||f.nodeType!==D(f)||f.childNodes!==x(f)},Mn=function(f){if(!D||typeof f!="object"||f===null)return!1;try{return D(f)===ot.documentFragment}catch{return!1}},yr=function(f){if(!D||typeof f!="object"||f===null)return!1;try{return typeof D(f)=="number"}catch{return!1}};function at(N,f,y){Sn(N,A=>{A.call(e,f,y,rn)})}let La=function(f){let y=null;if(at(fe.beforeSanitizeElements,f,null),br(f))return Fe(f),!0;let A=le(f.nodeName);if(at(fe.uponSanitizeElement,f,{tagName:A,allowedTags:se}),Nn&&f.hasChildNodes()&&!yr(f.firstElementChild)&&xe(/<[/\w!]/g,f.innerHTML)&&xe(/<[/\w!]/g,f.textContent)||Nn&&f.namespaceURI===Ke&&A==="style"&&yr(f.firstElementChild)||f.nodeType===ot.progressingInstruction||Nn&&f.nodeType===ot.comment&&xe(/<[/\w]/g,f.data))return Fe(f),!0;if(Cn[A]||!(gt.tagCheck instanceof Function&>.tagCheck(A))&&!se[A]){if(!Cn[A]&&Da(A)&&(ae.tagNameCheck instanceof RegExp&&xe(ae.tagNameCheck,A)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(A)))return!1;if(yi&&!Xe[A]){let j=S(f),J=x(f);if(J&&j){let Me=J.length;for(let Ze=Me-1;Ze>=0;--Ze){let $e=h(J[Ze],!0);j.insertBefore($e,g(f))}}}return Fe(f),!0}return(D?D(f):f.nodeType)===ot.element&&!Bu(f)||(A==="noscript"||A==="noembed"||A==="noframes")&&xe(/<\/no(script|embed|frames)/i,f.innerHTML)?(Fe(f),!0):(vt&&f.nodeType===ot.text&&(y=f.textContent,Sn([ur,dr,pr],j=>{y=_n(y,j," ")}),f.textContent!==y&&(wn(e.removed,{element:f.cloneNode()}),f.textContent=y)),at(fe.afterSanitizeElements,f,null),!1)},Pa=function(f,y,A){if(fr[y]||Ta&&(y==="id"||y==="name")&&(A in n||A in zu))return!1;let X=ue[y]||gt.attributeCheck instanceof Function&>.attributeCheck(y,f);if(!(gi&&!fr[y]&&xe(Lu,y))){if(!(ya&&xe(Pu,y))){if(!X||fr[y]){if(!(Da(f)&&(ae.tagNameCheck instanceof RegExp&&xe(ae.tagNameCheck,f)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(f))&&(ae.attributeNameCheck instanceof RegExp&&xe(ae.attributeNameCheck,y)||ae.attributeNameCheck instanceof Function&&ae.attributeNameCheck(y,f))||y==="is"&&ae.allowCustomizedBuiltInElements&&(ae.tagNameCheck instanceof RegExp&&xe(ae.tagNameCheck,A)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(A))))return!1}else if(!Ei[y]){if(!xe(ba,_n(A,va,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&f!=="script"&&Bc(A,"data:")===0&&_a[f])){if(!(xa&&!xe(Du,_n(A,va,"")))){if(A)return!1}}}}}}return!0},ju=F({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Da=function(f){return!ju[tr(f)]&&xe(Uu,f)},Ua=function(f){at(fe.beforeSanitizeAttributes,f,null);let y=f.attributes;if(!y||br(f))return;let A={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ue,forceKeepAttr:void 0},X=y.length;for(;X--;){let j=y[X],J=j.name,Me=j.namespaceURI,Ze=j.value,$e=le(J),ki=Ze,he=J==="value"?ki:ym(ki);if(A.attrName=$e,A.attrValue=he,A.keepAttr=!0,A.forceKeepAttr=void 0,at(fe.uponSanitizeAttribute,f,A),he=A.attrValue,Sa&&($e==="id"||$e==="name")&&Bc(he,wa)!==0&&(At(J,f),he=wa+he),Nn&&xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,he)){At(J,f);continue}if($e==="attributename"&&zc(he,"href")){At(J,f);continue}if(A.forceKeepAttr)continue;if(!A.keepAttr){At(J,f);continue}if(!Ea&&xe(/\/>/i,he)){At(J,f);continue}vt&&Sn([ur,dr,pr],Ga=>{he=_n(he,Ga," ")});let Ha=le(f.nodeName);if(!Pa(Ha,$e,he)){At(J,f);continue}if(U&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Me)switch(m.getAttributeType(Ha,$e)){case"TrustedHTML":{he=U.createHTML(he);break}case"TrustedScriptURL":{he=U.createScriptURL(he);break}}if(he!==ki)try{Me?f.setAttributeNS(Me,J,he):f.setAttribute(J,he),br(f)?Fe(f):$c(e.removed)}catch{At(J,f)}}at(fe.afterSanitizeAttributes,f,null)},xr=function(f){let y=null,A=Oa(f);for(at(fe.beforeSanitizeShadowDOM,f,null);y=A.nextNode();)if(at(fe.uponSanitizeShadowNode,y,null),La(y),Ua(y),Mn(y.content)&&xr(y.content),(D?D(y):y.nodeType)===ot.element){let j=E?E(y):y.shadowRoot;Mn(j)&&(on(j),xr(j))}at(fe.afterSanitizeShadowDOM,f,null)},on=function(f){let y=D?D(f):f.nodeType;if(y===ot.element){let j=E?E(f):f.shadowRoot;Mn(j)&&(on(j),xr(j))}let A=x?x(f):f.childNodes;if(!A)return;let X=[];Sn(A,j=>{wn(X,j)});for(let j of X)on(j);if(y===ot.element){let j=P?P(f):null;if(typeof j=="string"&&le(j)==="template"){let J=f.content;Mn(J)&&on(J)}}};return e.sanitize=function(N){let f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,A=null,X=null,j=null;if(Ti=!N,Ti&&(N="<!-->"),typeof N!="string"&&!yr(N)&&(N=wm(N),typeof N!="string"))throw er("dirty is not a string, aborting");if(!e.isSupported)return N;if(vi||Ai(f),e.removed=[],typeof N=="string"&&(Rn=!1),Rn){let Ze=P?P(N):N.nodeName;if(typeof Ze=="string"){let $e=le(Ze);if(!se[$e]||Cn[$e])throw er("root node is forbidden and cannot be sanitized in-place")}if(br(N))throw er("root node is clobbered and cannot be sanitized in-place");on(N)}else if(yr(N))y=Ra("<!---->"),A=y.ownerDocument.importNode(N,!0),A.nodeType===ot.element&&A.nodeName==="BODY"||A.nodeName==="HTML"?y=A:y.appendChild(A),on(A);else{if(!en&&!vt&&!_t&&N.indexOf("<")===-1)return U&&mr?U.createHTML(N):N;if(y=Ra(N),!y)return en?null:mr?we:""}y&&bi&&Fe(y.firstChild);let J=Oa(Rn?N:y);for(;X=J.nextNode();)La(X),Ua(X),Mn(X.content)&&xr(X.content);if(Rn)return vt&&Ma(N),N;if(en){if(vt&&Ma(y),hr)for(j=Ru.call(y.ownerDocument);y.firstChild;)j.appendChild(y.firstChild);else j=y;return(ue.shadowroot||ue.shadowrootmode)&&(j=Mu.call(r,j,!0)),j}let Me=_t?y.outerHTML:y.innerHTML;return _t&&se["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&xe(Pm,y.ownerDocument.doctype.name)&&(Me="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
|
|
13
|
-
`+Me),vt&&Sn([
|
|
14
|
-
]`).replace("lheading",
|
|
8
|
+
Error: ${x}`)}}return f()}case v.MESSAGES_SNAPSHOT:{let h=await K(r,s,a,(d,g,x)=>d.onMessagesSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messages:d}=m,g=new Map(d.map(I=>[I.id,I])),x=d.some(I=>I.role==="reasoning"),S=I=>I.role==="activity"||I.role==="reasoning"&&!x;s=s.filter(I=>S(I)||g.has(I.id)).map(I=>S(I)?I:g.get(I.id));let E=new Set(s.map(I=>I.id));for(let I of d)E.has(I.id)||s.push(I);c({messages:s})}return f()}case v.ACTIVITY_SNAPSHOT:{let h=m,d=s.findIndex(I=>I.id===h.messageId),g=d>=0?s[d]:void 0,x=g?.role==="activity"?g:void 0,S=h.replace??!0,E=await K(r,s,a,(I,D,P)=>I.onActivitySnapshotEvent?.({event:h,messages:D,state:P,agent:n,input:t,activityMessage:x,existingMessage:g}));if(c(E),E.stopPropagation!==!0){let I={id:h.messageId,role:"activity",activityType:h.activityType,content:j(h.content)},D;d===-1?(s.push(I),D=I):x?S&&(s[d]={...x,activityType:h.activityType,content:j(h.content)}):S&&(s[d]=I,D=I),c({messages:s}),D&&await Promise.all(r.map(P=>P.onNewMessage?.({message:D,messages:s,state:a,agent:n,input:t})))}return f()}case v.ACTIVITY_DELTA:{let h=m,d=s.findIndex(E=>E.id===h.messageId);if(d===-1)return f();let g=s[d];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${h.messageId}' is not an activity message`),f();let x=g,S=await K(r,s,a,(E,I,D)=>E.onActivityDeltaEvent?.({event:h,messages:I,state:D,agent:n,input:t,activityMessage:x}));if(c(S),S.stopPropagation!==!0)try{let E=j(x.content??{}),I=Br.applyPatch(E,h.patch??[],!0,!1).newDocument;s[d]={...x,content:j(I),activityType:h.activityType},c({messages:s})}catch(E){let I=E instanceof Error?E.message:String(E);console.warn(`Failed to apply activity patch for '${h.messageId}': ${I}`)}return f()}case v.RAW:return c(await K(r,s,a,(h,d,g)=>h.onRawEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.CUSTOM:return c(await K(r,s,a,(h,d,g)=>h.onCustomEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.RUN_STARTED:{let h=await K(r,s,a,(d,g,x)=>d.onRunStartedEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let d=m;if(d.input?.messages){for(let g of d.input.messages)s.find(x=>x.id===g.id)||s.push(g);c({messages:s})}}return f()}case v.RUN_FINISHED:{let h=m,d=h.outcome?.type==="interrupt"?{event:h,outcome:"interrupt",interrupts:h.outcome.interrupts}:{event:h,outcome:"success",result:h.result},g=await K(r,s,a,(x,S,E)=>x.onRunFinishedEvent?.({...d,messages:S,state:E,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=d.outcome==="interrupt"?[...d.interrupts]:[]),f()}case v.RUN_ERROR:return c(await K(r,s,a,(h,d,g)=>h.onRunErrorEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.STEP_STARTED:return c(await K(r,s,a,(h,d,g)=>h.onStepStartedEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.STEP_FINISHED:return c(await K(r,s,a,(h,d,g)=>h.onStepFinishedEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case v.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be tranformed before being applied");case v.THINKING_START:return f();case v.THINKING_END:return f();case v.THINKING_TEXT_MESSAGE_START:return f();case v.THINKING_TEXT_MESSAGE_CONTENT:return f();case v.THINKING_TEXT_MESSAGE_END:return f();case v.REASONING_START:return c(await K(r,s,a,(h,d,g)=>h.onReasoningStartEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.REASONING_MESSAGE_START:{let h=await K(r,s,a,(d,g,x)=>d.onReasoningMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:d}=m;if(!s.find(g=>g.id===d)){let g={id:d,role:"reasoning",content:""};s.push(g),c({messages:s})}}return f()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:h,delta:d}=m,g=s.find(S=>S.id===h);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${h}'`),f();let x=await K(r,s,a,(S,E,I)=>S.onReasoningMessageContentEvent?.({event:m,messages:E,state:I,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${d}`,c({messages:s})),f()}case v.REASONING_MESSAGE_END:{let{messageId:h}=m,d=s.find(g=>g.id===h);return d?(c(await K(r,s,a,(g,x,S)=>g.onReasoningMessageEndEvent?.({event:m,messages:x,state:S,agent:n,input:t,reasoningMessageBuffer:typeof d.content=="string"?d.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:d,messages:s,state:a,agent:n,input:t})})),f()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${h}'`),f())}case v.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case v.REASONING_END:return c(await K(r,s,a,(h,d,g)=>h.onReasoningEndEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:h,entityId:d,encryptedValue:g}=m,x=await K(r,s,a,(S,E,I)=>S.onReasoningEncryptedValueEvent?.({event:m,messages:E,state:I,agent:n,input:t}));if(c(x),x.stopPropagation!==!0){let S=!1;if(h==="tool-call"){for(let E of s)if(E.role==="assistant"&&E.toolCalls){let I=E.toolCalls.find(D=>D.id===d);if(I){I.encryptedValue=g,S=!0;break}}}else{let E=s.find(I=>I.id===d);E?.role!=="activity"&&E&&(E.encryptedValue=g,S=!0)}S&&(l.messages=s)}return f()}}return m.type,f()}),Ss(),r.length>0?ws({}):m=>m)},zs=t=>e=>{let n=Qn(t),r=new Map,i=new Map,o=!1,s=!1,a=!1,l=new Map,c=!1,f=!1,m=!1,b=()=>{r.clear(),i.clear(),l.clear(),c=!1,f=!1,o=!1,s=!1,m=!0};return e.pipe(Ce(h=>{let d=h.type;if(n?.event("VERIFY","Event:",h,{type:h.type}),s)return te(()=>new Q(`Cannot send event type '${d}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(o&&d!==v.RUN_ERROR&&d!==v.RUN_STARTED)return te(()=>new Q(`Cannot send event type '${d}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(a){if(d===v.RUN_STARTED){if(m&&!o)return te(()=>new Q("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));o&&b()}}else if(a=!0,d!==v.RUN_STARTED&&d!==v.RUN_ERROR)return te(()=>new Q("First event must be 'RUN_STARTED'"));switch(d){case v.TEXT_MESSAGE_START:{let g=h.messageId;return r.has(g)?te(()=>new Q(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${g}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(r.set(g,!0),re(h))}case v.TEXT_MESSAGE_CONTENT:{let g=h.messageId;return r.has(g)?re(h):te(()=>new Q(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${g}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case v.TEXT_MESSAGE_END:{let g=h.messageId;return r.has(g)?(r.delete(g),re(h)):te(()=>new Q(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${g}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case v.TOOL_CALL_START:{let g=h.toolCallId;return i.has(g)?te(()=>new Q(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${g}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(i.set(g,!0),re(h))}case v.TOOL_CALL_ARGS:{let g=h.toolCallId;return i.has(g)?re(h):te(()=>new Q(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${g}'. Start a tool call with 'TOOL_CALL_START' first.`))}case v.TOOL_CALL_END:{let g=h.toolCallId;return i.has(g)?(i.delete(g),re(h)):te(()=>new Q(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${g}'. A 'TOOL_CALL_START' event must be sent first.`))}case v.STEP_STARTED:{let g=h.stepName;return l.has(g)?te(()=>new Q(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),re(h))}case v.STEP_FINISHED:{let g=h.stepName;return l.has(g)?(l.delete(g),re(h)):te(()=>new Q(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,re(h);case v.RUN_FINISHED:if(l.size>0){let g=Array.from(l.keys()).join(", ");return te(()=>new Q(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(r.size>0){let g=Array.from(r.keys()).join(", ");return te(()=>new Q(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(i.size>0){let g=Array.from(i.keys()).join(", ");return te(()=>new Q(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return o=!0,re(h);case v.RUN_ERROR:return s=!0,re(h);case v.CUSTOM:return re(h);case v.THINKING_TEXT_MESSAGE_START:return c?f?te(()=>new Q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(f=!0,re(h)):te(()=>new Q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case v.THINKING_TEXT_MESSAGE_CONTENT:return f?re(h):te(()=>new Q("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case v.THINKING_TEXT_MESSAGE_END:return f?(f=!1,re(h)):te(()=>new Q("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case v.THINKING_START:return c?te(()=>new Q("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(c=!0,re(h));case v.THINKING_END:return c?(c=!1,re(h)):te(()=>new Q("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return re(h)}}))},Zt=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),Ph=t=>pi(()=>qt(t())).pipe(_s(e=>{if(!e.ok){let i=e.headers.get("content-type")||"";return qt(e.text()).pipe(Ce(o=>{let s=o;if(i.includes("application/json"))try{s=JSON.parse(o)}catch{}let a=Error(`HTTP ${e.status}: ${typeof s=="string"?s:JSON.stringify(s)}`);return a.status=e.status,a.payload=s,te(()=>a)}))}let n={type:Zt.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new ee(i=>(i.next(n),(async()=>{try{for(;;){let{done:o,value:s}=await r.read();if(o)break;let a={type:Zt.DATA,data:s};i.next(a)}i.complete()}catch(o){i.error(o)}})(),()=>{r.cancel().catch(o=>{if(o?.name!=="AbortError")throw o})})):te(()=>Error("Failed to getReader() from response"))})),Dh=(t,e)=>{let n=Qn(e),r=new rt,i=new TextDecoder("utf-8",{fatal:!1}),o="";t.subscribe({next:a=>{if(a.type!==Zt.HEADERS&&a.type===Zt.DATA&&a.data){let l=i.decode(a.data,{stream:!0});o+=l;let c=o.split(/\n\n/);o=c.pop()||"";for(let f of c)s(f)}},error:a=>r.error(a),complete:()=>{o&&(o+=i.decode(),s(o)),r.complete()}});function s(a){let l=a.split(`
|
|
9
|
+
`),c=[];for(let f of l)f.startsWith("data:")&&c.push(f.slice(5).replace(/^ /,""));if(c.length>0)try{let f=c.join(`
|
|
10
|
+
`),m=JSON.parse(f);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(f){r.error(f)}}return r.asObservable()},Uh=t=>{let e=new rt,n=new Uint8Array;t.subscribe({next:i=>{if(i.type!==Zt.HEADERS&&i.type===Zt.DATA&&i.data){let o=new Uint8Array(n.length+i.data.length);o.set(n,0),o.set(i.data,n.length),n=o,r()}},error:i=>e.error(i),complete:()=>{if(n.length>0)try{r()}catch{console.warn("Incomplete or invalid protocol buffer data at stream end")}e.complete()}});function r(){for(;n.length>=4;){let i=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<i)break;try{let o=n.slice(4,i),s=Cc(o);e.next(s),n=n.slice(i)}catch(o){let s=o instanceof Error?o.message:String(o);e.error(Error(`Failed to decode protocol buffer message: ${s}`));return}}}return e.asObservable()},Hh=(t,e)=>{let n=Qn(e),r=new rt,i=new Yr,o=!1;return t.subscribe({next:s=>{if(i.next(s),s.type===Zt.HEADERS&&!o){o=!0;let a=s.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===Hs?"protobuf":"sse"}),a===Hs?Uh(i).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):Dh(i,n).subscribe({next:l=>{try{let c=Pr.parse(l);n?.event("HTTP","Event validated:",c,{type:c.type,valid:!0}),r.next(c)}catch(c){n?.event("HTTP","Event invalid:",{json:l,error:String(c)}),r.error(c)}},error:l=>{if(l?.name==="AbortError"){r.next({type:v.RUN_ERROR,message:l.message||"Request aborted",code:"abort",rawEvent:l}),r.complete();return}return r.error(l)},complete:()=>r.complete()})}else o||r.error(Error("No headers event received before data events"))},error:s=>{i.error(s),r.error(s)},complete:()=>{i.complete()}}),r.asObservable()},Y=u.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Gh=u.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Fh=u.object({type:u.literal(Y.enum.TextMessageStart),messageId:u.string(),parentMessageId:u.string().optional(),role:u.string().optional()}),$h=u.object({type:u.literal(Y.enum.TextMessageContent),messageId:u.string(),content:u.string()}),zh=u.object({type:u.literal(Y.enum.TextMessageEnd),messageId:u.string()}),Bh=u.object({type:u.literal(Y.enum.ActionExecutionStart),actionExecutionId:u.string(),actionName:u.string(),parentMessageId:u.string().optional()}),Vh=u.object({type:u.literal(Y.enum.ActionExecutionArgs),actionExecutionId:u.string(),args:u.string()}),jh=u.object({type:u.literal(Y.enum.ActionExecutionEnd),actionExecutionId:u.string()}),Wh=u.object({type:u.literal(Y.enum.ActionExecutionResult),actionName:u.string(),actionExecutionId:u.string(),result:u.string()}),qh=u.object({type:u.literal(Y.enum.AgentStateMessage),threadId:u.string(),agentName:u.string(),nodeName:u.string(),runId:u.string(),active:u.boolean(),role:u.string(),state:u.string(),running:u.boolean()}),Xh=u.object({type:u.literal(Y.enum.MetaEvent),name:Gh,value:u.any()}),Kh=u.object({type:u.literal(Y.enum.RunError),message:u.string(),code:u.string().optional()});u.discriminatedUnion("type",[Fh,$h,zh,Bh,Vh,jh,Wh,qh,Xh,Kh]),u.object({id:u.string(),role:u.string(),content:u.string(),parentMessageId:u.string().optional()}),u.object({id:u.string(),name:u.string(),arguments:u.any(),parentMessageId:u.string().optional()}),u.object({id:u.string(),result:u.any(),actionExecutionId:u.string(),actionName:u.string()});var Zh=t=>{if(typeof t=="string")return t;if(!Array.isArray(t))return;let e=t.filter(n=>n.type==="text").map(n=>n.text).filter(n=>n.length>0);if(e.length!==0)return e.join(`
|
|
11
|
+
`)},Yh=(t,e,n)=>r=>{let i={},o=!0,s=!0,a="",l=null,c=null,f=[],m={},b=h=>{typeof h=="object"&&h&&("messages"in h&&delete h.messages,i=h)};return r.pipe(Ce(h=>{switch(h.type){case v.TEXT_MESSAGE_START:{let d=h;return[{type:Y.enum.TextMessageStart,messageId:d.messageId,role:d.role}]}case v.TEXT_MESSAGE_CONTENT:{let d=h;return[{type:Y.enum.TextMessageContent,messageId:d.messageId,content:d.delta}]}case v.TEXT_MESSAGE_END:{let d=h;return[{type:Y.enum.TextMessageEnd,messageId:d.messageId}]}case v.TOOL_CALL_START:{let d=h;return f.push({id:d.toolCallId,type:"function",function:{name:d.toolCallName,arguments:""}}),s=!0,m[d.toolCallId]=d.toolCallName,[{type:Y.enum.ActionExecutionStart,actionExecutionId:d.toolCallId,actionName:d.toolCallName,parentMessageId:d.parentMessageId}]}case v.TOOL_CALL_ARGS:{let d=h,g=f.find(S=>S.id===d.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${d.toolCallId}'`),[];g.function.arguments+=d.delta;let x=!1;if(c){let S=c.find(E=>E.tool==g.function.name);if(S)try{let E=JSON.parse(mi(g.function.arguments));S.tool_argument&&S.tool_argument in E?(b({...i,[S.state_key]:E[S.tool_argument]}),x=!0):S.tool_argument||(b({...i,[S.state_key]:E}),x=!0)}catch{}}return[{type:Y.enum.ActionExecutionArgs,actionExecutionId:d.toolCallId,args:d.delta},...x?[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:s}]:[]]}case v.TOOL_CALL_END:{let d=h;return[{type:Y.enum.ActionExecutionEnd,actionExecutionId:d.toolCallId}]}case v.TOOL_CALL_RESULT:{let d=h;return[{type:Y.enum.ActionExecutionResult,actionExecutionId:d.toolCallId,result:d.content,actionName:m[d.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let d=h;switch(d.name){case"Exit":o=!1;break;case"PredictState":c=d.value;break}return[{type:Y.enum.MetaEvent,name:d.name,value:d.value}]}case v.STATE_SNAPSHOT:return b(h.snapshot),[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:s}];case v.STATE_DELTA:{let d=h,g=Br.applyPatch(i,d.delta,!0,!1);return g?(b(g.newDocument),[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:s}]):[]}case v.MESSAGES_SNAPSHOT:return l=h.messages,[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify({...i,...l?{messages:l}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return l&&(i.messages=l),Object.keys(i).length===0?[]:[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify({...i,...l?{messages:Jh(l)}:{}}),active:!1}];case v.RUN_ERROR:{let d=h;return[{type:Y.enum.RunError,message:d.message,code:d.code}]}case v.STEP_STARTED:return a=h.stepName,f=[],c=null,[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:!0}];case v.STEP_FINISHED:return f=[],c=null,[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:!1}];default:return[]}}))};function Jh(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=Zh(n.content);if(r){let i={id:n.id,role:n.role,content:r};e.push(i)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let i of n.toolCalls){let o={id:i.id,name:i.function.name,arguments:JSON.parse(i.function.arguments),parentMessageId:n.id};e.push(o)}}else if(n.role==="tool"){let r="unknown";for(let o of t)if(o.role==="assistant"&&o.toolCalls?.length){for(let s of o.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let i={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(i)}return e}var Yi=t=>e=>{let n=Qn(t),r,i,o,s,a=()=>{if(!r||s!=="text")throw Error("No text message to close");let m={type:v.TEXT_MESSAGE_END,messageId:r.messageId};return s=void 0,r=void 0,n?.event("TRANSFORM","TEXT_MESSAGE_END",m,{messageId:m.messageId}),m},l=()=>{if(!i||s!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:i.toolCallId};return s=void 0,i=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},c=()=>{if(!o||s!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:o.messageId};return s=void 0,o=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},f=()=>s==="text"?[a()]:s==="tool"?[l()]:s==="reasoning"?[c()]:[];return e.pipe(Ce(m=>{switch(m.type){case v.TEXT_MESSAGE_START:case v.TEXT_MESSAGE_CONTENT:case v.TEXT_MESSAGE_END:case v.TOOL_CALL_START:case v.TOOL_CALL_ARGS:case v.TOOL_CALL_END:case v.TOOL_CALL_RESULT:case v.STATE_SNAPSHOT:case v.STATE_DELTA:case v.MESSAGES_SNAPSHOT:case v.CUSTOM:case v.RUN_STARTED:case v.RUN_FINISHED:case v.RUN_ERROR:case v.STEP_STARTED:case v.STEP_FINISHED:case v.THINKING_START:case v.THINKING_END:case v.THINKING_TEXT_MESSAGE_START:case v.THINKING_TEXT_MESSAGE_CONTENT:case v.THINKING_TEXT_MESSAGE_END:case v.REASONING_START:case v.REASONING_MESSAGE_START:case v.REASONING_MESSAGE_CONTENT:case v.REASONING_MESSAGE_END:case v.REASONING_END:return[...f(),m];case v.RAW:case v.ACTIVITY_SNAPSHOT:case v.ACTIVITY_DELTA:case v.REASONING_ENCRYPTED_VALUE:return[m];case v.TEXT_MESSAGE_CHUNK:let b=m,h=[];if((s!=="text"||b.messageId!==void 0&&b.messageId!==r?.messageId)&&h.push(...f()),s!=="text"){if(b.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:b.messageId,name:b.name},s="text";let E={type:v.TEXT_MESSAGE_START,messageId:b.messageId,role:b.role||"assistant",...b.name!==void 0&&{name:b.name}};h.push(E),n?.event("TRANSFORM","TEXT_MESSAGE_START",E,{messageId:b.messageId})}if(b.delta!==void 0){let E={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:b.delta};h.push(E),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",E,{messageId:r.messageId})}return h;case v.TOOL_CALL_CHUNK:let d=m,g=[];if((s!=="tool"||d.toolCallId!==void 0&&d.toolCallId!==i?.toolCallId)&&g.push(...f()),s!=="tool"){if(d.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(d.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");i={toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId},s="tool";let E={type:v.TOOL_CALL_START,toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId};g.push(E),n?.event("TRANSFORM","TOOL_CALL_START",E,{toolCallId:d.toolCallId,toolCallName:d.toolCallName})}if(d.delta!==void 0){let E={type:v.TOOL_CALL_ARGS,toolCallId:i.toolCallId,delta:d.delta};g.push(E),n?.event("TRANSFORM","TOOL_CALL_ARGS",E,{toolCallId:i.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let x=m,S=[];if((s!=="reasoning"||x.messageId&&x.messageId!==o?.messageId)&&S.push(...f()),s!=="reasoning"){if(x.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");o={messageId:x.messageId},s="reasoning";let E={type:v.REASONING_MESSAGE_START,messageId:x.messageId};S.push(E),n?.event("TRANSFORM","REASONING_MESSAGE_START",E,{messageId:x.messageId})}if(x.delta!==void 0){let E={type:v.REASONING_MESSAGE_CONTENT,messageId:o.messageId,delta:x.delta};S.push(E),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",E,{messageId:o.messageId})}return S}return m.type,[]}),Kt(()=>{f()}))};function Qh(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function Fc(t,e){let n=new Set(t.map(s=>s.id)),r=new Set(Object.keys(e)),i=[...n].filter(s=>!r.has(s));if(i.length>0)throw Error(`buildResumeArray: missing responses for open interrupts: ${i.join(", ")}`);let o=[...r].filter(s=>!n.has(s));if(o.length>0)throw Error(`buildResumeArray: responses reference unknown interrupt ids: ${o.join(", ")}`);return t.map(s=>{let a=e[s.id];if(a.status==="resolved"){let l={interruptId:s.id,status:"resolved"};return a.payload!==void 0&&(l.payload=a.payload),l}return{interruptId:s.id,status:"cancelled"}})}var Ji=class{runNext(t,e){return e.run(t).pipe(Yi(!1))}runNextWithState(t,e){let n=j(t.messages||[]),r=j(t.state||{}),i=new Yr;return Gc(t,i,e,[]).subscribe(o=>{o.messages!==void 0&&(n=o.messages),o.state!==void 0&&(r=o.state)}),this.runNext(t,e).pipe(fi(async o=>(i.next(o),await new Promise(s=>setTimeout(s,0)),{event:o,messages:j(n),state:j(r)})))}},em=class extends Ji{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function tm(t){let e=t.content;if(Array.isArray(e)){let n=e.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...t,content:n}}return typeof e=="string"?t:{...t,content:""}}var nm=class extends Ji{run(t,e){let{parentRunId:n,...r}=t,i={...r,messages:r.messages.map(tm)};return this.runNext(i,e)}},Lc="THINKING_START",Pc="THINKING_END",Dc="THINKING_TEXT_MESSAGE_START",Uc="THINKING_TEXT_MESSAGE_CONTENT",Hc="THINKING_TEXT_MESSAGE_END",rm=class extends Ji{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(Xt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Lc:{this.currentReasoningId=Oe();let{title:e,...n}=t;return this.warnAboutTransformation(Lc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case Dc:return this.currentMessageId=Oe(),this.warnAboutTransformation(Dc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Uc:{let{delta:e,...n}=t;return this.warnAboutTransformation(Uc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Oe(),delta:e}}case Hc:{let e=this.currentMessageId??Oe();return this.warnAboutTransformation(Hc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case Pc:{let e=this.currentReasoningId??Oe();return this.warnAboutTransformation(Pc,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function im(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function om(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function sm(t){let e=im(t.mimeType);return t.data?{type:e,source:{type:"data",value:t.data,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t.url?{type:e,source:{type:"url",value:t.url,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t}function am(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>om(r)?sm(r):r);return{...t,content:n}}var lm=class extends Ji{run(t,e){let n={...t,messages:t.messages.map(am)};return this.runNext(n,e)}},cm="0.0.57",um=class{get maxVersion(){return cm}get debug(){return this._debug}set debug(t){this._debug=Zi(t),this._debugLogger=$s(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?$s(Zi(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:i,debug:o}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??bt(),this.messages=j(r??[]),this.state=j(i??{}),this._debug=Zi(o),this._debugLogger=$s(this._debug),Jn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new nm),Jn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new rm),Jn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new lm)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(n=>typeof n=="function"?new em(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??bt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,i=new Set(this.messages.map(l=>l.id)),o=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,o),this.activeRunDetach$=new rt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await di(Zr(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:f=>c.run(f,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),Yi(this.debugLogger),zs(this.debugLogger),l=>l.pipe(hi(this.activeRunDetach$)),l=>this.apply(n,l,o),l=>this.processApplyEvents(n,l,o),Kn(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,o))),Kt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(re(null)));let a=j(this.messages).filter(l=>!i.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new us}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??bt();let n=this.prepareRunAgentInput(t),r,i=new Set(this.messages.map(l=>l.id)),o=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,o),this.activeRunDetach$=new rt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await di(Zr(()=>pi(()=>this.connect(n)),Yi(this.debugLogger),zs(this.debugLogger),l=>l.pipe(hi(this.activeRunDetach$)),l=>this.apply(n,l,o),l=>this.processApplyEvents(n,l,o),Kn(l=>(this.isRunning=!1,l instanceof us?Jr:this.onError(n,l,o))),Kt(()=>{this.isRunning=!1,this.onFinalize(n,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(re(null)),{defaultValue:void 0});let a=j(this.messages).filter(l=>!i.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return Gc(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(As(r=>{r.messages&&(this.messages=r.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=j(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:t?.runId||bt(),tools:j(t?.tools??[]),context:j(t?.context??[]),forwardedProps:j(t?.forwardedProps??{}),state:j(this.state),messages:e,...t?.resume===void 0?{}:{resume:j(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(o=>o.interruptId)),i=this.pendingInterrupts.map(o=>o.id).filter(o=>!r.has(o));if(i.length>0)throw new Q(`Thread has ${i.length} pending interrupt(s) not addressed by resume: ${i.join(", ")}`);for(let o of this.pendingInterrupts)if(Qh(o))throw new Q(`Interrupt ${o.id} expired at ${o.expiresAt}`)}let n=await K(e,this.messages,this.state,(r,i,o)=>r.onRunInitialized?.({messages:i,state:o,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}onError(t,e,n){return qt(K(n,this.messages,this.state,(r,i,o)=>r.onRunFailed?.({error:e,messages:i,state:o,agent:this,input:t}))).pipe(Xt(r=>{let i=r;if((i.messages!==void 0||i.state!==void 0)&&(i.messages!==void 0&&(this.messages=i.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),i.state!==void 0&&(this.state=i.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),i.stopPropagation!==!0){let o=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||o==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await K(e,this.messages,this.state,(r,i,o)=>r.onRunFinalized?.({messages:i,state:o,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=j(this.messages),t.state=j(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=j(this.pendingInterrupts),t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let n of this.subscribers)await n.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let n of e.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=j(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=j(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??bt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:i=>r.run(i,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Yi(this.debugLogger),zs(this.debugLogger),Yh(this.threadId,e.runId,this.agentId),n=>n.pipe(Xt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},$c=class extends um{requestInit(t){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t,e){return this.abortController=t?.abortController??new AbortController,super.runAgent(t,e)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(t){super(t),this.abortController=new AbortController,this.url=t.url,this.headers=j(t.headers??{}),this.fetch=t.fetch??((e,n)=>fetch(e,n))}run(t){return Hh(Ph(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=j(this.headers??{}),t.fetch=this.fetch;let e=new AbortController,n=this.abortController.signal;return n.aborted&&e.abort(n.reason),t.abortController=e,t}};var Qi=class{element;#n;#e;#t=[];constructor(e){this.#n=e,this.#e=e.strings??ne,this.element=document.createElement("div"),this.element.className="attachment-tray",this.element.setAttribute("part","attachment-tray"),this.element.hidden=!0}add(e){let n={localId:Oe(),file:e,status:Le.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#t.push(n);let r=this.#i(e);if(r!==null){n.status=Le.ERROR,n.error=r,this.#s(),this.#n.onChange?.();return}this.#s(),this.#n.onChange?.(),this.#r(n)}readyRefs(){let e=[];for(let n of this.#t)n.ref!==null&&e.push(n.ref);return e}hasPending(){return this.#t.some(e=>e.status===Le.UPLOADING)}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===Le.UPLOADING),this.#s()}clear(){for(let e of this.#t)e.controller?.abort();this.#t=[],this.#s()}dispose(){for(let e of this.#t)e.controller?.abort()}#i(e){return this.#n.maxBytes>0&&e.size>this.#n.maxBytes?this.#e.tooLarge.replace("{size}",kr(this.#n.maxBytes)):dm(this.#n.accept,e)?null:this.#e.fileTypeNotAllowed}#r(e){let n=this.#i(e.file);if(n!==null){e.status=Le.ERROR,e.error=n,this.#s(),this.#n.onChange?.();return}e.status=Le.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#s(),this.#n.upload(e.file,i=>{e.progress=i,this.#s()},r.signal).then(i=>{e.status=Le.READY,e.ref=i}).catch(i=>{e.status=Le.ERROR,e.error=i instanceof Error?i.message:this.#e.uploadFailed}).finally(()=>{e.controller=null,this.#s(),this.#n.onChange?.()})}#a(e){e.controller?.abort(),this.#t=this.#t.filter(n=>n!==e),this.#s(),this.#n.onChange?.()}#s(){this.element.replaceChildren(),this.element.hidden=this.#t.length===0;for(let e of this.#t)this.element.appendChild(this.#o(e))}#o(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`,n.setAttribute("part","attachment-chip");let r=document.createElement("span");r.className="attachment-chip-icon",r.setAttribute("part","attachment-chip-icon"),r.textContent=rs(e.file.type),r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.className="attachment-chip-name",i.setAttribute("part","attachment-chip-name"),i.textContent=e.file.name,i.title=e.file.name;let o=document.createElement("span");if(o.className="attachment-chip-size",o.setAttribute("part","attachment-chip-size"),o.textContent=e.status===Le.ERROR?e.error:kr(e.file.size),n.append(r,i,o),e.status===Le.UPLOADING){let a=document.createElement("div");a.className="attachment-chip-bar",a.setAttribute("part","attachment-chip-bar");let l=document.createElement("div");l.className="attachment-chip-bar-fill",l.setAttribute("part","attachment-chip-bar-fill"),l.style.width=`${Math.round(e.progress*100)}%`,a.appendChild(l),n.appendChild(a)}if(e.status===Le.ERROR){let a=document.createElement("button");a.type="button",a.className="attachment-chip-retry",a.setAttribute("part","attachment-chip-retry"),a.title=this.#e.retry,a.setAttribute("aria-label",this.#e.retryUpload),a.textContent="\u21BB",a.addEventListener("click",()=>this.#r(e)),n.appendChild(a)}let s=document.createElement("button");return s.type="button",s.className="attachment-chip-remove",s.setAttribute("part","attachment-chip-remove"),s.title=this.#e.remove,s.setAttribute("aria-label",this.#e.removeAttachment),s.textContent="\u2715",s.addEventListener("click",()=>this.#a(e)),n.appendChild(s),n}};function dm(t,e){let n=t.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),i=e.name.toLowerCase();return n.some(o=>o.startsWith(".")?i.endsWith(o):o.endsWith("/*")?r.startsWith(o.slice(0,-1)):r===o)}function eo(t,e=Date.now(),n=ne){if(!Number.isFinite(t))return n.justNow;let r=Math.round((e-t)/1e3);if(r<60)return n.justNow;let i=Math.round(r/60);if(i<60)return n.minutesAgo.replace("{n}",String(i));let o=Math.round(i/60);if(o<24)return n.hoursAgo.replace("{n}",String(o));let s=Math.round(o/24);return s<7?n.daysAgo.replace("{n}",String(s)):n.weeksAgo.replace("{n}",String(Math.round(s/7)))}var er=class{element;#n;#e;#t;#i;#r=[];constructor(e,n=ne){this.#n=e,this.#i=n,this.element=document.createElement("div"),this.element.className="checkpoints",this.element.setAttribute("part","checkpoints"),this.element.setAttribute("role","dialog"),this.element.setAttribute("aria-label",n.checkpoints),this.element.hidden=!0;let r=document.createElement("div");r.className="checkpoints-header",r.setAttribute("part","checkpoints-header"),this.#t=document.createElement("span"),this.#t.className="checkpoints-title",this.#t.textContent=n.checkpoints,r.append(this.#t),this.#e=document.createElement("div"),this.#e.className="checkpoints-list",this.#e.setAttribute("part","checkpoints-list"),this.element.append(r,this.#e),this.element.addEventListener("keydown",i=>{i.key==="Escape"&&(i.stopPropagation(),this.close())})}setRuns(e){this.#r=e,this.#a()}setStrings(e){this.#i=e,this.element.setAttribute("aria-label",e.checkpoints),this.#t.textContent=e.checkpoints,this.#a()}open(){this.element.hidden=!1}close(){this.element.hidden=!0}get open_(){return!this.element.hidden}#a(){if(this.#e.replaceChildren(),this.#r.length===0){let e=document.createElement("div");e.className="checkpoints-empty",e.setAttribute("part","checkpoints-empty"),e.textContent=this.#i.noCheckpoints,this.#e.append(e);return}for(let e of this.#r)this.#e.append(this.#s(e))}#s(e){let n=document.createElement("div");n.className="checkpoint-row",n.setAttribute("part","checkpoint-row");let r=document.createElement("span");if(r.className="checkpoint-label",r.textContent=e.started_at===null?e.run_id:eo(Date.parse(e.started_at),Date.now(),this.#i),r.title=e.run_id,n.append(r),e.parent_run_id!==null){let i=document.createElement("span");i.className="checkpoint-branch",i.setAttribute("part","checkpoint-branch"),i.textContent=this.#i.forkedRun,i.title=e.parent_run_id,n.append(i)}return n.append(this.#o(e.run_id,"resume",this.#i.resumeRun),this.#o(e.run_id,"fork",this.#i.forkRun)),n}#o(e,n,r){let i=document.createElement("button");return i.type="button",i.className=`checkpoint-action checkpoint-${n}`,i.setAttribute("part",`checkpoint-action checkpoint-${n}`),i.textContent=r,i.addEventListener("click",()=>{this.close(),this.#n(e,n)}),i}};function zc(t,e){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${t}`,n.setAttribute("part",`confirm-button confirm-${t}`),n.textContent=e,n}function js(t,e,n={}){let r=n.strings??ne;return new Promise(i=>{let o=document.createElement("div");o.className="confirm",o.setAttribute("part","confirm"),o.setAttribute("data-tool-name",e.toolName),o.setAttribute("role","group"),o.setAttribute("aria-label",r.confirmAction);let s=document.createElement("div");s.className="confirm-body",s.setAttribute("part","confirm-body"),s.textContent=e.message??r.confirmRun.replace("{tool}",e.toolName);let a=document.createElement("pre");a.className="confirm-args",a.setAttribute("part","confirm-args"),a.textContent=JSON.stringify(e.args,null,2);let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let c=zc("cancel",r.cancel),f=zc("confirm",r.confirm),m=!1,b=h=>{m||(m=!0,c.disabled=!0,f.disabled=!0,o.setAttribute("data-resolved",h?"confirmed":"declined"),i(h))};if(c.addEventListener("click",()=>b(!1)),f.addEventListener("click",()=>b(!0)),n.signal?.addEventListener("abort",()=>b(!1),{once:!0}),l.append(c,f),o.append(s,a,l),t.appendChild(o),n.signal?.aborted===!0){b(!1);return}f.focus()})}function Ws(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function pm(t){let e=document.createElement("input");return e.type="text",e.className="question-input",e.setAttribute("part","question-input"),e.placeholder=t,e}function qs(t,e,n={}){let r=n.strings??ne,i=e.options??[],o=i.length>0,s=!o||e.allowCustom===!0;return new Promise(a=>{let l=document.createElement("div");l.className="question",l.setAttribute("part","question"),l.setAttribute("role","group"),l.setAttribute("aria-label",r.askUserAction);let c=document.createElement("div");c.className="question-body",c.setAttribute("part","question-body"),c.textContent=e.question;let f=document.createElement("div");f.className="question-options",f.setAttribute("part","question-options");let m=`q-${i.length}-${e.question.length}`,b=[];for(let P of i){let U=document.createElement("label");U.className="question-choice",U.setAttribute("part","question-choice");let we=document.createElement("input");we.type="radio",we.name=m,we.value=P,we.setAttribute("part","question-radio");let mt=document.createElement("span");mt.setAttribute("part","question-choice-text"),mt.textContent=P,U.append(we,mt),f.appendChild(U),b.push(we)}let h=null,d=null;if(s){if(d=pm(r.answerPlaceholder),o){let P=document.createElement("label");P.className="question-choice",P.setAttribute("part","question-choice"),h=document.createElement("input"),h.type="radio",h.name=m,h.value="",h.setAttribute("part","question-radio");let U=document.createElement("span");U.setAttribute("part","question-choice-text"),U.textContent=r.otherOption,P.append(h,U),f.appendChild(P),d.disabled=!0}f.appendChild(d)}let g=document.createElement("div");g.className="question-actions",g.setAttribute("part","question-actions");let x=document.createElement("button");x.type="button",x.className="question-btn",x.setAttribute("part","question-button"),x.textContent=r.submit,g.appendChild(x);let S=!1,E=()=>{let P=b.find(U=>U.checked);if(P!==void 0)return P.value;if(d!==null&&(h===null||h.checked)){let U=d.value.trim();return U===""?null:U}return null},I=()=>{d!==null&&h!==null&&(d.disabled=!h.checked),x.disabled=E()===null},D=P=>{if(!S){S=!0,x.disabled=!0;for(let U of b)U.disabled=!0;h!==null&&(h.disabled=!0),d!==null&&(d.disabled=!0),l.setAttribute("data-resolved",P===""?"cancelled":"answered"),a(P)}};for(let P of[...b,...h!==null?[h]:[]])P.addEventListener("change",I);if(d?.addEventListener("input",I),d?.addEventListener("keydown",P=>{if(P.key==="Enter"){P.preventDefault();let U=E();U!==null&&D(U)}}),x.addEventListener("click",()=>{let P=E();P!==null&&D(P)}),n.signal?.addEventListener("abort",()=>D(""),{once:!0}),l.append(c,f,g),t.appendChild(l),n.signal?.aborted===!0){D("");return}I(),(o?b[0]:d)?.focus()})}function Bc(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function fm(t){if(Array.isArray(t))return t}function hm(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,i,o,s,a=[],l=!0,c=!1;try{if(o=(n=n.call(t)).next,e!==0)for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(f){c=!0,i=f}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function mm(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
12
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gm(t,e){return fm(t)||hm(t,e)||vm(t,e)||mm()}function vm(t,e){if(t){if(typeof t=="string")return Bc(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Bc(t,e):void 0}}var nu=Object.entries,Vc=Object.setPrototypeOf,bm=Object.isFrozen,ym=Object.getPrototypeOf,xm=Object.getOwnPropertyDescriptor,Ae=Object.freeze,Ge=Object.seal,An=Object.create,ru=typeof Reflect<"u"&&Reflect,Qs=ru.apply,ea=ru.construct;Ae||(Ae=function(e){return e});Ge||(Ge=function(e){return e});Qs||(Qs=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];return e.apply(n,i)});ea||(ea=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new e(...r)});var Sn=pe(Array.prototype.forEach),Em=pe(Array.prototype.lastIndexOf),jc=pe(Array.prototype.pop),wn=pe(Array.prototype.push),Tm=pe(Array.prototype.splice),_e=Array.isArray,rr=pe(String.prototype.toLowerCase),Xs=pe(String.prototype.toString),Wc=pe(String.prototype.match),_n=pe(String.prototype.replace),qc=pe(String.prototype.indexOf),Sm=pe(String.prototype.trim),wm=pe(Number.prototype.toString),_m=pe(Boolean.prototype.toString),Xc=typeof BigInt>"u"?null:pe(BigInt.prototype.toString),Kc=typeof Symbol>"u"?null:pe(Symbol.prototype.toString),oe=pe(Object.prototype.hasOwnProperty),tr=pe(Object.prototype.toString),xe=pe(RegExp.prototype.test),nr=Am(TypeError);function pe(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return Qs(t,e,r)}}function Am(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return ea(t,n)}}function F(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:rr;if(Vc&&Vc(t,null),!_e(e))return t;let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){let o=n(i);o!==i&&(bm(e)||(e[r]=o),i=o)}t[i]=!0}return t}function km(t){for(let e=0;e<t.length;e++)oe(t,e)||(t[e]=null);return t}function Te(t){let e=An(null);for(let r of nu(t)){var n=gm(r,2);let i=n[0],o=n[1];oe(t,i)&&(_e(o)?e[i]=km(o):o&&typeof o=="object"&&o.constructor===Object?e[i]=Te(o):e[i]=o)}return e}function Im(t){switch(typeof t){case"string":return t;case"number":return wm(t);case"boolean":return _m(t);case"bigint":return Xc?Xc(t):"0";case"symbol":return Kc?Kc(t):"Symbol()";case"undefined":return tr(t);case"function":case"object":{if(t===null)return tr(t);let e=t,n=ot(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:tr(r)}return tr(t)}default:return tr(t)}}function ot(t,e){for(;t!==null;){let r=xm(t,e);if(r){if(r.get)return pe(r.get);if(typeof r.value=="function")return pe(r.value)}t=ym(t)}function n(){return null}return n}function Cm(t){try{return xe(t,""),!0}catch{return!1}}var Zc=Ae(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ks=Ae(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Zs=Ae(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Nm=Ae(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ys=Ae(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Rm=Ae(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Yc=Ae(["#text"]),Jc=Ae(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Js=Ae(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Qc=Ae(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),to=Ae(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Om=Ge(/{{[\w\W]*|^[\w\W]*}}/g),Mm=Ge(/<%[\w\W]*|^[\w\W]*%>/g),Lm=Ge(/\${[\w\W]*/g),Pm=Ge(/^data-[\-\w.\u00B7-\uFFFF]+$/),Dm=Ge(/^aria-[\-\w]+$/),eu=Ge(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Um=Ge(/^(?:\w+script|data):/i),Hm=Ge(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Gm=Ge(/^html$/i),Fm=Ge(/^[a-z][.\w]*(-[.\w]+)+$/i),it={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},$m=function(){return typeof window>"u"?null:window},zm=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));let o="dompurify"+(r?"#"+r:"");try{return e.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},tu=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function iu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:$m(),e=N=>iu(N);if(e.version="3.4.7",e.removed=[],!t||!t.document||t.document.nodeType!==it.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,i=r.currentScript;t.DocumentFragment;let o=t.HTMLTemplateElement,s=t.Node,a=t.Element,l=t.NodeFilter,c=t.NamedNodeMap;c===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let f=t.DOMParser,m=t.trustedTypes,b=a.prototype,h=ot(b,"cloneNode"),d=ot(b,"remove"),g=ot(b,"nextSibling"),x=ot(b,"childNodes"),S=ot(b,"parentNode"),E=ot(b,"shadowRoot"),I=ot(b,"attributes"),D=s&&s.prototype?ot(s.prototype,"nodeType"):null,P=s&&s.prototype?ot(s.prototype,"nodeName"):null;if(typeof o=="function"){let N=n.createElement("template");N.content&&N.content.ownerDocument&&(n=N.content.ownerDocument)}let U,we="",mt=n,vo=mt.implementation,xa=mt.createNodeIterator,Lu=mt.createDocumentFragment,Pu=mt.getElementsByTagName,Du=r.importNode,fe=tu();e.isSupported=typeof nu=="function"&&typeof S=="function"&&vo&&vo.createHTMLDocument!==void 0;let pr=Om,fr=Mm,hr=Lm,Uu=Pm,Hu=Dm,Gu=Um,Ea=Hm,Fu=Fm,Ta=eu,se=null,bo=F({},[...Zc,...Ks,...Zs,...Ys,...Yc]),ue=null,yo=F({},[...Jc,...Js,...Qc,...to]),ae=Object.seal(An(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Nn=null,mr=null,gt=Object.seal(An(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Sa=!0,xo=!0,wa=!1,_a=!0,vt=!1,Rn=!0,_t=!1,Eo=!1,To=!1,en=!1,gr=!1,vr=!1,Aa=!0,ka=!1,Ia="user-content-",So=!0,On=!1,tn={},Xe=null,wo=F({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),Ca=null,Na=F({},["audio","video","img","source","image","track"]),_o=null,Ra=F({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),br="http://www.w3.org/1998/Math/MathML",yr="http://www.w3.org/2000/svg",Ke="http://www.w3.org/1999/xhtml",nn=Ke,Ao=!1,ko=null,$u=F({},[br,yr,Ke],Xs),Io=F({},["mi","mo","mn","ms","mtext"]),Co=F({},["annotation-xml"]),zu=F({},["title","style","font","a","script"]),Mn=null,Bu=["application/xhtml+xml","text/html"],Vu="text/html",le=null,rn=null,ju=n.createElement("form"),Oa=function(p){return p instanceof RegExp||p instanceof Function},No=function(){let p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(rn&&rn===p)return;(!p||typeof p!="object")&&(p={}),p=Te(p),Mn=Bu.indexOf(p.PARSER_MEDIA_TYPE)===-1?Vu:p.PARSER_MEDIA_TYPE,le=Mn==="application/xhtml+xml"?Xs:rr,se=oe(p,"ALLOWED_TAGS")&&_e(p.ALLOWED_TAGS)?F({},p.ALLOWED_TAGS,le):bo,ue=oe(p,"ALLOWED_ATTR")&&_e(p.ALLOWED_ATTR)?F({},p.ALLOWED_ATTR,le):yo,ko=oe(p,"ALLOWED_NAMESPACES")&&_e(p.ALLOWED_NAMESPACES)?F({},p.ALLOWED_NAMESPACES,Xs):$u,_o=oe(p,"ADD_URI_SAFE_ATTR")&&_e(p.ADD_URI_SAFE_ATTR)?F(Te(Ra),p.ADD_URI_SAFE_ATTR,le):Ra,Ca=oe(p,"ADD_DATA_URI_TAGS")&&_e(p.ADD_DATA_URI_TAGS)?F(Te(Na),p.ADD_DATA_URI_TAGS,le):Na,Xe=oe(p,"FORBID_CONTENTS")&&_e(p.FORBID_CONTENTS)?F({},p.FORBID_CONTENTS,le):wo,Nn=oe(p,"FORBID_TAGS")&&_e(p.FORBID_TAGS)?F({},p.FORBID_TAGS,le):Te({}),mr=oe(p,"FORBID_ATTR")&&_e(p.FORBID_ATTR)?F({},p.FORBID_ATTR,le):Te({}),tn=oe(p,"USE_PROFILES")?p.USE_PROFILES&&typeof p.USE_PROFILES=="object"?Te(p.USE_PROFILES):p.USE_PROFILES:!1,Sa=p.ALLOW_ARIA_ATTR!==!1,xo=p.ALLOW_DATA_ATTR!==!1,wa=p.ALLOW_UNKNOWN_PROTOCOLS||!1,_a=p.ALLOW_SELF_CLOSE_IN_ATTR!==!1,vt=p.SAFE_FOR_TEMPLATES||!1,Rn=p.SAFE_FOR_XML!==!1,_t=p.WHOLE_DOCUMENT||!1,en=p.RETURN_DOM||!1,gr=p.RETURN_DOM_FRAGMENT||!1,vr=p.RETURN_TRUSTED_TYPE||!1,To=p.FORCE_BODY||!1,Aa=p.SANITIZE_DOM!==!1,ka=p.SANITIZE_NAMED_PROPS||!1,So=p.KEEP_CONTENT!==!1,On=p.IN_PLACE||!1,Ta=Cm(p.ALLOWED_URI_REGEXP)?p.ALLOWED_URI_REGEXP:eu,nn=typeof p.NAMESPACE=="string"?p.NAMESPACE:Ke,Io=oe(p,"MATHML_TEXT_INTEGRATION_POINTS")&&p.MATHML_TEXT_INTEGRATION_POINTS&&typeof p.MATHML_TEXT_INTEGRATION_POINTS=="object"?Te(p.MATHML_TEXT_INTEGRATION_POINTS):F({},["mi","mo","mn","ms","mtext"]),Co=oe(p,"HTML_INTEGRATION_POINTS")&&p.HTML_INTEGRATION_POINTS&&typeof p.HTML_INTEGRATION_POINTS=="object"?Te(p.HTML_INTEGRATION_POINTS):F({},["annotation-xml"]);let y=oe(p,"CUSTOM_ELEMENT_HANDLING")&&p.CUSTOM_ELEMENT_HANDLING&&typeof p.CUSTOM_ELEMENT_HANDLING=="object"?Te(p.CUSTOM_ELEMENT_HANDLING):An(null);if(ae=An(null),oe(y,"tagNameCheck")&&Oa(y.tagNameCheck)&&(ae.tagNameCheck=y.tagNameCheck),oe(y,"attributeNameCheck")&&Oa(y.attributeNameCheck)&&(ae.attributeNameCheck=y.attributeNameCheck),oe(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(ae.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),vt&&(xo=!1),gr&&(en=!0),tn&&(se=F({},Yc),ue=An(null),tn.html===!0&&(F(se,Zc),F(ue,Jc)),tn.svg===!0&&(F(se,Ks),F(ue,Js),F(ue,to)),tn.svgFilters===!0&&(F(se,Zs),F(ue,Js),F(ue,to)),tn.mathMl===!0&&(F(se,Ys),F(ue,Qc),F(ue,to))),gt.tagCheck=null,gt.attributeCheck=null,oe(p,"ADD_TAGS")&&(typeof p.ADD_TAGS=="function"?gt.tagCheck=p.ADD_TAGS:_e(p.ADD_TAGS)&&(se===bo&&(se=Te(se)),F(se,p.ADD_TAGS,le))),oe(p,"ADD_ATTR")&&(typeof p.ADD_ATTR=="function"?gt.attributeCheck=p.ADD_ATTR:_e(p.ADD_ATTR)&&(ue===yo&&(ue=Te(ue)),F(ue,p.ADD_ATTR,le))),oe(p,"ADD_URI_SAFE_ATTR")&&_e(p.ADD_URI_SAFE_ATTR)&&F(_o,p.ADD_URI_SAFE_ATTR,le),oe(p,"FORBID_CONTENTS")&&_e(p.FORBID_CONTENTS)&&(Xe===wo&&(Xe=Te(Xe)),F(Xe,p.FORBID_CONTENTS,le)),oe(p,"ADD_FORBID_CONTENTS")&&_e(p.ADD_FORBID_CONTENTS)&&(Xe===wo&&(Xe=Te(Xe)),F(Xe,p.ADD_FORBID_CONTENTS,le)),So&&(se["#text"]=!0),_t&&F(se,["html","head","body"]),se.table&&(F(se,["tbody"]),delete Nn.tbody),p.TRUSTED_TYPES_POLICY){if(typeof p.TRUSTED_TYPES_POLICY.createHTML!="function")throw nr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof p.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw nr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');U=p.TRUSTED_TYPES_POLICY,we=U.createHTML("")}else U===void 0&&(U=zm(m,i)),U!==null&&typeof we=="string"&&(we=U.createHTML(""));(fe.uponSanitizeElement.length>0||fe.uponSanitizeAttribute.length>0)&&se===bo&&(se=Te(se)),fe.uponSanitizeAttribute.length>0&&ue===yo&&(ue=Te(ue)),Ae&&Ae(p),rn=p},Ma=F({},[...Ks,...Zs,...Nm]),La=F({},[...Ys,...Rm]),Wu=function(p){let y=S(p);(!y||!y.tagName)&&(y={namespaceURI:nn,tagName:"template"});let A=rr(p.tagName),X=rr(y.tagName);return ko[p.namespaceURI]?p.namespaceURI===yr?y.namespaceURI===Ke?A==="svg":y.namespaceURI===br?A==="svg"&&(X==="annotation-xml"||Io[X]):!!Ma[A]:p.namespaceURI===br?y.namespaceURI===Ke?A==="math":y.namespaceURI===yr?A==="math"&&Co[X]:!!La[A]:p.namespaceURI===Ke?y.namespaceURI===yr&&!Co[X]||y.namespaceURI===br&&!Io[X]?!1:!La[A]&&(zu[A]||!Ma[A]):!!(Mn==="application/xhtml+xml"&&ko[p.namespaceURI]):!1},Fe=function(p){wn(e.removed,{element:p});try{S(p).removeChild(p)}catch{d(p)}},At=function(p,y){try{wn(e.removed,{attribute:y.getAttributeNode(p),from:y})}catch{wn(e.removed,{attribute:null,from:y})}if(y.removeAttribute(p),p==="is")if(en||gr)try{Fe(y)}catch{}else try{y.setAttribute(p,"")}catch{}},Pa=function(p){let y=null,A=null;if(To)p="<remove></remove>"+p;else{let J=Wc(p,/^[\r\n\t ]+/);A=J&&J[0]}Mn==="application/xhtml+xml"&&nn===Ke&&(p='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+p+"</body></html>");let X=U?U.createHTML(p):p;if(nn===Ke)try{y=new f().parseFromString(X,Mn)}catch{}if(!y||!y.documentElement){y=vo.createDocument(nn,"template",null);try{y.documentElement.innerHTML=Ao?we:X}catch{}}let V=y.body||y.documentElement;return p&&A&&V.insertBefore(n.createTextNode(A),V.childNodes[0]||null),nn===Ke?Pu.call(y,_t?"html":"body")[0]:_t?y.documentElement:V},Da=function(p){return xa.call(p.ownerDocument||p,p,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ua=function(p){p.normalize();let y=xa.call(p.ownerDocument||p,p,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),A=y.nextNode();for(;A;){let X=A.data;Sn([pr,fr,hr],V=>{X=_n(X,V," ")}),A.data=X,A=y.nextNode()}},xr=function(p){let y=P?P(p):null;return typeof y!="string"||le(y)!=="form"?!1:typeof p.nodeName!="string"||typeof p.textContent!="string"||typeof p.removeChild!="function"||p.attributes!==I(p)||typeof p.removeAttribute!="function"||typeof p.setAttribute!="function"||typeof p.namespaceURI!="string"||typeof p.insertBefore!="function"||typeof p.hasChildNodes!="function"||p.nodeType!==D(p)||p.childNodes!==x(p)},Ln=function(p){if(!D||typeof p!="object"||p===null)return!1;try{return D(p)===it.documentFragment}catch{return!1}},Er=function(p){if(!D||typeof p!="object"||p===null)return!1;try{return typeof D(p)=="number"}catch{return!1}};function at(N,p,y){Sn(N,A=>{A.call(e,p,y,rn)})}let Ha=function(p){let y=null;if(at(fe.beforeSanitizeElements,p,null),xr(p))return Fe(p),!0;let A=le(p.nodeName);if(at(fe.uponSanitizeElement,p,{tagName:A,allowedTags:se}),Rn&&p.hasChildNodes()&&!Er(p.firstElementChild)&&xe(/<[/\w!]/g,p.innerHTML)&&xe(/<[/\w!]/g,p.textContent)||Rn&&p.namespaceURI===Ke&&A==="style"&&Er(p.firstElementChild)||p.nodeType===it.progressingInstruction||Rn&&p.nodeType===it.comment&&xe(/<[/\w]/g,p.data))return Fe(p),!0;if(Nn[A]||!(gt.tagCheck instanceof Function&>.tagCheck(A))&&!se[A]){if(!Nn[A]&&Fa(A)&&(ae.tagNameCheck instanceof RegExp&&xe(ae.tagNameCheck,A)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(A)))return!1;if(So&&!Xe[A]){let V=S(p),J=x(p);if(J&&V){let Me=J.length;for(let Ze=Me-1;Ze>=0;--Ze){let $e=h(J[Ze],!0);V.insertBefore($e,g(p))}}}return Fe(p),!0}return(D?D(p):p.nodeType)===it.element&&!Wu(p)||(A==="noscript"||A==="noembed"||A==="noframes")&&xe(/<\/no(script|embed|frames)/i,p.innerHTML)?(Fe(p),!0):(vt&&p.nodeType===it.text&&(y=p.textContent,Sn([pr,fr,hr],V=>{y=_n(y,V," ")}),p.textContent!==y&&(wn(e.removed,{element:p.cloneNode()}),p.textContent=y)),at(fe.afterSanitizeElements,p,null),!1)},Ga=function(p,y,A){if(mr[y]||Aa&&(y==="id"||y==="name")&&(A in n||A in ju))return!1;let X=ue[y]||gt.attributeCheck instanceof Function&>.attributeCheck(y,p);if(!(xo&&!mr[y]&&xe(Uu,y))){if(!(Sa&&xe(Hu,y))){if(!X||mr[y]){if(!(Fa(p)&&(ae.tagNameCheck instanceof RegExp&&xe(ae.tagNameCheck,p)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(p))&&(ae.attributeNameCheck instanceof RegExp&&xe(ae.attributeNameCheck,y)||ae.attributeNameCheck instanceof Function&&ae.attributeNameCheck(y,p))||y==="is"&&ae.allowCustomizedBuiltInElements&&(ae.tagNameCheck instanceof RegExp&&xe(ae.tagNameCheck,A)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(A))))return!1}else if(!_o[y]){if(!xe(Ta,_n(A,Ea,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&p!=="script"&&qc(A,"data:")===0&&Ca[p])){if(!(wa&&!xe(Gu,_n(A,Ea,"")))){if(A)return!1}}}}}}return!0},qu=F({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Fa=function(p){return!qu[rr(p)]&&xe(Fu,p)},$a=function(p){at(fe.beforeSanitizeAttributes,p,null);let y=p.attributes;if(!y||xr(p))return;let A={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ue,forceKeepAttr:void 0},X=y.length;for(;X--;){let V=y[X],J=V.name,Me=V.namespaceURI,Ze=V.value,$e=le(J),Ro=Ze,he=J==="value"?Ro:Sm(Ro);if(A.attrName=$e,A.attrValue=he,A.keepAttr=!0,A.forceKeepAttr=void 0,at(fe.uponSanitizeAttribute,p,A),he=A.attrValue,ka&&($e==="id"||$e==="name")&&qc(he,Ia)!==0&&(At(J,p),he=Ia+he),Rn&&xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,he)){At(J,p);continue}if($e==="attributename"&&Wc(he,"href")){At(J,p);continue}if(A.forceKeepAttr)continue;if(!A.keepAttr){At(J,p);continue}if(!_a&&xe(/\/>/i,he)){At(J,p);continue}vt&&Sn([pr,fr,hr],Ba=>{he=_n(he,Ba," ")});let za=le(p.nodeName);if(!Ga(za,$e,he)){At(J,p);continue}if(U&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Me)switch(m.getAttributeType(za,$e)){case"TrustedHTML":{he=U.createHTML(he);break}case"TrustedScriptURL":{he=U.createScriptURL(he);break}}if(he!==Ro)try{Me?p.setAttributeNS(Me,J,he):p.setAttribute(J,he),xr(p)?Fe(p):jc(e.removed)}catch{At(J,p)}}at(fe.afterSanitizeAttributes,p,null)},Tr=function(p){let y=null,A=Da(p);for(at(fe.beforeSanitizeShadowDOM,p,null);y=A.nextNode();)if(at(fe.uponSanitizeShadowNode,y,null),Ha(y),$a(y),Ln(y.content)&&Tr(y.content),(D?D(y):y.nodeType)===it.element){let V=E?E(y):y.shadowRoot;Ln(V)&&(on(V),Tr(V))}at(fe.afterSanitizeShadowDOM,p,null)},on=function(p){let y=D?D(p):p.nodeType;if(y===it.element){let V=E?E(p):p.shadowRoot;Ln(V)&&(on(V),Tr(V))}let A=x?x(p):p.childNodes;if(!A)return;let X=[];Sn(A,V=>{wn(X,V)});for(let V of X)on(V);if(y===it.element){let V=P?P(p):null;if(typeof V=="string"&&le(V)==="template"){let J=p.content;Ln(J)&&on(J)}}};return e.sanitize=function(N){let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,A=null,X=null,V=null;if(Ao=!N,Ao&&(N="<!-->"),typeof N!="string"&&!Er(N)&&(N=Im(N),typeof N!="string"))throw nr("dirty is not a string, aborting");if(!e.isSupported)return N;if(Eo||No(p),e.removed=[],typeof N=="string"&&(On=!1),On){let Ze=P?P(N):N.nodeName;if(typeof Ze=="string"){let $e=le(Ze);if(!se[$e]||Nn[$e])throw nr("root node is forbidden and cannot be sanitized in-place")}if(xr(N))throw nr("root node is clobbered and cannot be sanitized in-place");on(N)}else if(Er(N))y=Pa("<!---->"),A=y.ownerDocument.importNode(N,!0),A.nodeType===it.element&&A.nodeName==="BODY"||A.nodeName==="HTML"?y=A:y.appendChild(A),on(A);else{if(!en&&!vt&&!_t&&N.indexOf("<")===-1)return U&&vr?U.createHTML(N):N;if(y=Pa(N),!y)return en?null:vr?we:""}y&&To&&Fe(y.firstChild);let J=Da(On?N:y);for(;X=J.nextNode();)Ha(X),$a(X),Ln(X.content)&&Tr(X.content);if(On)return vt&&Ua(N),N;if(en){if(vt&&Ua(y),gr)for(V=Lu.call(y.ownerDocument);y.firstChild;)V.appendChild(y.firstChild);else V=y;return(ue.shadowroot||ue.shadowrootmode)&&(V=Du.call(r,V,!0)),V}let Me=_t?y.outerHTML:y.innerHTML;return _t&&se["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&xe(Gm,y.ownerDocument.doctype.name)&&(Me="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
|
|
13
|
+
`+Me),vt&&Sn([pr,fr,hr],Ze=>{Me=_n(Me,Ze," ")}),U&&vr?U.createHTML(Me):Me},e.setConfig=function(){let N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};No(N),Eo=!0},e.clearConfig=function(){rn=null,Eo=!1},e.isValidAttribute=function(N,p,y){rn||No({});let A=le(N),X=le(p);return Ga(A,X,y)},e.addHook=function(N,p){typeof p=="function"&&wn(fe[N],p)},e.removeHook=function(N,p){if(p!==void 0){let y=Em(fe[N],p);return y===-1?void 0:Tm(fe[N],y,1)[0]}return jc(fe[N])},e.removeHooks=function(N){fe[N]=[]},e.removeAllHooks=function(){fe=tu()},e}var ou=iu();function ia(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Qt=ia();function fu(t){Qt=t}var Yt={exec:()=>null};function kn(t){let e=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=e[r];return i||(i=t(r),e[r]=i),i}}function W(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(i,o)=>{let s=typeof o=="string"?o:o.source;return s=s.replace(Se.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,e)};return r}var Bm=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Se={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:kn(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:kn(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:kn(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:kn(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:kn(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:kn(t=>new RegExp(`^ {0,${t}}>`))},Vm=/^(?:[ \t]*(?:\n|$))+/,jm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Wm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,sr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,qm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,oa=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,hu=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,mu=W(hu).replace(/bull/g,oa).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Xm=W(hu).replace(/bull/g,oa).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),sa=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Km=/^[^\n]+/,aa=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Zm=W(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",aa).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ym=W(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,oa).getRegex(),so="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",la=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Jm=W("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",la).replace("tag",so).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),gu=W(sa).replace("hr",sr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",so).getRegex(),Qm=W(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",gu).getRegex(),ca={blockquote:Qm,code:jm,def:Zm,fences:Wm,heading:qm,hr:sr,html:Jm,lheading:mu,list:Ym,newline:Vm,paragraph:gu,table:Yt,text:Km},su=W("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",sr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",so).getRegex(),eg={...ca,lheading:Xm,table:su,paragraph:W(sa).replace("hr",sr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",su).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",so).getRegex()},tg={...ca,html:W(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",la).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Yt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:W(sa).replace("hr",sr).replace("heading",` *#{1,6} *[^
|
|
14
|
+
]`).replace("lheading",mu).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ng=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,rg=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,vu=/^( {2,}|\\)\n(?!\s*$)/,ig=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,In=/[\p{P}\p{S}]/u,ao=/[\s\p{P}\p{S}]/u,ua=/[^\s\p{P}\p{S}]/u,og=W(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ao).getRegex(),bu=/(?!~)[\p{P}\p{S}]/u,sg=/(?!~)[\s\p{P}\p{S}]/u,ag=/(?:[^\s\p{P}\p{S}]|~)/u,lg=W(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Bm?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),yu=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,cg=W(yu,"u").replace(/punct/g,In).getRegex(),ug=W(yu,"u").replace(/punct/g,bu).getRegex(),xu="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",dg=W(xu,"gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,ao).replace(/punct/g,In).getRegex(),pg=W(xu,"gu").replace(/notPunctSpace/g,ag).replace(/punctSpace/g,sg).replace(/punct/g,bu).getRegex(),fg=W("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,ao).replace(/punct/g,In).getRegex(),hg=W(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,In).getRegex(),mg="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",gg=W(mg,"gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,ao).replace(/punct/g,In).getRegex(),vg=W(/\\(punct)/,"gu").replace(/punct/g,In).getRegex(),bg=W(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),yg=W(la).replace("(?:-->|$)","-->").getRegex(),xg=W("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",yg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ro=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Eg=W(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ro).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Eu=W(/^!?\[(label)\]\[(ref)\]/).replace("label",ro).replace("ref",aa).getRegex(),Tu=W(/^!?\[(ref)\](?:\[\])?/).replace("ref",aa).getRegex(),Tg=W("reflink|nolink(?!\\()","g").replace("reflink",Eu).replace("nolink",Tu).getRegex(),au=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,da={_backpedal:Yt,anyPunctuation:vg,autolink:bg,blockSkip:lg,br:vu,code:rg,del:Yt,delLDelim:Yt,delRDelim:Yt,emStrongLDelim:cg,emStrongRDelimAst:dg,emStrongRDelimUnd:fg,escape:ng,link:Eg,nolink:Tu,punctuation:og,reflink:Eu,reflinkSearch:Tg,tag:xg,text:ig,url:Yt},Sg={...da,link:W(/^!?\[(label)\]\((.*?)\)/).replace("label",ro).getRegex(),reflink:W(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ro).getRegex()},ta={...da,emStrongRDelimAst:pg,emStrongLDelim:ug,delLDelim:hg,delRDelim:gg,url:W(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",au).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:W(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",au).getRegex()},wg={...ta,br:W(vu).replace("{2,}","*").getRegex(),text:W(ta.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},no={normal:ca,gfm:eg,pedantic:tg},ir={normal:da,gfm:ta,breaks:wg,pedantic:Sg},_g={"&":"&","<":"<",">":">",'"':""","'":"'"},lu=t=>_g[t];function st(t,e){if(e){if(Se.escapeTest.test(t))return t.replace(Se.escapeReplace,lu)}else if(Se.escapeTestNoEncode.test(t))return t.replace(Se.escapeReplaceNoEncode,lu);return t}function cu(t){try{t=encodeURI(t).replace(Se.percentDecode,"%")}catch{return null}return t}function uu(t,e){let n=t.replace(Se.findPipe,(o,s,a)=>{let l=!1,c=s;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(Se.splitPipe),i=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;i<r.length;i++)r[i]=r[i].trim().replace(Se.slashPipe,"|");return r}function wt(t,e,n){let r=t.length;if(r===0)return"";let i=0;for(;i<r;){let o=t.charAt(r-i-1);if(o===e&&!n)i++;else if(o!==e&&n)i++;else break}return t.slice(0,r-i)}function du(t){let e=t.split(`
|
|
15
15
|
`),n=e.length-1;for(;n>=0&&Se.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
|
|
16
|
-
`)}function
|
|
17
|
-
`).map(
|
|
18
|
-
`)}var
|
|
16
|
+
`)}function Ag(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function kg(t,e=0){let n=e,r="";for(let i of t)if(i===" "){let o=4-n%4;r+=" ".repeat(o),n+=o}else r+=i,n++;return r}function pu(t,e,n,r,i){let o=e.href,s=e.title||null,a=t[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:s,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}function Ig(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let i=r[1];return e.split(`
|
|
17
|
+
`).map(o=>{let s=o.match(n.other.beginningSpace);if(s===null)return o;let[a]=s;return a.length>=i.length?o.slice(i.length):o}).join(`
|
|
18
|
+
`)}var io=class{options;rules;lexer;constructor(t){this.options=t||Qt}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=this.options.pedantic?e[0]:du(e[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=Ig(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=wt(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:wt(e[0],`
|
|
19
19
|
`),depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:wt(e[0],`
|
|
20
20
|
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=wt(e[0],`
|
|
21
21
|
`).split(`
|
|
22
|
-
`),r="",
|
|
23
|
-
`),
|
|
22
|
+
`),r="",i="",o=[];for(;n.length>0;){let s=!1,a=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))a.push(n[l]),s=!0;else if(!s)a.push(n[l]);else break;n=n.slice(l);let c=a.join(`
|
|
23
|
+
`),f=c.replace(this.rules.other.blockquoteSetextReplace,`
|
|
24
24
|
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
|
|
25
|
-
${c}`:c,
|
|
26
|
-
${
|
|
25
|
+
${c}`:c,i=i?`${i}
|
|
26
|
+
${f}`:f;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(f,o,!0),this.lexer.state.top=m,n.length===0)break;let b=o.at(-1);if(b?.type==="code")break;if(b?.type==="blockquote"){let h=b,d=h.raw+`
|
|
27
27
|
`+n.join(`
|
|
28
|
-
`),g=this.blockquote(d);
|
|
28
|
+
`),g=this.blockquote(d);o[o.length-1]=g,r=r.substring(0,r.length-h.raw.length)+g.raw,i=i.substring(0,i.length-h.text.length)+g.text;break}else if(b?.type==="list"){let h=b,d=h.raw+`
|
|
29
29
|
`+n.join(`
|
|
30
|
-
`),g=this.list(d);
|
|
31
|
-
`);continue}}return{type:"blockquote",raw:r,tokens:
|
|
30
|
+
`),g=this.list(d);o[o.length-1]=g,r=r.substring(0,r.length-b.raw.length)+g.raw,i=i.substring(0,i.length-h.raw.length)+g.raw,n=d.substring(o.at(-1).raw.length).split(`
|
|
31
|
+
`);continue}}return{type:"blockquote",raw:r,tokens:o,text:i}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let o=this.rules.other.listItemRegex(n),s=!1;for(;t;){let l=!1,c="",f="";if(!(e=o.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let m=kg(e[2].split(`
|
|
32
32
|
`,1)[0],e[1].length),b=t.split(`
|
|
33
|
-
`,1)[0],h=!m.trim(),d=0;if(this.options.pedantic?(d=2,
|
|
33
|
+
`,1)[0],h=!m.trim(),d=0;if(this.options.pedantic?(d=2,f=m.trimStart()):h?d=e[1].length+1:(d=m.search(this.rules.other.nonSpaceChar),d=d>4?1:d,f=m.slice(d),d+=e[1].length),h&&this.rules.other.blankLine.test(b)&&(c+=b+`
|
|
34
34
|
`,t=t.substring(b.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(d),x=this.rules.other.hrRegex(d),S=this.rules.other.fencesBeginRegex(d),E=this.rules.other.headingBeginRegex(d),I=this.rules.other.htmlBeginRegex(d),D=this.rules.other.blockquoteBeginRegex(d);for(;t;){let P=t.split(`
|
|
35
|
-
`,1)[0],U;if(b=P,this.options.pedantic?(b=b.replace(this.rules.other.listReplaceNesting," "),U=b):U=b.replace(this.rules.other.tabCharGlobal," "),S.test(b)||E.test(b)||I.test(b)||D.test(b)||g.test(b)||x.test(b))break;if(U.search(this.rules.other.nonSpaceChar)>=d||!b.trim())
|
|
36
|
-
`+U.slice(d);else{if(h||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(m)||E.test(m)||x.test(m))break;
|
|
35
|
+
`,1)[0],U;if(b=P,this.options.pedantic?(b=b.replace(this.rules.other.listReplaceNesting," "),U=b):U=b.replace(this.rules.other.tabCharGlobal," "),S.test(b)||E.test(b)||I.test(b)||D.test(b)||g.test(b)||x.test(b))break;if(U.search(this.rules.other.nonSpaceChar)>=d||!b.trim())f+=`
|
|
36
|
+
`+U.slice(d);else{if(h||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(m)||E.test(m)||x.test(m))break;f+=`
|
|
37
37
|
`+b}h=!b.trim(),c+=P+`
|
|
38
|
-
`,t=t.substring(P.length+1),m=U.slice(d)}}
|
|
39
|
-
`),href:r,title:
|
|
40
|
-
`):[],
|
|
41
|
-
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?
|
|
38
|
+
`,t=t.substring(P.length+1),m=U.slice(d)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),i.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(f),loose:!1,text:f,tokens:[]}),i.raw+=c}let a=i.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let f=this.rules.other.listTaskCheckbox.exec(l.raw);if(f){let m={type:"checkbox",raw:f[0]+" ",checked:f[0]!=="[ ]"};l.checked=m.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=m.raw+l.tokens[0].raw,l.tokens[0].text=m.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(m)):l.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):l.tokens.unshift(m)}}else l.task&&(l.task=!1);if(!i.loose){let f=l.tokens.filter(b=>b.type==="space"),m=f.length>0&&f.some(b=>this.rules.other.anyLine.test(b.raw));i.loose=m}}if(i.loose)for(let l of i.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return i}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=du(e[0]);return{type:"html",block:!0,raw:n,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:n}}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:wt(e[0],`
|
|
39
|
+
`),href:r,title:i}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=uu(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
40
|
+
`):[],o={type:"table",raw:wt(e[0],`
|
|
41
|
+
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?o.align.push("right"):this.rules.other.tableAlignCenter.test(s)?o.align.push("center"):this.rules.other.tableAlignLeft.test(s)?o.align.push("left"):o.align.push(null);for(let s=0;s<n.length;s++)o.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:o.align[s]});for(let s of i)o.rows.push(uu(s,o.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[l]})));return o}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:wt(e[0],`
|
|
42
42
|
`),depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
|
|
43
|
-
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let
|
|
44
|
-
`),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Se.tabCharGlobal," ").replace(Se.spaceLine,""));let
|
|
45
|
-
`:n.push(
|
|
43
|
+
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let o=wt(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=Ag(e[2],"()");if(o===-2)return;if(o>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+o;e[2]=e[2].substring(0,o),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let r=e[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],i=o[3])}else i=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),pu(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=e[r.toLowerCase()];if(!i){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return pu(n,i,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,a=i,l=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*t.length+i);(r=c.exec(e))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(s=[...o].length,r[3]||r[4]){a+=s;continue}else if((r[5]||r[6])&&i%3&&!((i+s)%3)){l+=s;continue}if(a-=s,a>0)continue;s=Math.min(s,s+a+l);let f=[...r[0]][0].length,m=t.slice(0,i+r.index+f+s);if(Math.min(i,s)%2){let h=m.slice(1,-1);return{type:"em",raw:m,text:h,tokens:this.lexer.inlineTokens(h)}}let b=m.slice(2,-2);return{type:"strong",raw:m,text:b,tokens:this.lexer.inlineTokens(b)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,a=i,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+i);(r=l.exec(e))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o||(s=[...o].length,s!==i))continue;if(r[3]||r[4]){a+=s;continue}if(a-=s,a>0)continue;s=Math.min(s,s+a);let c=[...r[0]][0].length,f=t.slice(0,i+r.index+c+s),m=f.slice(i,-i);return{type:"del",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let i;do i=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(i!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},We=class na{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Qt,this.options.tokenizer=this.options.tokenizer||new io,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:Se,block:no.normal,inline:ir.normal};this.options.pedantic?(n.block=no.pedantic,n.inline=ir.pedantic):this.options.gfm&&(n.block=no.gfm,this.options.breaks?n.inline=ir.breaks:n.inline=ir.gfm),this.tokenizer.rules=n}static get rules(){return{block:no,inline:ir}}static lex(e,n){return new na(n).lex(e)}static lexInline(e,n){return new na(n).inlineTokens(e)}lex(e){e=e.replace(Se.carriageReturn,`
|
|
44
|
+
`),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Se.tabCharGlobal," ").replace(Se.spaceLine,""));let i=1/0;for(;e;){if(e.length<i)i=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},e,n))?(e=e.substring(o.raw.length),n.push(o),!0):!1))continue;if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length);let a=n.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
|
|
45
|
+
`:n.push(o);continue}if(o=this.tokenizer.code(e)){e=e.substring(o.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
46
46
|
`)?"":`
|
|
47
|
-
`)+
|
|
48
|
-
`+
|
|
47
|
+
`)+o.raw,a.text+=`
|
|
48
|
+
`+o.text,this.inlineQueue.at(-1).src=a.text):n.push(o);continue}if(o=this.tokenizer.fences(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.heading(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.hr(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.blockquote(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.list(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.html(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.def(e)){e=e.substring(o.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
49
49
|
`)?"":`
|
|
50
|
-
`)+
|
|
51
|
-
`+
|
|
50
|
+
`)+o.raw,a.text+=`
|
|
51
|
+
`+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},n.push(o));continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),n.push(o);continue}let s=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),c;this.options.extensions.startBlock.forEach(f=>{c=f.call({lexer:this},l),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(s=e.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(s))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
|
|
52
52
|
`)?"":`
|
|
53
|
-
`)+
|
|
54
|
-
`+
|
|
53
|
+
`)+o.raw,a.text+=`
|
|
54
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(o),r=s.length!==e.length,e=e.substring(o.raw.length);continue}if(o=this.tokenizer.text(e)){e=e.substring(o.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
55
55
|
`)?"":`
|
|
56
|
-
`)+
|
|
57
|
-
`+
|
|
58
|
-
`;return r?'<pre><code class="language-'+st(r)+'">'+(n?
|
|
59
|
-
`:"<pre><code>"+(n?
|
|
56
|
+
`)+o.raw,a.text+=`
|
|
57
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(o);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e,i=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)c.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)o=i[2]?i[2].length:0,r=r.slice(0,i.index+o)+"["+"a".repeat(i[0].length-o-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let s=!1,a="",l=1/0;for(;e;){if(e.length<l)l=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}s||(a=""),s=!1;let c;if(this.options.extensions?.inline?.some(m=>(c=m.call({lexer:this},e,n))?(e=e.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(c.raw.length);let m=n.at(-1);c.type==="text"&&m?.type==="text"?(m.raw+=c.raw,m.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(e,r,a)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(e,r,a)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(e)){e=e.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(e))){e=e.substring(c.raw.length),n.push(c);continue}let f=e;if(this.options.extensions?.startInline){let m=1/0,b=e.slice(1),h;this.options.extensions.startInline.forEach(d=>{h=d.call({lexer:this},b),typeof h=="number"&&h>=0&&(m=Math.min(m,h))}),m<1/0&&m>=0&&(f=e.substring(0,m+1))}if(c=this.tokenizer.inlineText(f)){e=e.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(a=c.raw.slice(-1)),s=!0;let m=n.at(-1);m?.type==="text"?(m.raw+=c.raw,m.text+=c.text):n.push(c);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}infiniteLoopError(e){let n="Infinite loop on byte: "+e;if(this.options.silent)console.error(n);else throw new Error(n)}},oo=class{options;parser;constructor(t){this.options=t||Qt}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(Se.notSpaceStart)?.[0],i=t.replace(Se.endingNewline,"")+`
|
|
58
|
+
`;return r?'<pre><code class="language-'+st(r)+'">'+(n?i:st(i,!0))+`</code></pre>
|
|
59
|
+
`:"<pre><code>"+(n?i:st(i,!0))+`</code></pre>
|
|
60
60
|
`}blockquote({tokens:t}){return`<blockquote>
|
|
61
61
|
${this.parser.parse(t)}</blockquote>
|
|
62
62
|
`}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
|
|
63
63
|
`}hr(t){return`<hr>
|
|
64
|
-
`}list(t){let e=t.ordered,n=t.start,r="";for(let s=0;s<t.items.length;s++){let a=t.items[s];r+=this.listitem(a)}let
|
|
65
|
-
`+r+"</"+
|
|
64
|
+
`}list(t){let e=t.ordered,n=t.start,r="";for(let s=0;s<t.items.length;s++){let a=t.items[s];r+=this.listitem(a)}let i=e?"ol":"ul",o=e&&n!==1?' start="'+n+'"':"";return"<"+i+o+`>
|
|
65
|
+
`+r+"</"+i+`>
|
|
66
66
|
`}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
|
|
67
67
|
`}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
|
|
68
|
-
`}table(t){let e="",n="";for(let
|
|
68
|
+
`}table(t){let e="",n="";for(let i=0;i<t.header.length;i++)n+=this.tablecell(t.header[i]);e+=this.tablerow({text:n});let r="";for(let i=0;i<t.rows.length;i++){let o=t.rows[i];n="";for(let s=0;s<o.length;s++)n+=this.tablecell(o[s]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
|
|
69
69
|
<thead>
|
|
70
70
|
`+e+`</thead>
|
|
71
71
|
`+r+`</table>
|
|
72
72
|
`}tablerow({text:t}){return`<tr>
|
|
73
73
|
${t}</tr>
|
|
74
74
|
`}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
|
|
75
|
-
`}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${st(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),
|
|
76
|
-
Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+st(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},Jt=new
|
|
75
|
+
`}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${st(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),i=cu(t);if(i===null)return r;t=i;let o='<a href="'+t+'"';return e&&(o+=' title="'+st(e)+'"'),o+=">"+r+"</a>",o}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=cu(t);if(i===null)return st(n);t=i;let o=`<img src="${t}" alt="${st(n)}"`;return e&&(o+=` title="${st(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:st(t.text)}},pa=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},qe=class ra{options;renderer;textRenderer;constructor(e){this.options=e||Qt,this.options.renderer=this.options.renderer||new oo,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new pa}static parse(e,n){return new ra(n).parse(e)}static parseInline(e,n){return new ra(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let s=i,a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(s.type)){n+=a||"";continue}}let o=i;switch(o.type){case"space":{n+=this.renderer.space(o);break}case"hr":{n+=this.renderer.hr(o);break}case"heading":{n+=this.renderer.heading(o);break}case"code":{n+=this.renderer.code(o);break}case"table":{n+=this.renderer.table(o);break}case"blockquote":{n+=this.renderer.blockquote(o);break}case"list":{n+=this.renderer.list(o);break}case"checkbox":{n+=this.renderer.checkbox(o);break}case"html":{n+=this.renderer.html(o);break}case"def":{n+=this.renderer.def(o);break}case"paragraph":{n+=this.renderer.paragraph(o);break}case"text":{n+=this.renderer.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<e.length;i++){let o=e[i];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){r+=a||"";continue}}let s=o;switch(s.type){case"escape":{r+=n.text(s);break}case"html":{r+=n.html(s);break}case"link":{r+=n.link(s);break}case"image":{r+=n.image(s);break}case"checkbox":{r+=n.checkbox(s);break}case"strong":{r+=n.strong(s);break}case"em":{r+=n.em(s);break}case"codespan":{r+=n.codespan(s);break}case"br":{r+=n.br(s);break}case"del":{r+=n.del(s);break}case"text":{r+=n.text(s);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}},or=class{options;block;constructor(t){this.options=t||Qt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?We.lex:We.lexInline}provideParser(t=this.block){return t?qe.parse:qe.parseInline}},fa=class{defaults=ia();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=qe;Renderer=oo;TextRenderer=pa;Lexer=We;Tokenizer=io;Hooks=or;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let i=r;for(let o of i.header)n=n.concat(this.walkTokens(o.tokens,e));for(let o of i.rows)for(let s of o)n=n.concat(this.walkTokens(s.tokens,e));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,e));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let s=i[o].flat(1/0);n=n.concat(this.walkTokens(s,e))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=e.renderers[i.name];o?e.renderers[i.name]=function(...s){let a=i.renderer.apply(this,s);return a===!1&&(a=o.apply(this,s)),a}:e.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=e[i.level];o?o.unshift(i.tokenizer):e[i.level]=[i.tokenizer],i.start&&(i.level==="block"?e.startBlock?e.startBlock.push(i.start):e.startBlock=[i.start]:i.level==="inline"&&(e.startInline?e.startInline.push(i.start):e.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(e.childTokens[i.name]=i.childTokens)}),r.extensions=e),n.renderer){let i=this.defaults.renderer||new oo(this.defaults);for(let o in n.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,a=n.renderer[s],l=i[s];i[s]=(...c)=>{let f=a.apply(i,c);return f===!1&&(f=l.apply(i,c)),f||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new io(this.defaults);for(let o in n.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,a=n.tokenizer[s],l=i[s];i[s]=(...c)=>{let f=a.apply(i,c);return f===!1&&(f=l.apply(i,c)),f}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new or;for(let o in n.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,a=n.hooks[s],l=i[s];or.passThroughHooks.has(o)?i[s]=c=>{if(this.defaults.async&&or.passThroughHooksRespectAsync.has(o))return(async()=>{let m=await a.call(i,c);return l.call(i,m)})();let f=a.call(i,c);return l.call(i,f)}:i[s]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(i,c);return m===!1&&(m=await l.apply(i,c)),m})();let f=a.apply(i,c);return f===!1&&(f=l.apply(i,c)),f}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,o=n.walkTokens;r.walkTokens=function(s){let a=[];return a.push(o.call(this,s)),i&&(a=a.concat(i.call(this,s))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return We.lex(t,e??this.defaults)}parser(t,e){return qe.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=t),i.async)return(async()=>{let s=i.hooks?await i.hooks.preprocess(e):e,a=await(i.hooks?await i.hooks.provideLexer(t):t?We.lex:We.lexInline)(s,i),l=i.hooks?await i.hooks.processAllTokens(a):a;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let c=await(i.hooks?await i.hooks.provideParser(t):t?qe.parse:qe.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(c):c})().catch(o);try{i.hooks&&(e=i.hooks.preprocess(e));let s=(i.hooks?i.hooks.provideLexer(t):t?We.lex:We.lexInline)(e,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let a=(i.hooks?i.hooks.provideParser(t):t?qe.parse:qe.parseInline)(s,i);return i.hooks&&(a=i.hooks.postprocess(a)),a}catch(s){return o(s)}}}onError(t,e){return n=>{if(n.message+=`
|
|
76
|
+
Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+st(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},Jt=new fa;function Z(t,e){return Jt.parse(t,e)}Z.options=Z.setOptions=function(t){return Jt.setOptions(t),Z.defaults=Jt.defaults,fu(Z.defaults),Z};Z.getDefaults=ia;Z.defaults=Qt;Z.use=function(...t){return Jt.use(...t),Z.defaults=Jt.defaults,fu(Z.defaults),Z};Z.walkTokens=function(t,e){return Jt.walkTokens(t,e)};Z.parseInline=Jt.parseInline;Z.Parser=qe;Z.parser=qe.parse;Z.Renderer=oo;Z.TextRenderer=pa;Z.Lexer=We;Z.lexer=We.lex;Z.Tokenizer=io;Z.Hooks=or;Z.parse=Z;var TS=Z.options,SS=Z.setOptions,wS=Z.use,_S=Z.walkTokens,AS=Z.parseInline;var kS=qe.parse,IS=We.lex;var Cg=new fa({gfm:!0,breaks:!0}),Su=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],wu=["href","title","class"],Ng=[...Su,"img"],Rg=[...wu,"src","alt","width","height"];function lo(t,e){let n=e?.allowImages===!0,r=Cg.parse(t,{async:!1}),i=ou.sanitize(r,{ALLOWED_TAGS:n?Ng:Su,ALLOWED_ATTR:n?Rg:wu}),o=document.createElement("template");o.innerHTML=i;for(let s of o.content.querySelectorAll("a[href]"))s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer");return o.innerHTML.trim()}function _u(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):_u(n,e)}function Au(t){let e=[];_u(t,e);let n=0;for(let{node:r,parent:i}of e){let o=document.createDocumentFragment();for(let s of r.data.split(/(\s+)/)){if(s==="")continue;if(/\s/.test(s)){o.appendChild(document.createTextNode(s));continue}let a=document.createElement("span");a.className="word",a.style.setProperty("--ag-ui-word-index",String(n)),a.textContent=s,o.appendChild(a),n+=1}i.replaceChild(o,r)}}var co=class{chips;palette;#n;#e=[];#t=!1;#i=!1;#r=[];#a=0;constructor(e){this.#n=e,this.chips=document.createElement("div"),this.chips.className="skill-chips",this.chips.setAttribute("part","skill-chips"),this.chips.hidden=!0,this.palette=document.createElement("div"),this.palette.className="skill-palette",this.palette.setAttribute("part","skill-palette"),this.palette.setAttribute("role","listbox"),this.palette.hidden=!0}setSkills(e){this.#e=e,this.#c()}enableChips(e){this.#t=e,this.#c()}enableSlash(e){this.#i=e}isOpen(){return!this.palette.hidden}onInput(e){this.#i&&e.startsWith("/")?this.#s(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#o(1),!0):e.key==="ArrowUp"?(this.#o(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#r.slice(this.#a,this.#a+1).forEach(n=>{this.#l(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#s(e){let n=e.trim().toLowerCase(),r=this.#e.filter(i=>i.name.toLowerCase().includes(n)||i.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#r=r,this.#a=0,this.#p(),this.palette.hidden=!1}#o(e){let n=this.#r.length;this.#a=(this.#a+e+n)%n,this.#p()}#l(e){this.close(),this.#n(e)}#c(){this.chips.replaceChildren();let e=this.#t?this.#e.filter(n=>n.chip===!0):[];this.chips.hidden=e.length===0;for(let n of e){let r=document.createElement("button");r.type="button",r.className="skill-chip",r.setAttribute("part","skill-chip"),r.textContent=n.title,r.addEventListener("click",()=>this.#l(n)),this.chips.appendChild(r)}}#p(){this.palette.replaceChildren(),this.#r.forEach((e,n)=>{let r=document.createElement("button");r.type="button",r.className="skill-item",r.setAttribute("part","skill-item"),r.setAttribute("role","option"),r.setAttribute("aria-selected",n===this.#a?"true":"false");let i=document.createElement("span");if(i.className="skill-item-title",i.setAttribute("part","skill-item-title"),i.textContent=e.title,r.appendChild(i),e.description!==void 0){let o=document.createElement("span");o.className="skill-item-desc",o.setAttribute("part","skill-item-desc"),o.textContent=e.description,r.appendChild(o)}r.addEventListener("click",()=>this.#l(e)),this.palette.appendChild(r)})}};var ku=`
|
|
77
77
|
:host {
|
|
78
78
|
/* Colors */
|
|
79
79
|
--ag-ui-bg: #ffffff;
|
|
@@ -1300,6 +1300,82 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
1300
1300
|
display: none;
|
|
1301
1301
|
}
|
|
1302
1302
|
|
|
1303
|
+
.checkpoints {
|
|
1304
|
+
position: absolute;
|
|
1305
|
+
inset-block-start: 3rem;
|
|
1306
|
+
inset-inline: 0.75rem;
|
|
1307
|
+
z-index: 6;
|
|
1308
|
+
display: flex;
|
|
1309
|
+
flex-direction: column;
|
|
1310
|
+
gap: 0.25rem;
|
|
1311
|
+
padding: 0.5rem;
|
|
1312
|
+
border: 1px solid var(--agui-border, #d7d7dc);
|
|
1313
|
+
border-radius: 0.5rem;
|
|
1314
|
+
background: var(--agui-surface, #fff);
|
|
1315
|
+
box-shadow: 0 6px 24px rgb(0 0 0 / 12%);
|
|
1316
|
+
max-height: 60%;
|
|
1317
|
+
overflow-y: auto;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
.checkpoints[hidden] {
|
|
1321
|
+
display: none;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
.checkpoints-title {
|
|
1325
|
+
font-size: 0.75rem;
|
|
1326
|
+
font-weight: 600;
|
|
1327
|
+
opacity: 0.7;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
.checkpoints-empty {
|
|
1331
|
+
padding: 0.5rem 0.25rem;
|
|
1332
|
+
font-size: 0.8125rem;
|
|
1333
|
+
opacity: 0.7;
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
.checkpoint-row {
|
|
1337
|
+
display: flex;
|
|
1338
|
+
align-items: center;
|
|
1339
|
+
gap: 0.5rem;
|
|
1340
|
+
padding: 0.25rem;
|
|
1341
|
+
border-radius: 0.375rem;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
.checkpoint-row:hover {
|
|
1345
|
+
background: var(--agui-hover, #f3f3f5);
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
.checkpoint-label {
|
|
1349
|
+
flex: 1;
|
|
1350
|
+
font-size: 0.8125rem;
|
|
1351
|
+
white-space: nowrap;
|
|
1352
|
+
overflow: hidden;
|
|
1353
|
+
text-overflow: ellipsis;
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
.checkpoint-branch {
|
|
1357
|
+
font-size: 0.6875rem;
|
|
1358
|
+
padding: 0 0.375rem;
|
|
1359
|
+
border-radius: 999px;
|
|
1360
|
+
background: var(--agui-hover, #f3f3f5);
|
|
1361
|
+
opacity: 0.8;
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
.checkpoint-action {
|
|
1365
|
+
font: inherit;
|
|
1366
|
+
font-size: 0.75rem;
|
|
1367
|
+
cursor: pointer;
|
|
1368
|
+
padding: 0.125rem 0.5rem;
|
|
1369
|
+
border: 1px solid var(--agui-border, #d7d7dc);
|
|
1370
|
+
border-radius: 0.375rem;
|
|
1371
|
+
background: transparent;
|
|
1372
|
+
color: inherit;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
.checkpoint-action:hover {
|
|
1376
|
+
background: var(--agui-hover, #f3f3f5);
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1303
1379
|
.drawer-backdrop {
|
|
1304
1380
|
position: absolute;
|
|
1305
1381
|
inset: 0;
|
|
@@ -1471,11 +1547,11 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
1471
1547
|
border-right: none;
|
|
1472
1548
|
box-shadow: none;
|
|
1473
1549
|
}
|
|
1474
|
-
`;var
|
|
1550
|
+
`;var uo=class{element;#n;#e;#t;#i;#r=!1;constructor(e=ne){this.#i=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="thoughts-toggle",this.#t.setAttribute("part","thoughts-toggle"),this.#t.setAttribute("aria-expanded","true"),this.#n=document.createElement("span"),this.#n.className="thoughts-label",this.#n.setAttribute("part","thoughts-label"),this.#n.textContent=e.thinking,this.#t.append(this.#n),this.#e=document.createElement("pre"),this.#e.className="thoughts-body",this.#e.setAttribute("part","thoughts-body"),this.#t.addEventListener("click",()=>{this.#a(!this.#r)}),this.element.append(this.#t,this.#e)}stream(e){this.#e.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#n.textContent=this.#i.thoughts,this.#a(!0))}#a(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};var po=class{element;#n;#e;#t;#i;#r;#a;#s=[];#o="";#l=null;constructor(e,n=ne){this.#n=e,this.#a=n,this.element=document.createElement("div"),this.element.className="drawer",this.element.setAttribute("part","drawer"),this.element.hidden=!0;let r=document.createElement("div");r.className="drawer-backdrop",r.setAttribute("part","drawer-backdrop"),r.addEventListener("click",()=>this.close()),this.#e=document.createElement("div"),this.#e.className="drawer-panel",this.#e.setAttribute("part","drawer-panel"),this.#e.setAttribute("role","dialog"),this.#e.setAttribute("aria-modal","true"),this.#e.setAttribute("aria-label",n.chatHistory),this.#e.addEventListener("keydown",o=>this.#p(o));let i=document.createElement("div");i.className="drawer-header",i.setAttribute("part","drawer-header"),this.#t=document.createElement("span"),this.#t.className="drawer-title",this.#t.setAttribute("part","drawer-title"),this.#t.textContent=n.chats,this.#i=document.createElement("button"),this.#i.type="button",this.#i.className="drawer-new",this.#i.setAttribute("part","drawer-new"),this.#i.textContent=n.newChat,this.#i.addEventListener("click",()=>{this.close(),this.#n.onNew()}),i.append(this.#t,this.#i),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#e.append(i,this.#r),this.element.append(r,this.#e)}setStrings(e){this.#a=e,this.#e.setAttribute("aria-label",e.chatHistory),this.#t.textContent=e.chats,this.#i.textContent=e.newChat,this.#u()}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#l=this.#c(),this.element.hidden=!1,this.#i.focus())}close(){this.isOpen()&&(this.element.hidden=!0,this.#l?.focus(),this.#l=null)}toggle(){this.isOpen()?this.close():this.open()}#c(){return this.element.getRootNode().activeElement}#p(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let n=Array.from(this.#e.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],i=n[n.length-1],o=this.#c();e.shiftKey&&o===r?(e.preventDefault(),i?.focus()):!e.shiftKey&&o===i&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#s=e,this.#o=n,this.#u()}#u(){if(this.#r.replaceChildren(),this.#s.length===0){let e=document.createElement("div");e.className="drawer-empty",e.setAttribute("part","drawer-empty"),e.textContent=this.#a.noConversations,this.#r.appendChild(e);return}for(let e of this.#s)this.#r.appendChild(this.#h(e))}#h(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#o&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let i=document.createElement("span");i.className="drawer-row-title",i.setAttribute("part","drawer-row-title"),i.textContent=e.title;let o=document.createElement("span");o.className="drawer-row-time",o.setAttribute("part","drawer-row-time"),o.textContent=eo(e.updatedAt,void 0,this.#a);let s=document.createElement("span");s.className="drawer-row-preview",s.setAttribute("part","drawer-row-preview"),s.textContent=e.preview,r.append(i,o,s),r.addEventListener("click",()=>{this.close(),this.#n.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.setAttribute("part","drawer-row-rename"),a.title=this.#a.rename,a.setAttribute("aria-label",this.#a.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#f(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.setAttribute("part","drawer-row-delete"),l.title=this.#a.delete,l.setAttribute("aria-label",this.#a.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#k(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#f(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.setAttribute("part","drawer-rename-input"),r.value=n.title;let i=!1,o=()=>{if(i)return;i=!0;let a=r.value.trim();a===""||a===n.title?this.#u():this.#n.onRename(n.threadId,a)},s=()=>{i||(i=!0,this.#u())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),o()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>o()),e.replaceChildren(r),r.focus(),r.select()}#k(e,n){let r=document.createElement("div");r.className="drawer-confirm",r.setAttribute("part","drawer-confirm");let i=document.createElement("span");i.className="drawer-confirm-label",i.setAttribute("part","drawer-confirm-label"),i.textContent=this.#a.deletePrompt;let o=document.createElement("button");o.type="button",o.className="drawer-confirm-yes",o.setAttribute("part","drawer-confirm-yes"),o.textContent=this.#a.delete,o.addEventListener("click",()=>this.#n.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.setAttribute("part","drawer-confirm-no"),s.textContent=this.#a.cancel,s.addEventListener("click",()=>this.#u()),r.append(i,o,s),e.replaceChildren(r)}};function Iu(t){return{[ce.PENDING]:t.toolRunning,[ce.DONE]:t.toolDone,[ce.ERROR]:t.toolError,[ce.DECLINED]:t.toolDeclined}}function Og(t){return{[ce.DONE]:t.resultLabel,[ce.ERROR]:t.errorLabel,[ce.DECLINED]:t.declinedLabel}}var ar=class{element;#n;#e;#t;#i;#r=!1;constructor(e,n,r=ze.FULL,i,o=ne){this.#e=r,this.#t=n,this.#i=o,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",ce.PENDING),this.element.setAttribute("data-display",r);let s=document.createElement("div");s.className="tool-call-head",s.setAttribute("part","tool-card-head");let a=document.createElement("span");a.className="tool-call-icon",a.setAttribute("part","tool-card-icon"),a.setAttribute("aria-hidden","true");let l=document.createElement("span");if(l.className="tool-call-name",l.setAttribute("part","tool-card-name"),l.textContent=i??e,this.#n=document.createElement("span"),this.#n.className="tool-call-status",this.#n.setAttribute("part","tool-card-status"),this.#n.textContent=Iu(o)[ce.PENDING],s.append(a,l,this.#n),this.element.append(s),r===ze.FULL){let c=document.createElement("pre");c.className="tool-call-args",c.setAttribute("part","tool-card-args"),c.textContent=JSON.stringify(n,null,2),this.element.append(c)}}get settled(){return this.#r}settle(e,n){if(this.#r||(this.#r=!0,this.element.setAttribute("data-status",e),this.#n.textContent=Iu(this.#i)[e],this.#e===ze.MINIMAL))return;let r=document.createElement("button");r.type="button",r.className="tool-call-toggle",r.setAttribute("part","tool-card-toggle"),r.setAttribute("aria-expanded","false");let i=document.createElement("pre");i.className="tool-call-result",i.setAttribute("part","tool-card-result"),i.hidden=!0,this.#e===ze.COMPACT?(r.textContent=this.#i.details,i.textContent=`args: ${JSON.stringify(this.#t)}
|
|
1475
1551
|
|
|
1476
|
-
${n}`):(r.textContent=Ig(this.#i)[e],o.textContent=n),r.addEventListener("click",()=>{let i=o.hidden;o.hidden=!i,r.setAttribute("aria-expanded",String(i))}),this.element.append(r,o)}};var ci=class{element;#n;#e;#t;#i="idle";#r=null;#a=null;#s=[];#o=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??re,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button"),this.element.textContent="\u{1F3A4}",this.#d("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#i==="recording"){this.#c();return}this.#i!=="transcribing"&&await this.#l()}async#l(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#m(this.#t.transcriptionFailed);return}this.#a=e,this.#s=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#s.push(r.data)}),n.addEventListener("stop",()=>{this.#h(n.mimeType)}),this.#r=n,n.start(),this.#d("recording")}#c(){this.#r?.stop()}dispose(){this.#o=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#h(e){if(this.#o)return;this.#u(),this.#d("transcribing");let n=new Blob(this.#s,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#d("idle"),r!==""&&this.#e(r)}catch(r){this.#m(r instanceof Error?r.message:this.#t.transcriptionFailed)}finally{this.#r=null}}#u(){for(let e of this.#a?.getTracks()??[])e.stop();this.#a=null}#m(e){this.#u(),this.#r=null,this.#d("idle"),this.element.title=e}#d(e){this.#i=e,this.element.dataset.state=e;let n=this.#p(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#p(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var ui=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},sr=class{#n;#e;#t;#i;#r;#a;#s;#o;#l=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#i=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#s=e.onPersist??(()=>{}),this.#o=e.connectionLostMessage??"Connection lost"}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:Oe(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#s(this.#n.messages),await this.#c()}async resume(){await this.#c()}addToolResult(e,n){this.#n.addMessage({id:Oe(),role:"tool",content:n,toolCallId:e}),this.#s(this.#n.messages)}cancel(){this.#l=!0,this.#n.abortRun()}async#c(){this.#l=!1;try{await this.#u(),this.#l&&this.#h()}catch(e){this.#l||Cg(e)?this.#h():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#h(){this.#s(this.#n.messages),this.#e.onCancelled()}async#u(){let e;for(let n=0;n<Oi;n+=1){if(this.#l)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#t(),context:this.#i()};if(e!==void 0&&(i.resume=e),await this.#n.runAgent(i,this.#m(r,o)),e=void 0,this.#s(this.#n.messages),this.#l)return;if(!o.terminal)throw new ui(this.#o);if(o.errored)return;if(o.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(o.interrupts);if(this.#l)return;e=Dc(o.interrupts,a);continue}if(this.#r===null||r.length===0)return;let s=!1;for(let a of r){let l=await this.#r(a);if(l!==null){if(l.halt===!0)return;this.#n.addMessage({id:Oe(),role:"tool",content:l.content,toolCallId:a.id}),this.#s(this.#n.messages),s=!0}}if(!s)return}}#m(e,n){let r=this.#e;return{onRunInitialized(){r.onRunStart()},onTextMessageContentEvent({textMessageBuffer:o}){r.onTextDelta(o)},onTextMessageEndEvent({textMessageBuffer:o}){r.onTextEnd(o)},onToolCallEndEvent({event:o,toolCallName:i,toolCallArgs:s}){let a={id:o.toolCallId,name:i,args:s};e.push(a),r.onToolCall(a)},onToolCallResultEvent({event:o}){r.onToolResult(o.toolCallId,o.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:o}){r.onReasoningDelta(o)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(o){n.terminal=!0,o.outcome==="interrupt"&&(n.interrupts=o.interrupts)},onRunErrorEvent({event:o}){n.terminal=!0,n.errored=!0,r.onError(o.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Cg(t){return t instanceof Error&&t.name==="AbortError"}function ua(t){let e=t.attachments;return Array.isArray(e)?e.filter(Ng):[]}function Ng(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.name=="string"&&typeof e.mime=="string"&&typeof e.size=="number"&&(e.url===void 0||typeof e.url=="string")}var da="ag-ui-chat",ar="thread",pa="threads",di="messages:",pi="checkpoint:",Rg=60,Og=100,Mg="New conversation",ht=class{#n;constructor(e=""){this.#n=e===""?da:`${da}@${e}`,e!==""&&this.#a()}threadId(){let e=this.#r(ar),n=sessionStorage.getItem(e);if(n!==null)return n;let r=Oe();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#s(this.#r(di+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(di+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#s(this.#r(pi+e))}saveCheckpoint(e,n){let r=this.#r(pi+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(di+e)),sessionStorage.removeItem(this.#r(pi+e)),this.#i(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(ar))===e&&sessionStorage.removeItem(this.#r(ar))}listThreads(){let e=this.#t().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(this.#r(ar),e)}renameThread(e,n){let r=this.#t(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#i(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),i=Pg(n),s=Date.now();o===void 0?r.push({threadId:e,title:Au(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=Au(n))),this.#i(r)}#t(){return this.#s(this.#r(pa))??[]}#i(e){let n=this.#r(pa);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${da}:`,n=[];for(let r=0;r<sessionStorage.length;r+=1){let o=sessionStorage.key(r);if(o===null||!o.startsWith(e))continue;let i=o.slice(e.length);Lg(i)&&n.push([o,this.#r(i)])}for(let[r,o]of n){let i=sessionStorage.getItem(r);i!==null&&sessionStorage.getItem(o)===null&&sessionStorage.setItem(o,i),sessionStorage.removeItem(r)}}#s(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function Lg(t){return t===ar||t===pa||t.startsWith(di)||t.startsWith(pi)}function Au(t){for(let e of t)if(e.role==="user"){let n=ku(e.content);if(n!=="")return Iu(n,Rg)}return Mg}function Pg(t){for(let e of[...t].reverse()){let n=ku(e.content);if(n!=="")return Iu(n,Og)}return""}function ku(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Iu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function fa(t){return new Uc({url:t.endpoint,headers:t.headers??{},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let o=new Headers(n?.headers);for(let[i,s]of Object.entries(r))o.set(i,s);return fetch(e,{...n,headers:o})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var lr=class{#n;#e;#t;#i=new Set;#r=new Map;constructor(e,n=()=>({}),r=new ht){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r}threadId(){return this.#t.threadId()}setActiveThread(e){this.#t.setActiveThread(e)}saveMessages(e,n){this.#t.saveMessages(e,n)}loadCheckpoint(e){return this.#t.loadCheckpoint(e)}saveCheckpoint(e,n){this.#t.saveCheckpoint(e,n)}renameThread(e,n){this.#t.renameThread(e,n),this.#r.set(e,n),this.#c(e,"PATCH",{title:n})}clear(e){this.#t.clear(e),this.#i.add(e),this.#c(e,"DELETE")}async listThreads(){let e=await this.#a();return e===null?this.#t.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#o(n))}async loadMessages(e){let n=await this.#l(this.#n+encodeURIComponent(e)+"/");if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#s(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#a(){let e=await this.#l(this.#n);if(e===null||!e.ok)return null;let n=await this.#s(e);return n===null?null:n.threads??[]}async#s(e){try{return await e.json()}catch{return null}}#o(e){return{threadId:e.thread_id,title:this.#r.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#l(e){try{return await fetch(e,{headers:this.#e()})}catch{return null}}async#c(e,n,r){let o=this.#e();try{await fetch(this.#n+encodeURIComponent(e)+"/",{method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};async function ha(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,{method:"POST",headers:{...e.headers??{}},body:n});if(!r.ok)throw new Error(await Dg(r));let o=await r.json();if(typeof o=="object"&&o!==null&&typeof o.text=="string")return o.text;throw new Error("transcription returned an unreadable response")}async function Dg(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function ma(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))i.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(Ug(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Hg(i)))}),i.addEventListener("error",()=>r(new Error("upload failed"))),i.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>i.abort()),i.send(o)})}function Ug(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,i=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:o,size:i,url:s}:{id:n,name:r,mime:o,size:i}}function Hg(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var Cu="ag-ui-chat:collapsed",Nu="ag-ui-chat:theme",cr=class extends HTMLElement{agentFactory=fa;headers={};allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#J().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...Wi(this.getPageMap,this.autoInjectPageMap),...this.#we()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new ht;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};strings={};resolvePageTarget=e=>document.querySelector(e);#n={};#e=re;#t=new Dn;#i=new Map;#r=new Set;#a;#s;#o;#l;#c;#h;#u;#m;#d;#p;#g;#M;#E;#T;#A;#w=null;#L;#G=null;#N=[];#R=null;#P=!1;#b=null;#y=null;#F=0;#D=null;#S=null;#k=null;#f="";#I="";#$=0;#z=[];#K=[];#Z=[];#Y=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#s=document.createElement("div"),this.#o=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#h=document.createElement("span"),this.#d=document.createElement("div"),this.#p=document.createElement("button"),this.#g=document.createElement("input"),this.#M=document.createElement("div"),this.#L=document.createElement("span"),this.#E=document.createElement("button"),this.#T=document.createElement("button"),this.#A=document.createElement("div"),this.#u=new si(e=>this.#Ne(e)),this.#m=new li({onSelect:e=>{this.#Re(e)},onNew:()=>{this.newChat(),this.#U()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#U()},onDelete:e=>{this.#Oe(e)}})}static get observedAttributes(){return["title-text"]}attributeChangedCallback(e,n,r){this.#h.textContent=r??this.#e.title}registerTool(e){this.#t.register(e)}registerStateHook(e){for(let n of Ki(e))this.#t.register(n)}#ue(){return this.routeMap.length===0?[]:Xi(()=>this.routeMap,()=>this.navigate)}#de(){let e=this.getPageMap;return e===null?[]:[{name:"read_page",description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[Ne]:"Read the page"},handler:()=>e()}]}#pe(){let e=this.getAttribute("data-page-actions");if(e===null)return[];let n=new Set(e.split(",").map(r=>r.trim()).filter(r=>r!==""));return Vi(n,r=>this.resolvePageTarget(r))}#J(){return[...this.#ue(),...this.#de(),...this.#pe(),...this.#fe()]}#fe(){return this.askUser?[{name:"ask_user",description:"Ask the user a question and wait for their answer. Provide `options` for a multiple-choice prompt; set `allow_custom` to also accept a free-text answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user."},options:{type:"array",items:{type:"string"},description:"Preset choices offered as radio buttons."},allow_custom:{type:"boolean",description:"Allow a free-text answer in addition to any options."}},required:["question"]},handler:e=>this.#he(e)}]:[]}async#he(e){let r={question:typeof e.question=="string"?e.question:""},o=e.options;Array.isArray(o)&&(r.options=o.filter(a=>typeof a=="string")),e.allow_custom===!0&&(r.allowCustom=!0),this.#b=new AbortController;let i=this.#b.signal;this.#x();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await Bs(this.#_(),r,{signal:i,strings:this.#e});return this.#b=null,this.#v(),this.#o.scrollTop=this.#o.scrollHeight,s}#Q(e){let n=this.#J().find(r=>r.name===e);return n!==void 0?n:this.#t.has(e)?this.#t.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===ze.INLINE||e===ze.MINIMAL||e===ze.COMPACT?e:ze.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#I=this.id!==""?this.id:this.endpoint,this.#e=Zi({...this.#me(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#ee(Nu);e!==null&&this.setAttribute("theme",e)}this.#De(),this.#m.setStrings(this.#e),this.#ee(Cu)==="1"&&this.setAttribute("collapsed",""),this.#ie(),this.#ke(),this.#Ae(),this.#I!==""&&this.conversationStore instanceof ht&&(this.conversationStore=new ht(this.#I)),this.#_e(),this.#ge(),this.#be(),this.#f=this.conversationStore.threadId(),this.#ne()}disconnectedCallback(){this.#C(),this.#w?.dispose(),this.#G?.dispose()}#me(){let e=this.getAttribute("data-strings");if(e===null)return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#ge(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#ve(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"";this.#w=new Yo({upload:n,maxBytes:this.#Ee(),accept:r,strings:this.#e}),this.#M.appendChild(this.#w.element),this.#g.accept=r,this.#p.hidden=!1,this.#Se()}#ve(e){return e===null?null:(n,r,o)=>ma(n,{url:e,headers:this.headers,onProgress:r,signal:o})}#be(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#ye(e);n!==null&&(this.#G=new ci({transcribe:n,onText:r=>this.#xe(r),strings:this.#e}),this.#L.appendChild(this.#G.element))}#ye(e){return e===null?null:n=>ha(n,{url:e,headers:this.headers})}#xe(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#se(),this.#l.focus()}#Ee(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Mi;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Mi}#Te(){let e=this.#g.files;if(e!==null)for(let n of Array.from(e))this.#w?.add(n);this.#g.value=""}#Se(){this.#s.addEventListener("dragover",e=>{e.preventDefault(),this.#s.classList.add("chat--dragover")}),this.#s.addEventListener("dragleave",()=>{this.#s.classList.remove("chat--dragover")}),this.#s.addEventListener("drop",e=>{e.preventDefault(),this.#s.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#w?.add(r)})}#we(){return this.#N.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#N.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
|
|
1552
|
+
${n}`):(r.textContent=Og(this.#i)[e],i.textContent=n),r.addEventListener("click",()=>{let o=i.hidden;i.hidden=!o,r.setAttribute("aria-expanded",String(o))}),this.element.append(r,i)}};var fo=class{element;#n;#e;#t;#i="idle";#r=null;#a=null;#s=[];#o=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??ne,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button"),this.element.textContent="\u{1F3A4}",this.#f("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#i==="recording"){this.#c();return}this.#i!=="transcribing"&&await this.#l()}async#l(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#h(this.#t.transcriptionFailed);return}this.#a=e,this.#s=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#s.push(r.data)}),n.addEventListener("stop",()=>{this.#p(n.mimeType)}),this.#r=n,n.start(),this.#f("recording")}#c(){this.#r?.stop()}dispose(){this.#o=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#p(e){if(this.#o)return;this.#u(),this.#f("transcribing");let n=new Blob(this.#s,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#f("idle"),r!==""&&this.#e(r)}catch(r){this.#h(r instanceof Error?r.message:this.#t.transcriptionFailed)}finally{this.#r=null}}#u(){for(let e of this.#a?.getTracks()??[])e.stop();this.#a=null}#h(e){this.#u(),this.#r=null,this.#f("idle"),this.element.title=e}#f(e){this.#i=e,this.element.dataset.state=e;let n=this.#k(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#k(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var ho=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Cn=class{#n;#e;#t;#i;#r;#a;#s;#o;#l=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#i=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#s=e.onPersist??(()=>{}),this.#o=e.connectionLostMessage??"Connection lost";let n=e.onStateChanged;n!==void 0&&this.#n.subscribe({onStateChanged:({state:r})=>{n(r)}})}get state(){return this.#n.state}setState(e){this.#n.setState({...e})}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:Oe(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#s(this.#n.messages),await this.#c()}async resume(){await this.#c()}addToolResult(e,n){this.#n.addMessage({id:Oe(),role:"tool",content:n,toolCallId:e}),this.#s(this.#n.messages)}cancel(){this.#l=!0,this.#n.abortRun()}async#c(){this.#l=!1;try{await this.#u(),this.#l&&this.#p()}catch(e){this.#l||Mg(e)?this.#p():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#p(){this.#s(this.#n.messages),this.#e.onCancelled()}async#u(){let e;for(let n=0;n<Uo;n+=1){if(this.#l)return;let r=[],i={terminal:!1,errored:!1,interrupts:[]},o={tools:this.#t(),context:this.#i()};if(e!==void 0&&(o.resume=e),await this.#n.runAgent(o,this.#h(r,i)),e=void 0,this.#s(this.#n.messages),this.#l)return;if(!i.terminal)throw new ho(this.#o);if(i.errored)return;if(i.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(i.interrupts);if(this.#l)return;e=Fc(i.interrupts,a);continue}if(this.#r===null||r.length===0)return;let s=!1;for(let a of r){let l=await this.#r(a);if(l!==null){if(l.halt===!0)return;this.#n.addMessage({id:Oe(),role:"tool",content:l.content,toolCallId:a.id}),this.#s(this.#n.messages),s=!0}}if(!s)return}}#h(e,n){let r=this.#e;return{onRunInitialized(){r.onRunStart()},onTextMessageContentEvent({textMessageBuffer:i}){r.onTextDelta(i)},onTextMessageEndEvent({textMessageBuffer:i}){r.onTextEnd(i)},onToolCallEndEvent({event:i,toolCallName:o,toolCallArgs:s}){let a={id:i.toolCallId,name:o,args:s};e.push(a),r.onToolCall(a)},onToolCallResultEvent({event:i}){r.onToolResult(i.toolCallId,i.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:i}){r.onReasoningDelta(i)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(i){n.terminal=!0,i.outcome==="interrupt"&&(n.interrupts=i.interrupts)},onRunErrorEvent({event:i}){n.terminal=!0,n.errored=!0,r.onError(i.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Mg(t){return t instanceof Error&&t.name==="AbortError"}function ha(t){let e=t.attachments;return Array.isArray(e)?e.filter(Lg):[]}function Lg(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.name=="string"&&typeof e.mime=="string"&&typeof e.size=="number"&&(e.url===void 0||typeof e.url=="string")}var ma="ag-ui-chat",lr="thread",ga="threads",mo="messages:",go="checkpoint:",Pg=60,Dg=100,Ug="New conversation",ht=class{#n;constructor(e=""){this.#n=e===""?ma:`${ma}@${e}`,e!==""&&this.#a()}threadId(){let e=this.#r(lr),n=sessionStorage.getItem(e);if(n!==null)return n;let r=Oe();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#s(this.#r(mo+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(mo+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#s(this.#r(go+e))}saveCheckpoint(e,n){let r=this.#r(go+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(mo+e)),sessionStorage.removeItem(this.#r(go+e)),this.#i(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(lr))===e&&sessionStorage.removeItem(this.#r(lr))}listThreads(){let e=this.#t().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:i,preview:o})=>({threadId:n,title:r,updatedAt:i,preview:o}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(this.#r(lr),e)}renameThread(e,n){let r=this.#t(),i=r.find(o=>o.threadId===e);i!==void 0&&(i.title=n,i.titleCustom=!0,this.#i(r))}#e(e,n){let r=this.#t(),i=r.find(a=>a.threadId===e),o=Gg(n),s=Date.now();i===void 0?r.push({threadId:e,title:Cu(n),titleCustom:!1,preview:o,updatedAt:s}):(i.preview=o,i.updatedAt=s,i.titleCustom||(i.title=Cu(n))),this.#i(r)}#t(){return this.#s(this.#r(ga))??[]}#i(e){let n=this.#r(ga);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${ma}:`,n=[];for(let r=0;r<sessionStorage.length;r+=1){let i=sessionStorage.key(r);if(i===null||!i.startsWith(e))continue;let o=i.slice(e.length);Hg(o)&&n.push([i,this.#r(o)])}for(let[r,i]of n){let o=sessionStorage.getItem(r);o!==null&&sessionStorage.getItem(i)===null&&sessionStorage.setItem(i,o),sessionStorage.removeItem(r)}}#s(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function Hg(t){return t===lr||t===ga||t.startsWith(mo)||t.startsWith(go)}function Cu(t){for(let e of t)if(e.role==="user"){let n=Nu(e.content);if(n!=="")return Ru(n,Pg)}return Ug}function Gg(t){for(let e of[...t].reverse()){let n=Nu(e.content);if(n!=="")return Ru(n,Dg)}return""}function Nu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Ru(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function va(t){return new $c({url:t.endpoint,headers:t.headers??{},initialState:{...t.initialState??{}},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let i=new Headers(n?.headers);for(let[o,s]of Object.entries(r))i.set(o,s);return fetch(e,{...n,headers:i})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var cr=class{#n;#e;#t;#i=new Set;#r=new Map;constructor(e,n=()=>({}),r=new ht){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r}threadId(){return this.#t.threadId()}setActiveThread(e){this.#t.setActiveThread(e)}saveMessages(e,n){this.#t.saveMessages(e,n)}loadCheckpoint(e){return this.#t.loadCheckpoint(e)}saveCheckpoint(e,n){this.#t.saveCheckpoint(e,n)}renameThread(e,n){this.#t.renameThread(e,n),this.#r.set(e,n),this.#c(e,"PATCH",{title:n})}clear(e){this.#t.clear(e),this.#i.add(e),this.#c(e,"DELETE")}async listThreads(){let e=await this.#a();return e===null?this.#t.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#o(n))}async loadMessages(e){let n=await this.#l(this.#n+encodeURIComponent(e)+"/");if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#s(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#a(){let e=await this.#l(this.#n);if(e===null||!e.ok)return null;let n=await this.#s(e);return n===null?null:n.threads??[]}async#s(e){try{return await e.json()}catch{return null}}#o(e){return{threadId:e.thread_id,title:this.#r.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#l(e){try{return await fetch(e,{headers:this.#e()})}catch{return null}}async#c(e,n,r){let i=this.#e();try{await fetch(this.#n+encodeURIComponent(e)+"/",{method:n,headers:r===void 0?i:{...i,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};var ur=class{#n;#e;constructor(e,n=()=>({})){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n}async list(){try{let e=await fetch(this.#n,{method:"GET",headers:{Accept:"application/json",...this.#e()}});return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#t("resume",e)}forkUrl(e){return this.#t("fork",e)}#t(e,n){return`${this.#n.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};async function ba(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,{method:"POST",headers:{...e.headers??{}},body:n});if(!r.ok)throw new Error(await Fg(r));let i=await r.json();if(typeof i=="object"&&i!==null&&typeof i.text=="string")return i.text;throw new Error("transcription returned an unreadable response")}async function Fg(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function ya(t,e){return new Promise((n,r)=>{let i=new FormData;i.append("file",t);let o=new XMLHttpRequest;o.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))o.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&o.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),o.addEventListener("load",()=>{if(o.status>=200&&o.status<300)try{n($g(JSON.parse(o.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(zg(o)))}),o.addEventListener("error",()=>r(new Error("upload failed"))),o.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>o.abort()),o.send(i)})}function $g(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,i=e.mime,o=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof i!="string"||typeof o!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:i,size:o,url:s}:{id:n,name:r,mime:i,size:o}}function zg(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var Ou="ag-ui-chat:collapsed",Mu="ag-ui-chat:theme",dr=class extends HTMLElement{agentFactory=va;headers={};allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#ne().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...Yo(this.getPageMap,this.autoInjectPageMap),...this.#Me()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new ht;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};strings={};resolvePageTarget=e=>document.querySelector(e);#n={};#e=ne;#t=new Un;#i=new Map;#r=new Set;#a;#s;#o;#l;#c;#p;#u;#h;#f;#k=null;#E;#m;#g;#D;#T;#S;#I;#_=null;#U;#B=null;#L=[];#C=null;#R={};#H=!1;#b=null;#y=null;#V=0;#G=null;#w=null;#N=null;#d="";#O="";#j=0;#W=[];#Q=[];#ee=[];#te=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#s=document.createElement("div"),this.#o=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#p=document.createElement("span"),this.#E=document.createElement("div"),this.#m=document.createElement("button"),this.#g=document.createElement("input"),this.#D=document.createElement("div"),this.#U=document.createElement("span"),this.#T=document.createElement("button"),this.#S=document.createElement("button"),this.#I=document.createElement("div"),this.#u=new co(e=>this.#Ge(e)),this.#h=new po({onSelect:e=>{this.#Fe(e)},onNew:()=>{this.newChat(),this.#F()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#F()},onDelete:e=>{this.#$e(e)}}),this.#f=new er((e,n)=>{this.#ve(e,n)})}#q(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#k===null&&(this.#k=new ur(e,()=>this.headers)),this.#k)}async#ve(e,n){let r=this.#q();if(r===null)return;let i=this.#l.value.trim();if(i==="")return;this.#l.value="";let o=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:o,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#d,initialMessages:[]});await new Cn({agent:s,handlers:this.#he(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:l=>this.#pe(l),resolveInterrupts:l=>this.#fe(l),connectionLostMessage:this.#e.connectionLost}).send(i)}async#be(){let e=this.#q();this.#f.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text"]}attributeChangedCallback(e,n,r){this.#p.textContent=r??this.#e.title}registerTool(e){this.#t.register(e)}get sharedState(){return this.#C?.state??this.#R}set sharedState(e){this.#R={...e},this.#C?.setState(this.#R)}registerPageState(e){for(let n of Ar(e))this.#t.register(n)}registerStateHook(e){this.registerPageState(e)}#ye(){return this.routeMap.length===0?[]:Qo(()=>this.routeMap,()=>this.navigate)}#xe(){let e=this.getPageMap;return e===null?[]:[{name:"read_page",description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[Ne]:"Read the page"},handler:()=>e()}]}#Ee(){let e=this.getAttribute("data-page-actions");if(e===null)return[];let n=new Set(e.split(",").map(r=>r.trim()).filter(r=>r!==""));return Zo(n,r=>this.resolvePageTarget(r))}#ne(){return[...this.#ye(),...this.#xe(),...this.#Ee(),...this.#Te()]}#Te(){return this.askUser?[{name:"ask_user",description:"Ask the user a question and wait for their answer. Provide `options` for a multiple-choice prompt; set `allow_custom` to also accept a free-text answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user."},options:{type:"array",items:{type:"string"},description:"Preset choices offered as radio buttons."},allow_custom:{type:"boolean",description:"Allow a free-text answer in addition to any options."}},required:["question"]},handler:e=>this.#Se(e)}]:[]}async#Se(e){let r={question:typeof e.question=="string"?e.question:""},i=e.options;Array.isArray(i)&&(r.options=i.filter(a=>typeof a=="string")),e.allow_custom===!0&&(r.allowCustom=!0),this.#b=new AbortController;let o=this.#b.signal;this.#x();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:o}):await qs(this.#A(),r,{signal:o,strings:this.#e});return this.#b=null,this.#v(),this.#o.scrollTop=this.#o.scrollHeight,s}#re(e){let n=this.#ne().find(r=>r.name===e);return n!==void 0?n:this.#t.has(e)?this.#t.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===ze.INLINE||e===ze.MINIMAL||e===ze.COMPACT?e:ze.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#O=this.id!==""?this.id:this.endpoint,this.#e=es({...this.#we(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#ie(Mu);e!==null&&this.setAttribute("theme",e)}this.#je(),this.#h.setStrings(this.#e),this.#f.setStrings(this.#e),this.#ie(Ou)==="1"&&this.setAttribute("collapsed",""),this.#ce(),this.#De(),this.#Pe(),this.#O!==""&&this.conversationStore instanceof ht&&(this.conversationStore=new ht(this.#O)),this.#Le(),this.#_e(),this.#ke(),this.#d=this.conversationStore.threadId(),this.#se()}disconnectedCallback(){this.#M(),this.#_?.dispose(),this.#B?.dispose()}#we(){let e=this.getAttribute("data-strings");if(e===null)return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#_e(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#Ae(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"";this.#_=new Qi({upload:n,maxBytes:this.#Ne(),accept:r,strings:this.#e}),this.#D.appendChild(this.#_.element),this.#g.accept=r,this.#m.hidden=!1,this.#Oe()}#Ae(e){return e===null?null:(n,r,i)=>ya(n,{url:e,headers:this.headers,onProgress:r,signal:i})}#ke(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#Ie(e);n!==null&&(this.#B=new fo({transcribe:n,onText:r=>this.#Ce(r),strings:this.#e}),this.#U.appendChild(this.#B.element))}#Ie(e){return e===null?null:n=>ba(n,{url:e,headers:this.headers})}#Ce(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#ue(),this.#l.focus()}#Ne(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Ho;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Ho}#Re(){let e=this.#g.files;if(e!==null)for(let n of Array.from(e))this.#_?.add(n);this.#g.value=""}#Oe(){this.#s.addEventListener("dragover",e=>{e.preventDefault(),this.#s.classList.add("chat--dragover")}),this.#s.addEventListener("dragleave",()=>{this.#s.classList.remove("chat--dragover")}),this.#s.addEventListener("drop",e=>{e.preventDefault(),this.#s.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#_?.add(r)})}#Me(){return this.#L.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#L.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
|
|
1477
1553
|
`)}
|
|
1478
|
-
Use the read_attachment tool with an id to read a file's contents.`}]}#_e(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new lr(e,()=>this.headers,this.conversationStore))}async#Ae(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#n=qi(await n.json())}catch{}}setSkills(e){this.#Y=e,this.#B()}#ke(){this.#u.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#u.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#Z=this.#Ie(),this.#B(),this.#Ce()}#Ie(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Li(JSON.parse(e))}catch{return[]}}async#Ce(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#K=Li(await n.json()),this.#B()}catch{}}#B(){let e=new Map;for(let n of[...this.#K,...this.#Z,...this.#Y])e.set(n.name,n);this.#u.setSkills([...e.values()])}#Ne(e){let{text:n,missing:r}=Fa(e.prompt,this.skillContext());if(r.length>0){this.#d.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#d.hidden=!1;return}this.#d.hidden=!0,this.#l.value=n,e.sendImmediately===!0?this.#q():this.#l.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(this.#j(Cu),e?"1":"0"),this.#ie(),this.dispatchEvent(new CustomEvent(Ni,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),sessionStorage.setItem(this.#j(Nu),e),this.#te()}#j(e){return this.#I===""?e:`${e}:${this.#I}`}#ee(e){let n=sessionStorage.getItem(this.#j(e));return n!==null||this.#I===""?n:sessionStorage.getItem(e)}#te(){let e=this.getAttribute("theme")==="dark";this.#E.textContent=e?"\u2600\uFE0F":"\u{1F319}"}newChat(){this.#C(),this.conversationStore.clear(this.#f),this.#V(),this.#f=this.conversationStore.threadId(),this.#O(!1)}#V(){this.#R=null,this.#y=null,this.#S=null,this.#k=null,this.#x(),this.#i.clear(),this.#r.clear(),this.#z=[],this.#N=[],this.#w?.clear(),this.#o.replaceChildren(this.#A),this.#v()}async#Re(e){e!==this.#f&&(this.#C(),this.#V(),this.conversationStore.setActiveThread(e),this.#f=e,this.#O(!1),await this.#ne())}#Oe(e){let n=e===this.#f;n&&this.#C(),this.conversationStore.clear(e),n&&(this.#V(),this.#f=this.conversationStore.threadId(),this.#O(!1)),this.#U()}async#U(){this.#m.setThreads(await this.conversationStore.listThreads(),this.#f)}async#ne(){this.#$+=1;let e=this.#$,n=await this.conversationStore.loadMessages(this.#f);if(e!==this.#$)return;if(n!==null){this.#z=n;for(let o of n)this.#Me(o)}let r=this.conversationStore.loadCheckpoint(this.#f);r!==null&&await this.#Pe(r)}#Me(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Ye.USER){let r=ua(e);if(n!==""||r.length>0){let o=this.appendMessage(Ye.USER,n);r.length>0&&o.appendChild(Ji(r))}return}if(e.role===Ye.ASSISTANT){n!==""&&this.appendMessage(Ye.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let o of r)this.#X({id:o.id,name:o.function.name,args:this.#Le(o.function.arguments)});return}if(e.role==="tool"){let r=this.#i.get(e.toolCallId);r!==void 0&&r.settle(ce.DONE,e.content)}}#Le(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#re(e){this.getAttribute("data-text-animation")==="word"&&Tu(e)}async#Pe(e){this.conversationStore.saveCheckpoint(this.#f,null);let n=this.#ae();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===Ye.ASSISTANT?(r.innerHTML=ii(n,{allowImages:this.allowImages}),this.#_().appendChild(r)):(this.#S=null,r.textContent=n,this.#o.appendChild(r)),this.#v(),this.#o.scrollTop=this.#o.scrollHeight,r}#_(){if(this.#S===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#S=e,this.#o.appendChild(e),this.#v()}return this.#S}#De(){let e=document.createElement("style");e.textContent=Su,this.#s.className="chat",this.#s.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#h;r.className="header-title",r.setAttribute("part","title"),r.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&n.append(this.#oe("icon","icon",null));let o=document.createElement("slot");o.name="header-actions";let i=document.createElement("div");i.className="header-controls",i.setAttribute("part","header-controls");let s=this.#W("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>{this.#U(),this.#m.open()});let a=this.#W("new",this.#e.newChat,"\u271A");a.addEventListener("click",()=>this.newChat());let l=this.#W("collapse",this.#e.collapse,"\u2014");l.addEventListener("click",()=>this.toggleCollapsed()),i.append(s,a),this.getAttribute("data-theme-toggle")!==null&&(this.#E.type="button",this.#E.className="header-btn header-btn--theme",this.#E.setAttribute("part","header-button theme-toggle"),this.#E.title=this.#e.toggleTheme,this.#E.setAttribute("aria-label",this.#e.toggleTheme),this.#E.addEventListener("click",()=>this.toggleTheme()),this.#te(),i.append(this.#E)),i.append(l),n.append(r,o,i),this.#o.className="messages",this.#o.setAttribute("part","messages"),this.#o.setAttribute("role","log"),this.#o.setAttribute("aria-live","polite"),this.#o.setAttribute("aria-label",this.#e.conversation),this.#A.className="empty",this.#A.setAttribute("part","empty");let c=document.createElement("slot");c.name="empty",this.#A.append(c),this.#o.append(this.#A);let p=document.createElement("div");p.className="input-row",p.setAttribute("part","composer"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=2,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",b=>this.#Ue(b)),this.#l.addEventListener("input",()=>this.#se()),this.#c.className="send",this.#c.type="button",this.#c.setAttribute("part","send"),this.#c.textContent=this.#e.send,this.#c.setAttribute("aria-label",this.#e.send),this.#c.dataset.state="idle",this.#c.addEventListener("click",()=>{if(this.#P){this.#C();return}this.#q()}),this.#d.className="skill-hint",this.#d.setAttribute("part","skill-hint"),this.#d.hidden=!0,this.#p.className="attach-btn",this.#p.type="button",this.#p.setAttribute("part","attach-button"),this.#p.textContent="\u{1F4CE}",this.#p.title=this.#e.attachFiles,this.#p.setAttribute("aria-label",this.#e.attachFiles),this.#p.hidden=!0,this.#p.addEventListener("click",()=>this.#g.click()),this.#g.className="attach-input",this.#g.type="file",this.#g.multiple=!0,this.#g.hidden=!0,this.#g.addEventListener("change",()=>this.#Te()),this.#M.className="attachment-slot",this.#L.className="voice-slot";let m=document.createElement("slot");m.name="footer",p.append(this.#p,this.#L,this.#l,this.#c,this.#g),this.#s.append(n,this.#o,this.#u.palette,this.#u.chips,this.#d,this.#M,p,m,this.#m.element),this.#T.className="rail",this.#T.type="button",this.#T.setAttribute("part","launcher"),this.#T.setAttribute("aria-label",this.#e.expand),this.#T.append(this.#oe("launcher","launcher-icon","\u{1F4AC}")),this.#T.addEventListener("click",()=>this.setCollapsed(!1)),this.#a.append(e,this.#s,this.#T)}#W(e,n,r){let o=document.createElement("button");return o.type="button",o.className=`header-btn header-btn--${e}`,o.setAttribute("part",`header-button ${e}-button`),o.title=n,o.setAttribute("aria-label",n),o.textContent=r,o}#oe(e,n,r){let o=document.createElement("span");o.className="icon-holder",o.setAttribute("part",n);let i=document.createElement("slot");i.name=e;let s=this.getAttribute("data-icon-url");if(s!==null){let a=document.createElement("img");a.className="icon-img",a.src=s,a.alt="",i.append(a)}else r!==null&&i.append(document.createTextNode(r));return o.append(i),o}#ie(){this.#T.setAttribute("aria-expanded",String(!this.collapsed))}#v(){this.#A.hidden=this.#o.childElementCount>1}#se(){this.#u.onInput(this.#l.value),this.#d.hidden=!0}#Ue(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#P){e.preventDefault(),this.#C();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#q())}#C(){this.#b?.abort(),this.#R?.cancel()}#O(e){this.#P=e;let n=e?this.#e.stop:this.#e.send;this.#c.textContent=n,this.#c.setAttribute("aria-label",n),this.#c.dataset.state=e?"running":"idle"}async#q(){if(this.#P)return;let e=this.#l.value.trim(),n=this.#w?.readyRefs()??[];if(e===""&&n.length===0)return;let r=this.appendMessage(Ye.USER,e);n.length>0&&r.appendChild(Ji(n)),this.#l.value="",this.#w?.clearReady(),this.#N=n,this.dispatchEvent(new CustomEvent(Ci,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#He(e,n)}async#He(e,n){this.endpoint!==""&&await this.#ae().send(e,n)}#ae(){if(this.#R===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#f,initialMessages:this.#z});this.#R=new sr({agent:e,handlers:this.#ze(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#Fe(n),resolveInterrupts:n=>this.#$e(n),onPersist:n=>this.conversationStore.saveMessages(this.#f,n),connectionLostMessage:this.#e.connectionLost})}return this.#R}async#Ge(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Pi(n.parameters)}async#Fe(e){let n=this.#X(e);this.#i.delete(e.id);let r=this.#Q(e.name);if(r===null)return this.#r.has(e.id)||n.settle(ce.DONE,this.#e.noResult),null;if(await this.#Ge(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[Ri];typeof s=="string"&&(i.message=s),this.#b=new AbortController;let a=$s(this.#o,i,{signal:this.#b.signal,strings:this.#e});this.#v(),this.#o.scrollTop=this.#o.scrollHeight;let l=await a;if(this.#b=null,!l){let c=this.#e.declinedAction;return n.settle(ce.DECLINED,c),this.#H(),{content:c}}}let o=Di(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#f,{toolCallId:e.id});try{let i=await r.handler(e.args);if(o)return n.settle(ce.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(i??null);return n.settle(ce.DONE,s),this.#H(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#f,null);let s=i instanceof Error?i.message:String(i);return n.settle(ce.ERROR,s),this.#H(),{content:`Error: ${s}`,error:s}}}async#$e(e){let n={};this.#b=new AbortController,this.#x();for(let r of e){let o={};r.message!==void 0&&(o.message=r.message);let i=r.toolCallId!==void 0?this.#i.get(r.toolCallId):void 0,s=i?.element.getAttribute("data-tool-name");s!=null&&(o.toolName=s);let a=this.#b.signal,l=this.approvalRenderer!==null?await this.approvalRenderer(o,{signal:a}):await Yi(this.#_(),o,{signal:a,strings:this.#e});this.#v(),this.#o.scrollTop=this.#o.scrollHeight,l?n[r.id]={status:"resolved",payload:{approved:!0}}:(n[r.id]={status:"cancelled"},i?.settle(ce.DECLINED,this.#e.declinedAction))}return this.#b=null,n}#ze(){return{onRunStart:()=>{this.#O(!0),this.#_(),this.#H()},onReasoningStart:()=>{this.#x(),this.#le()},onReasoningDelta:e=>{this.#le().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#x(),this.#k?.collapse(),this.#ce(e),this.#F+=1},onTextEnd:e=>{let n=this.#ce(e);this.#F<=1&&this.#re(n),this.#y=null},onToolCall:e=>{this.#x(),this.#X(e)},onToolResult:(e,n)=>{let r=this.#i.get(e);r!==void 0&&(r.settle(ce.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#x(),this.#y=null},onError:e=>{this.#x(),this.#re(this.appendMessage(Ye.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#y=null},onCancelled:()=>{this.#x(),this.#Be(),this.#y=null},onSettled:()=>{this.#x(),this.#O(!1),this.#y=null,this.#N=[];for(let e of this.#i.values())e.settled||e.settle(ce.DONE,this.#e.noResult);this.#S!==null&&this.#S.childElementCount===0&&(this.#S.remove(),this.#v()),this.#S=null,this.#k=null}}}#Be(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#_().appendChild(e),this.#v(),this.#o.scrollTop=this.#o.scrollHeight}#H(){if(this.#D!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#D=e,this.#_().appendChild(e),this.#v(),this.#o.scrollTop=this.#o.scrollHeight}#x(){this.#D?.remove(),this.#D=null}#le(){if(this.#k===null){this.#k=new ai(this.#e);let e=this.#_();e.insertBefore(this.#k.element,e.firstChild),this.#v(),this.#o.scrollTop=this.#o.scrollHeight}return this.#k}#ce(e){return this.#y===null&&(this.#y=this.appendMessage(Ye.ASSISTANT,""),this.#F=0),this.#y.innerHTML=ii(e,{allowImages:this.allowImages}),this.#o.scrollTop=this.#o.scrollHeight,this.#y}#X(e){let n=this.#i.get(e.id);if(n!==void 0)return n;let r=this.#Q(e.name)?.parameters[Ne],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??zs(e.name),i=new ir(e.name,e.args,this.toolDisplay,o,this.#e);return this.#i.set(e.id,i),this.#_().appendChild(i.element),this.#v(),this.#o.scrollTop=this.#o.scrollHeight,i}};function Gg(){customElements.get(Er)===void 0&&customElements.define(Er,cr)}async function Fg(t,e,n={}){lt(t),await Gi(t,{flashMs:n.flashMs??0}),await Ui(t,e,n)}async function $g(t,e={}){lt(t),await Hi(t,e)}async function zg(t,e={}){lt(t),await $i(t,e)}async function Bg(t,e,n={}){lt(t),await zi(t,e,n)}async function jg(t,e,n={}){lt(t),await Bi(t,e,n)}function Vg(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Un(t,!!e):kt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Wg="0.11.0";export{cr as AgUiChat,sr as AgUiClient,Dn as ClientToolRegistry,ui as ConnectionLostError,re as DEFAULT_UI_STRINGS,Er as ELEMENT_TAG,Oi as MAX_TOOL_ROUNDS,Ye as MESSAGE_ROLE,ji as PAGE_ACTIONS,lr as RemoteConversationStore,Ci as SUBMIT_EVENT,ht as SessionStorageStore,Ni as TOGGLE_EVENT,ce as TOOL_CALL_STATUS,ze as TOOL_DISPLAY,ir as ToolCallCard,Wg as VERSION,Ri as X_CONFIRM_KEY,Ln as X_DESTRUCTIVE_KEY,Pn as X_NAVIGATES_KEY,Ne as X_SUMMARY_KEY,$g as clickElement,fa as createHttpAgent,Vi as createPageActionTools,Wi as createPageMapContext,Xi as createRouteTools,Ki as createStateHookTools,Gg as defineAgUiChat,Fg as fillField,Gi as focusWithFlash,Hi as highlightThenClick,Pi as isDestructive,Di as isNavigates,Zi as mergeUiStrings,ua as messageAttachments,qi as parseToolCatalog,Ba as prefersReducedMotion,zg as pressButton,$i as pressThenClick,zs as prettifyToolName,ii as renderMarkdown,Yi as requestApproval,$s as requestConfirmation,Bs as requestQuestion,lt as scrollIntoCenterView,Bg as selectControl,zi as selectOption,Vg as setControlValue,Un as setNativeChecked,kt as setNativeValue,jg as toggleCheckbox,Bi as toggleControl,ha as transcribeAudio,Ui as typeInto,ma as uploadAttachment};
|
|
1554
|
+
Use the read_attachment tool with an id to read a file's contents.`}]}#Le(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new cr(e,()=>this.headers,this.conversationStore))}async#Pe(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#n=Jo(await n.json())}catch{}}setSkills(e){this.#te=e,this.#X()}#De(){this.#u.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#u.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#ee=this.#Ue(),this.#X(),this.#He()}#Ue(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Go(JSON.parse(e))}catch{return[]}}async#He(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#Q=Go(await n.json()),this.#X()}catch{}}#X(){let e=new Map;for(let n of[...this.#Q,...this.#ee,...this.#te])e.set(n.name,n);this.#u.setSkills([...e.values()])}#Ge(e){let{text:n,missing:r}=Va(e.prompt,this.skillContext());if(r.length>0){this.#E.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#E.hidden=!1;return}this.#E.hidden=!0,this.#l.value=n,e.sendImmediately===!0?this.#Y():this.#l.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(this.#K(Ou),e?"1":"0"),this.#ce(),this.dispatchEvent(new CustomEvent(Lo,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),sessionStorage.setItem(this.#K(Mu),e),this.#oe()}#K(e){return this.#O===""?e:`${e}:${this.#O}`}#ie(e){let n=sessionStorage.getItem(this.#K(e));return n!==null||this.#O===""?n:sessionStorage.getItem(e)}#oe(){let e=this.getAttribute("theme")==="dark";this.#T.textContent=e?"\u2600\uFE0F":"\u{1F319}"}newChat(){this.#M(),this.conversationStore.clear(this.#d),this.#Z(),this.#d=this.conversationStore.threadId(),this.#P(!1)}#Z(){this.#C=null,this.#y=null,this.#w=null,this.#N=null,this.#x(),this.#i.clear(),this.#r.clear(),this.#W=[],this.#L=[],this.#_?.clear(),this.#o.replaceChildren(this.#I),this.#v()}async#Fe(e){e!==this.#d&&(this.#M(),this.#Z(),this.conversationStore.setActiveThread(e),this.#d=e,this.#P(!1),await this.#se())}#$e(e){let n=e===this.#d;n&&this.#M(),this.conversationStore.clear(e),n&&(this.#Z(),this.#d=this.conversationStore.threadId(),this.#P(!1)),this.#F()}async#F(){this.#h.setThreads(await this.conversationStore.listThreads(),this.#d)}async#se(){this.#j+=1;let e=this.#j,n=await this.conversationStore.loadMessages(this.#d);if(e!==this.#j)return;if(n!==null){this.#W=n;for(let i of n)this.#ze(i)}let r=this.conversationStore.loadCheckpoint(this.#d);r!==null&&await this.#Ve(r)}#ze(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Ye.USER){let r=ha(e);if(n!==""||r.length>0){let i=this.appendMessage(Ye.USER,n);r.length>0&&i.appendChild(ns(r))}return}if(e.role===Ye.ASSISTANT){n!==""&&this.appendMessage(Ye.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let i of r)this.#J({id:i.id,name:i.function.name,args:this.#Be(i.function.arguments)});return}if(e.role==="tool"){let r=this.#i.get(e.toolCallId);r!==void 0&&r.settle(ce.DONE,e.content)}}#Be(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#ae(e){this.getAttribute("data-text-animation")==="word"&&Au(e)}async#Ve(e){this.conversationStore.saveCheckpoint(this.#d,null);let n=this.#de();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===Ye.ASSISTANT?(r.innerHTML=lo(n,{allowImages:this.allowImages}),this.#A().appendChild(r)):(this.#w=null,r.textContent=n,this.#o.appendChild(r)),this.#v(),this.#o.scrollTop=this.#o.scrollHeight,r}#A(){if(this.#w===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#w=e,this.#o.appendChild(e),this.#v()}return this.#w}#je(){let e=document.createElement("style");e.textContent=ku,this.#s.className="chat",this.#s.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#p;r.className="header-title",r.setAttribute("part","title"),r.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&n.append(this.#le("icon","icon",null));let i=document.createElement("slot");i.name="header-actions";let o=document.createElement("div");o.className="header-controls",o.setAttribute("part","header-controls");let s=this.#$("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>{this.#F(),this.#h.open()});let a=this.#$("checkpoints",this.#e.checkpoints,"\u2B6F");a.addEventListener("click",()=>{this.#be(),this.#f.open()});let l=this.#$("new",this.#e.newChat,"\u271A");l.addEventListener("click",()=>this.newChat());let c=this.#$("collapse",this.#e.collapse,"\u2014");c.addEventListener("click",()=>this.toggleCollapsed()),this.#q()!==null?o.append(s,a,l):o.append(s,l),this.getAttribute("data-theme-toggle")!==null&&(this.#T.type="button",this.#T.className="header-btn header-btn--theme",this.#T.setAttribute("part","header-button theme-toggle"),this.#T.title=this.#e.toggleTheme,this.#T.setAttribute("aria-label",this.#e.toggleTheme),this.#T.addEventListener("click",()=>this.toggleTheme()),this.#oe(),o.append(this.#T)),o.append(c),n.append(r,i,o),this.#o.className="messages",this.#o.setAttribute("part","messages"),this.#o.setAttribute("role","log"),this.#o.setAttribute("aria-live","polite"),this.#o.setAttribute("aria-label",this.#e.conversation),this.#I.className="empty",this.#I.setAttribute("part","empty");let f=document.createElement("slot");f.name="empty",this.#I.append(f),this.#o.append(this.#I);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=2,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",h=>this.#We(h)),this.#l.addEventListener("input",()=>this.#ue()),this.#c.className="send",this.#c.type="button",this.#c.setAttribute("part","send"),this.#c.textContent=this.#e.send,this.#c.setAttribute("aria-label",this.#e.send),this.#c.dataset.state="idle",this.#c.addEventListener("click",()=>{if(this.#H){this.#M();return}this.#Y()}),this.#E.className="skill-hint",this.#E.setAttribute("part","skill-hint"),this.#E.hidden=!0,this.#m.className="attach-btn",this.#m.type="button",this.#m.setAttribute("part","attach-button"),this.#m.textContent="\u{1F4CE}",this.#m.title=this.#e.attachFiles,this.#m.setAttribute("aria-label",this.#e.attachFiles),this.#m.hidden=!0,this.#m.addEventListener("click",()=>this.#g.click()),this.#g.className="attach-input",this.#g.type="file",this.#g.multiple=!0,this.#g.hidden=!0,this.#g.addEventListener("change",()=>this.#Re()),this.#D.className="attachment-slot",this.#U.className="voice-slot";let b=document.createElement("slot");b.name="footer",m.append(this.#m,this.#U,this.#l,this.#c,this.#g),this.#s.append(n,this.#o,this.#u.palette,this.#u.chips,this.#E,this.#D,m,b,this.#h.element,this.#f.element),this.#S.className="rail",this.#S.type="button",this.#S.setAttribute("part","launcher"),this.#S.setAttribute("aria-label",this.#e.expand),this.#S.append(this.#le("launcher","launcher-icon","\u{1F4AC}")),this.#S.addEventListener("click",()=>this.setCollapsed(!1)),this.#a.append(e,this.#s,this.#S)}#$(e,n,r){let i=document.createElement("button");return i.type="button",i.className=`header-btn header-btn--${e}`,i.setAttribute("part",`header-button ${e}-button`),i.title=n,i.setAttribute("aria-label",n),i.textContent=r,i}#le(e,n,r){let i=document.createElement("span");i.className="icon-holder",i.setAttribute("part",n);let o=document.createElement("slot");o.name=e;let s=this.getAttribute("data-icon-url");if(s!==null){let a=document.createElement("img");a.className="icon-img",a.src=s,a.alt="",o.append(a)}else r!==null&&o.append(document.createTextNode(r));return i.append(o),i}#ce(){this.#S.setAttribute("aria-expanded",String(!this.collapsed))}#v(){this.#I.hidden=this.#o.childElementCount>1}#ue(){this.#u.onInput(this.#l.value),this.#E.hidden=!0}#We(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#H){e.preventDefault(),this.#M();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#Y())}#M(){this.#b?.abort(),this.#C?.cancel()}#P(e){this.#H=e;let n=e?this.#e.stop:this.#e.send;this.#c.textContent=n,this.#c.setAttribute("aria-label",n),this.#c.dataset.state=e?"running":"idle"}async#Y(){if(this.#H)return;let e=this.#l.value.trim(),n=this.#_?.readyRefs()??[];if(e===""&&n.length===0)return;let r=this.appendMessage(Ye.USER,e);n.length>0&&r.appendChild(ns(n)),this.#l.value="",this.#_?.clearReady(),this.#L=n,this.dispatchEvent(new CustomEvent(Mo,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#qe(e,n)}async#qe(e,n){this.endpoint!==""&&await this.#de().send(e,n)}#de(){if(this.#C===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#d,initialMessages:this.#W,initialState:this.#R});this.#C=new Cn({agent:e,handlers:this.#he(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#pe(n),resolveInterrupts:n=>this.#fe(n),onPersist:n=>this.conversationStore.saveMessages(this.#d,n),onStateChanged:n=>this.#Xe(n),connectionLostMessage:this.#e.connectionLost})}return this.#C}#Xe(e){this.#R={...e},this.dispatchEvent(new CustomEvent(Po,{detail:{state:this.#R},bubbles:!0,composed:!0}))}async#Ke(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Fo(n.parameters)}async#pe(e){let n=this.#J(e);this.#i.delete(e.id);let r=this.#re(e.name);if(r===null)return this.#r.has(e.id)||n.settle(ce.DONE,this.#e.noResult),null;if(await this.#Ke(e,r)){let o={toolName:e.name,args:e.args},s=r.parameters[Do];typeof s=="string"&&(o.message=s),this.#b=new AbortController;let a=js(this.#o,o,{signal:this.#b.signal,strings:this.#e});this.#v(),this.#o.scrollTop=this.#o.scrollHeight;let l=await a;if(this.#b=null,!l){let c=this.#e.declinedAction;return n.settle(ce.DECLINED,c),this.#z(),{content:c}}}let i=$o(r.parameters)&&this.navigate===null;i&&this.conversationStore.saveCheckpoint(this.#d,{toolCallId:e.id});try{let o=await r.handler(e.args);if(i)return n.settle(ce.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(o??null);return n.settle(ce.DONE,s),this.#z(),{content:s}}catch(o){i&&this.conversationStore.saveCheckpoint(this.#d,null);let s=o instanceof Error?o.message:String(o);return n.settle(ce.ERROR,s),this.#z(),{content:`Error: ${s}`,error:s}}}async#fe(e){let n={};this.#b=new AbortController,this.#x();for(let r of e){let i={};r.message!==void 0&&(i.message=r.message);let o=r.toolCallId!==void 0?this.#i.get(r.toolCallId):void 0,s=o?.element.getAttribute("data-tool-name");s!=null&&(i.toolName=s);let a=this.#b.signal,l=this.approvalRenderer!==null?await this.approvalRenderer(i,{signal:a}):await ts(this.#A(),i,{signal:a,strings:this.#e});this.#v(),this.#o.scrollTop=this.#o.scrollHeight,l?n[r.id]={status:"resolved",payload:{approved:!0}}:(n[r.id]={status:"cancelled"},o?.settle(ce.DECLINED,this.#e.declinedAction))}return this.#b=null,n}#he(){return{onRunStart:()=>{this.#P(!0),this.#A(),this.#z()},onReasoningStart:()=>{this.#x(),this.#me()},onReasoningDelta:e=>{this.#me().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#x(),this.#N?.collapse(),this.#ge(e),this.#V+=1},onTextEnd:e=>{let n=this.#ge(e);this.#V<=1&&this.#ae(n),this.#y=null},onToolCall:e=>{this.#x(),this.#J(e)},onToolResult:(e,n)=>{let r=this.#i.get(e);r!==void 0&&(r.settle(ce.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#x(),this.#y=null},onError:e=>{this.#x(),this.#ae(this.appendMessage(Ye.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#y=null},onCancelled:()=>{this.#x(),this.#Ze(),this.#y=null},onSettled:()=>{this.#x(),this.#P(!1),this.#y=null,this.#L=[];for(let e of this.#i.values())e.settled||e.settle(ce.DONE,this.#e.noResult);this.#w!==null&&this.#w.childElementCount===0&&(this.#w.remove(),this.#v()),this.#w=null,this.#N=null}}}#Ze(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#A().appendChild(e),this.#v(),this.#o.scrollTop=this.#o.scrollHeight}#z(){if(this.#G!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#G=e,this.#A().appendChild(e),this.#v(),this.#o.scrollTop=this.#o.scrollHeight}#x(){this.#G?.remove(),this.#G=null}#me(){if(this.#N===null){this.#N=new uo(this.#e);let e=this.#A();e.insertBefore(this.#N.element,e.firstChild),this.#v(),this.#o.scrollTop=this.#o.scrollHeight}return this.#N}#ge(e){return this.#y===null&&(this.#y=this.appendMessage(Ye.ASSISTANT,""),this.#V=0),this.#y.innerHTML=lo(e,{allowImages:this.allowImages}),this.#o.scrollTop=this.#o.scrollHeight,this.#y}#J(e){let n=this.#i.get(e.id);if(n!==void 0)return n;let r=this.#re(e.name)?.parameters[Ne],i=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??Ws(e.name),o=new ar(e.name,e.args,this.toolDisplay,i,this.#e);return this.#i.set(e.id,o),this.#A().appendChild(o.element),this.#v(),this.#o.scrollTop=this.#o.scrollHeight,o}};function Bg(){customElements.get(Sr)===void 0&&customElements.define(Sr,dr)}async function Vg(t,e,n={}){lt(t),await Vo(t,{flashMs:n.flashMs??0}),await zo(t,e,n)}async function jg(t,e={}){lt(t),await Bo(t,e)}async function Wg(t,e={}){lt(t),await Wo(t,e)}async function qg(t,e,n={}){lt(t),await qo(t,e,n)}async function Xg(t,e,n={}){lt(t),await Xo(t,e,n)}function Kg(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Hn(t,!!e):kt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Zg="0.13.0";export{dr as AgUiChat,Cn as AgUiClient,er as CheckpointMenu,Un as ClientToolRegistry,ho as ConnectionLostError,ne as DEFAULT_UI_STRINGS,Sr as ELEMENT_TAG,Uo as MAX_TOOL_ROUNDS,Ye as MESSAGE_ROLE,Ko as PAGE_ACTIONS,cr as RemoteConversationStore,ur as RunIndex,Po as STATE_EVENT,Mo as SUBMIT_EVENT,ht as SessionStorageStore,Lo as TOGGLE_EVENT,ce as TOOL_CALL_STATUS,ze as TOOL_DISPLAY,ar as ToolCallCard,Zg as VERSION,Do as X_CONFIRM_KEY,Pn as X_DESTRUCTIVE_KEY,Dn as X_NAVIGATES_KEY,Ne as X_SUMMARY_KEY,jg as clickElement,va as createHttpAgent,Zo as createPageActionTools,Yo as createPageMapContext,Ar as createPageStateTools,Qo as createRouteTools,od as createStateHookTools,Bg as defineAgUiChat,Vg as fillField,Vo as focusWithFlash,Bo as highlightThenClick,Fo as isDestructive,$o as isNavigates,es as mergeUiStrings,ha as messageAttachments,Jo as parseToolCatalog,qa as prefersReducedMotion,Wg as pressButton,Wo as pressThenClick,Ws as prettifyToolName,lo as renderMarkdown,ts as requestApproval,js as requestConfirmation,qs as requestQuestion,lt as scrollIntoCenterView,qg as selectControl,qo as selectOption,Kg as setControlValue,Hn as setNativeChecked,kt as setNativeValue,Xg as toggleCheckbox,Xo as toggleControl,ba as transcribeAudio,zo as typeInto,ya as uploadAttachment};
|
|
1479
1555
|
/*! Bundled license information:
|
|
1480
1556
|
|
|
1481
1557
|
fast-json-patch/module/helpers.mjs:
|